mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 05:09:21 +08:00
refactor: 调整系统初始化模块位置
This commit is contained in:
@@ -24,7 +24,3 @@ CREATE TABLE IF NOT EXISTS sys_license (
|
|||||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
UNIQUE KEY uk_jti (jti)
|
UNIQUE KEY uk_jti (jti)
|
||||||
) COMMENT '当前生效的 License';
|
) COMMENT '当前生效的 License';
|
||||||
|
|
||||||
-- 已有环境跳过初始化门禁(仅开发/存量部署)
|
|
||||||
INSERT INTO sys_init (id, step) VALUES (1, 3)
|
|
||||||
ON DUPLICATE KEY UPDATE step = GREATEST(step, 3);
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- 系统初始化增加显式完成标记,兼容旧 step>=3 语义
|
||||||
|
ALTER TABLE sys_init ADD COLUMN initialized BOOLEAN NOT NULL DEFAULT FALSE COMMENT '是否已完成初始化';
|
||||||
|
UPDATE sys_init SET initialized = TRUE WHERE step >= 3;
|
||||||
+21
@@ -24,6 +24,18 @@ public interface CompanyMemberService extends IService<CompanyMemberPO> {
|
|||||||
*/
|
*/
|
||||||
CompanyMemberVO create(Long userId, Long companyId, CompanyMemberRole role, Long positionId);
|
CompanyMemberVO create(Long userId, Long companyId, CompanyMemberRole role, Long positionId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建成员(指定创建人,用于系统初始化等无登录上下文场景)
|
||||||
|
*
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param role 角色
|
||||||
|
* @param positionId 职位ID(可空)
|
||||||
|
* @param createBy 创建人ID(可空)
|
||||||
|
* @return 成员VO
|
||||||
|
*/
|
||||||
|
CompanyMemberVO create(Long userId, Long companyId, CompanyMemberRole role, Long positionId, Long createBy);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建成员(DTO)
|
* 创建成员(DTO)
|
||||||
*
|
*
|
||||||
@@ -32,6 +44,15 @@ public interface CompanyMemberService extends IService<CompanyMemberPO> {
|
|||||||
*/
|
*/
|
||||||
CompanyMemberVO create(CreateCompanyMemberDTO dto);
|
CompanyMemberVO create(CreateCompanyMemberDTO dto);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建成员(DTO,指定创建人)
|
||||||
|
*
|
||||||
|
* @param dto 创建DTO
|
||||||
|
* @param createBy 创建人ID(可空)
|
||||||
|
* @return 成员VO
|
||||||
|
*/
|
||||||
|
CompanyMemberVO create(CreateCompanyMemberDTO dto, Long createBy);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新成员职位
|
* 更新成员职位
|
||||||
*
|
*
|
||||||
|
|||||||
+12
-2
@@ -49,16 +49,26 @@ public class CompanyMemberServiceImpl extends ServiceImpl<CompanyMemberMapper, C
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CompanyMemberVO create(Long userId, Long companyId, CompanyMemberRole role, Long positionId) {
|
public CompanyMemberVO create(Long userId, Long companyId, CompanyMemberRole role, Long positionId) {
|
||||||
|
return create(userId, companyId, role, positionId, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CompanyMemberVO create(Long userId, Long companyId, CompanyMemberRole role, Long positionId, Long createBy) {
|
||||||
CreateCompanyMemberDTO dto = new CreateCompanyMemberDTO();
|
CreateCompanyMemberDTO dto = new CreateCompanyMemberDTO();
|
||||||
dto.setUserId(userId);
|
dto.setUserId(userId);
|
||||||
dto.setCompanyId(companyId);
|
dto.setCompanyId(companyId);
|
||||||
dto.setRole(role != null ? role.getCode() : CompanyMemberRole.member.getCode());
|
dto.setRole(role != null ? role.getCode() : CompanyMemberRole.member.getCode());
|
||||||
dto.setPositionId(positionId);
|
dto.setPositionId(positionId);
|
||||||
return create(dto);
|
return create(dto, createBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public CompanyMemberVO create(CreateCompanyMemberDTO dto) {
|
public CompanyMemberVO create(CreateCompanyMemberDTO dto) {
|
||||||
|
return create(dto, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CompanyMemberVO create(CreateCompanyMemberDTO dto, Long createBy) {
|
||||||
// 检查是否已存在
|
// 检查是否已存在
|
||||||
LambdaQueryWrapper<CompanyMemberPO> wrapper = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<CompanyMemberPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
wrapper.eq(CompanyMemberPO::getUserId, dto.getUserId())
|
wrapper.eq(CompanyMemberPO::getUserId, dto.getUserId())
|
||||||
@@ -72,7 +82,7 @@ public class CompanyMemberServiceImpl extends ServiceImpl<CompanyMemberMapper, C
|
|||||||
// DTO 的 role 是 String,PO 是枚举;BeanUtils 无法自动转换,需显式映射
|
// DTO 的 role 是 String,PO 是枚举;BeanUtils 无法自动转换,需显式映射
|
||||||
member.setRole(CompanyMemberRole.fromCode(dto.getRole()));
|
member.setRole(CompanyMemberRole.fromCode(dto.getRole()));
|
||||||
member.setStatus(1);
|
member.setStatus(1);
|
||||||
member.setCreateBy(currentUserContext.getCurrentUserId());
|
member.setCreateBy(createBy);
|
||||||
|
|
||||||
this.save(member);
|
this.save(member);
|
||||||
return convertToVO(member);
|
return convertToVO(member);
|
||||||
|
|||||||
+1
-1
@@ -293,7 +293,7 @@ public class CompanyMenuServiceImpl extends ServiceImpl<CompanyMenuMapper, Compa
|
|||||||
.map(MenuPermissionVO::getPermissionId)
|
.map(MenuPermissionVO::getPermissionId)
|
||||||
.distinct()
|
.distinct()
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
companyPermissionService.grantPermissionsForCompany(companyId, permissionIds);
|
companyPermissionService.grantPermissionsForCompany(companyId, permissionIds, SecurityUtils.getCurrentUserId());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+8
@@ -59,6 +59,14 @@ public interface CompanyPermissionService {
|
|||||||
*/
|
*/
|
||||||
void grantPermissionsForCompany(Long companyId, List<Long> permissionIds);
|
void grantPermissionsForCompany(Long companyId, List<Long> permissionIds);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 给公司追加权限(指定创建人)
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param permissionIds 待追加的权限ID列表
|
||||||
|
* @param createBy 创建人ID(可空)
|
||||||
|
*/
|
||||||
|
void grantPermissionsForCompany(Long companyId, List<Long> permissionIds, Long createBy);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查公司是否有指定权限码(支持父→子权限继承)
|
* 检查公司是否有指定权限码(支持父→子权限继承)
|
||||||
* @param companyId 公司ID
|
* @param companyId 公司ID
|
||||||
|
|||||||
+6
-1
@@ -102,6 +102,11 @@ public class CompanyPermissionServiceImpl extends ServiceImpl<CompanyPermissionM
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void grantPermissionsForCompany(Long companyId, List<Long> permissionIds) {
|
public void grantPermissionsForCompany(Long companyId, List<Long> permissionIds) {
|
||||||
|
grantPermissionsForCompany(companyId, permissionIds, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void grantPermissionsForCompany(Long companyId, List<Long> permissionIds, Long createBy) {
|
||||||
if (permissionIds == null || permissionIds.isEmpty()) return;
|
if (permissionIds == null || permissionIds.isEmpty()) return;
|
||||||
List<Long> existingIds = getCompanyPermissionIds(companyId);
|
List<Long> existingIds = getCompanyPermissionIds(companyId);
|
||||||
List<Long> toAddIds = permissionIds.stream()
|
List<Long> toAddIds = permissionIds.stream()
|
||||||
@@ -112,7 +117,7 @@ public class CompanyPermissionServiceImpl extends ServiceImpl<CompanyPermissionM
|
|||||||
CompanyPermissionPO cp = new CompanyPermissionPO();
|
CompanyPermissionPO cp = new CompanyPermissionPO();
|
||||||
cp.setCompanyId(companyId);
|
cp.setCompanyId(companyId);
|
||||||
cp.setPermissionId(permissionId);
|
cp.setPermissionId(permissionId);
|
||||||
cp.setCreateBy(currentUserContext.getCurrentUserId());
|
cp.setCreateBy(createBy);
|
||||||
return cp;
|
return cp;
|
||||||
}).collect(Collectors.toList());
|
}).collect(Collectors.toList());
|
||||||
this.saveBatch(toAdd);
|
this.saveBatch(toAdd);
|
||||||
|
|||||||
+25
-1
@@ -16,13 +16,21 @@ import top.xyquan.ecomdmbbackend.modules.org.company.model.vo.CompanyVO;
|
|||||||
public interface CompanyService extends IService<CompanyPO> {
|
public interface CompanyService extends IService<CompanyPO> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建公司
|
* 创建公司(受 License 公司数量限制)
|
||||||
*
|
*
|
||||||
* @param createCompanyDTO 公司信息
|
* @param createCompanyDTO 公司信息
|
||||||
* @return 公司信息
|
* @return 公司信息
|
||||||
*/
|
*/
|
||||||
CompanyVO createCompany(CreateCompanyDTO createCompanyDTO);
|
CompanyVO createCompany(CreateCompanyDTO createCompanyDTO);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建系统公司(初始化专用,不限制数量)
|
||||||
|
*
|
||||||
|
* @param createCompanyDTO 公司信息
|
||||||
|
* @return 公司信息
|
||||||
|
*/
|
||||||
|
CompanyVO createSystemCompany(CreateCompanyDTO createCompanyDTO);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新公司
|
* 更新公司
|
||||||
*
|
*
|
||||||
@@ -68,10 +76,26 @@ public interface CompanyService extends IService<CompanyPO> {
|
|||||||
*/
|
*/
|
||||||
void initCompanyDepartments(Long companyId);
|
void initCompanyDepartments(Long companyId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化公司部门(指定创建人)
|
||||||
|
*
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param createBy 创建人ID(可空)
|
||||||
|
*/
|
||||||
|
void initCompanyDepartments(Long companyId, Long createBy);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 初始化公司岗位
|
* 初始化公司岗位
|
||||||
*
|
*
|
||||||
* @param companyId 公司ID
|
* @param companyId 公司ID
|
||||||
*/
|
*/
|
||||||
void initCompanyPositions(Long companyId);
|
void initCompanyPositions(Long companyId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化公司岗位(指定创建人)
|
||||||
|
*
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param createBy 创建人ID(可空)
|
||||||
|
*/
|
||||||
|
void initCompanyPositions(Long companyId, Long createBy);
|
||||||
}
|
}
|
||||||
|
|||||||
+76
-14
@@ -34,6 +34,9 @@ import top.xyquan.ecomdmbbackend.modules.sys.user.service.UserService;
|
|||||||
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
|
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
||||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.enums.CompanyMemberRole;
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.enums.CompanyMemberRole;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseEnforcement;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseInfo;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseValidator;
|
||||||
import org.springframework.context.annotation.Lazy;
|
import org.springframework.context.annotation.Lazy;
|
||||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
@@ -61,6 +64,7 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
private final UserService userService;
|
private final UserService userService;
|
||||||
private final CompanyMemberService companyMemberService;
|
private final CompanyMemberService companyMemberService;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final LicenseValidator licenseValidator;
|
||||||
|
|
||||||
public CompanyServiceImpl(@Lazy CurrentUserContext currentUserContext, SysFileService sysFileService,
|
public CompanyServiceImpl(@Lazy CurrentUserContext currentUserContext, SysFileService sysFileService,
|
||||||
PromotionFeeTypeService promotionFeeTypeService,
|
PromotionFeeTypeService promotionFeeTypeService,
|
||||||
@@ -68,7 +72,7 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
CompanyMenuService companyMenuService, DepartmentService departmentService,
|
CompanyMenuService companyMenuService, DepartmentService departmentService,
|
||||||
PositionService positionService, MenuService menuService,
|
PositionService positionService, MenuService menuService,
|
||||||
@Lazy UserService userService, @Lazy CompanyMemberService companyMemberService,
|
@Lazy UserService userService, @Lazy CompanyMemberService companyMemberService,
|
||||||
PasswordEncoder passwordEncoder) {
|
PasswordEncoder passwordEncoder, LicenseValidator licenseValidator) {
|
||||||
this.currentUserContext = currentUserContext;
|
this.currentUserContext = currentUserContext;
|
||||||
this.sysFileService = sysFileService;
|
this.sysFileService = sysFileService;
|
||||||
this.promotionFeeTypeService = promotionFeeTypeService;
|
this.promotionFeeTypeService = promotionFeeTypeService;
|
||||||
@@ -80,16 +84,37 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
this.companyMemberService = companyMemberService;
|
this.companyMemberService = companyMemberService;
|
||||||
this.passwordEncoder = passwordEncoder;
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.licenseValidator = licenseValidator;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建公司
|
* 创建公司(受 License 公司数量限制)
|
||||||
* @param createCompanyDTO 创建公司DTO
|
* @param createCompanyDTO 创建公司DTO
|
||||||
* @return 公司VO
|
* @return 公司VO
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public CompanyVO createCompany(CreateCompanyDTO createCompanyDTO) {
|
public CompanyVO createCompany(CreateCompanyDTO createCompanyDTO) {
|
||||||
|
checkCompanyLimit();
|
||||||
|
Long creatorId = currentUserContext.getCurrentUserId();
|
||||||
|
return doCreateCompany(createCompanyDTO, creatorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建系统公司(初始化专用,不校验 License 数量限制)
|
||||||
|
* @param createCompanyDTO 创建公司DTO
|
||||||
|
* @return 公司VO
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public CompanyVO createSystemCompany(CreateCompanyDTO createCompanyDTO) {
|
||||||
|
return doCreateCompany(createCompanyDTO, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公共创建逻辑
|
||||||
|
*/
|
||||||
|
private CompanyVO doCreateCompany(CreateCompanyDTO createCompanyDTO, Long creatorId) {
|
||||||
// 检查公司名称是否重复
|
// 检查公司名称是否重复
|
||||||
LambdaQueryWrapper<CompanyPO> wrapper = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<CompanyPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
wrapper.eq(CompanyPO::getName, createCompanyDTO.getName());
|
wrapper.eq(CompanyPO::getName, createCompanyDTO.getName());
|
||||||
@@ -107,7 +132,6 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 设置创建人ID
|
// 设置创建人ID
|
||||||
Long creatorId = currentUserContext.getCurrentUserId();
|
|
||||||
company.setCreateBy(creatorId);
|
company.setCreateBy(creatorId);
|
||||||
|
|
||||||
// 保存公司
|
// 保存公司
|
||||||
@@ -129,12 +153,12 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
ownerUser.setStatus(1);
|
ownerUser.setStatus(1);
|
||||||
ownerUser.setPwdSecurityLevel(1);
|
ownerUser.setPwdSecurityLevel(1);
|
||||||
ownerUser.setPwdUpdateTime(LocalDateTime.now());
|
ownerUser.setPwdUpdateTime(LocalDateTime.now());
|
||||||
ownerUser.setCreateBy(currentUserContext.getCurrentUserId());
|
ownerUser.setCreateBy(creatorId);
|
||||||
userService.save(ownerUser);
|
userService.save(ownerUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 将拥有者加入公司成员(owner角色)
|
// 将拥有者加入公司成员(owner角色)
|
||||||
companyMemberService.create(ownerUser.getId(), company.getId(), CompanyMemberRole.owner, null);
|
companyMemberService.create(ownerUser.getId(), company.getId(), CompanyMemberRole.owner, null, creatorId);
|
||||||
|
|
||||||
// 初始化推广费类型数据
|
// 初始化推广费类型数据
|
||||||
promotionFeeTypeService.initPromotionFeeTypeForCompany(company.getId(), creatorId);
|
promotionFeeTypeService.initPromotionFeeTypeForCompany(company.getId(), creatorId);
|
||||||
@@ -146,15 +170,33 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
initCompanyMenus(company.getId());
|
initCompanyMenus(company.getId());
|
||||||
|
|
||||||
// 初始化公司部门
|
// 初始化公司部门
|
||||||
initCompanyDepartments(company.getId());
|
initCompanyDepartments(company.getId(), creatorId);
|
||||||
|
|
||||||
// 初始化公司岗位
|
// 初始化公司岗位
|
||||||
initCompanyPositions(company.getId());
|
initCompanyPositions(company.getId(), creatorId);
|
||||||
|
|
||||||
// 转换为VO并返回
|
// 转换为VO并返回
|
||||||
return convertToVO(company);
|
return convertToVO(company);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验 License 允许创建的公司数量上限
|
||||||
|
*/
|
||||||
|
private void checkCompanyLimit() {
|
||||||
|
if (!LicenseEnforcement.isEnforced()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LicenseInfo license = licenseValidator.getCachedLicense();
|
||||||
|
if (license == null) {
|
||||||
|
throw new BusinessException("未激活 License 或 License 无效,无法创建公司");
|
||||||
|
}
|
||||||
|
long currentCount = this.count();
|
||||||
|
int maxCompanies = license.getMaxCompaniesOrDefault();
|
||||||
|
if (currentCount >= maxCompanies) {
|
||||||
|
throw new BusinessException("已达到 License 允许的最大公司数量:" + maxCompanies);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新公司
|
* 更新公司
|
||||||
* @param updateCompanyDTO 更新公司DTO
|
* @param updateCompanyDTO 更新公司DTO
|
||||||
@@ -325,23 +367,33 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void initCompanyDepartments(Long companyId) {
|
public void initCompanyDepartments(Long companyId) {
|
||||||
|
initCompanyDepartments(companyId, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化公司部门(指定创建人)
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param createBy 创建人ID
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void initCompanyDepartments(Long companyId, Long createBy) {
|
||||||
// 创建默认部门
|
// 创建默认部门
|
||||||
String[] defaultDepartments = {
|
String[] defaultDepartments = {
|
||||||
"总经理办公室",
|
"总经理办公室",
|
||||||
"技术部",
|
"技术部",
|
||||||
"市场部",
|
"市场部",
|
||||||
"财务部",
|
"财务部",
|
||||||
"人事部"
|
"人事部"
|
||||||
};
|
};
|
||||||
|
|
||||||
for (String deptName : defaultDepartments) {
|
for (String deptName : defaultDepartments) {
|
||||||
CreateDepartmentDTO createDepartmentDTO = new CreateDepartmentDTO();
|
CreateDepartmentDTO createDepartmentDTO = new CreateDepartmentDTO();
|
||||||
createDepartmentDTO.setName(deptName);
|
createDepartmentDTO.setName(deptName);
|
||||||
createDepartmentDTO.setRemark("系统初始化的默认部门");
|
createDepartmentDTO.setRemark("系统初始化的默认部门");
|
||||||
createDepartmentDTO.setStatus(1);
|
createDepartmentDTO.setStatus(1);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
departmentService.createDepartmentForCompany(createDepartmentDTO, companyId);
|
departmentService.createDepartmentForCompany(createDepartmentDTO, companyId, createBy);
|
||||||
} catch (BusinessException e) {
|
} catch (BusinessException e) {
|
||||||
// 如果已存在,跳过
|
// 如果已存在,跳过
|
||||||
continue;
|
continue;
|
||||||
@@ -355,6 +407,16 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void initCompanyPositions(Long companyId) {
|
public void initCompanyPositions(Long companyId) {
|
||||||
|
initCompanyPositions(companyId, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化公司岗位(指定创建人)
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param createBy 创建人ID
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void initCompanyPositions(Long companyId, Long createBy) {
|
||||||
// 创建默认岗位
|
// 创建默认岗位
|
||||||
String[][] defaultPositions = {
|
String[][] defaultPositions = {
|
||||||
{"总经理", "GM001", "负责公司整体运营管理"},
|
{"总经理", "GM001", "负责公司整体运营管理"},
|
||||||
@@ -364,16 +426,16 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
|||||||
{"财务经理", "FM001", "负责财务管理和会计核算"},
|
{"财务经理", "FM001", "负责财务管理和会计核算"},
|
||||||
{"人事经理", "HR001", "负责人力资源管理"}
|
{"人事经理", "HR001", "负责人力资源管理"}
|
||||||
};
|
};
|
||||||
|
|
||||||
for (String[] position : defaultPositions) {
|
for (String[] position : defaultPositions) {
|
||||||
CreatePositionDTO createPositionDTO = new CreatePositionDTO();
|
CreatePositionDTO createPositionDTO = new CreatePositionDTO();
|
||||||
createPositionDTO.setName(position[0]);
|
createPositionDTO.setName(position[0]);
|
||||||
createPositionDTO.setCode(position[1]);
|
createPositionDTO.setCode(position[1]);
|
||||||
createPositionDTO.setRemark(position[2]);
|
createPositionDTO.setRemark(position[2]);
|
||||||
createPositionDTO.setStatus(1);
|
createPositionDTO.setStatus(1);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
positionService.createPositionForCompany(createPositionDTO, companyId);
|
positionService.createPositionForCompany(createPositionDTO, companyId, createBy);
|
||||||
} catch (BusinessException e) {
|
} catch (BusinessException e) {
|
||||||
// 如果已存在,跳过
|
// 如果已存在,跳过
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
+10
@@ -70,4 +70,14 @@ public interface DepartmentService extends IService<DepartmentPO> {
|
|||||||
* @return 部门信息
|
* @return 部门信息
|
||||||
*/
|
*/
|
||||||
DepartmentVO createDepartmentForCompany(CreateDepartmentDTO createDepartmentDTO, Long companyId);
|
DepartmentVO createDepartmentForCompany(CreateDepartmentDTO createDepartmentDTO, Long companyId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为指定公司创建部门(指定创建人)
|
||||||
|
*
|
||||||
|
* @param createDepartmentDTO 部门信息
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param createBy 创建人ID(可空)
|
||||||
|
* @return 部门信息
|
||||||
|
*/
|
||||||
|
DepartmentVO createDepartmentForCompany(CreateDepartmentDTO createDepartmentDTO, Long companyId, Long createBy);
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-1
@@ -262,6 +262,12 @@ public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Departm
|
|||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public DepartmentVO createDepartmentForCompany(CreateDepartmentDTO createDepartmentDTO, Long companyId) {
|
public DepartmentVO createDepartmentForCompany(CreateDepartmentDTO createDepartmentDTO, Long companyId) {
|
||||||
|
return createDepartmentForCompany(createDepartmentDTO, companyId, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public DepartmentVO createDepartmentForCompany(CreateDepartmentDTO createDepartmentDTO, Long companyId, Long createBy) {
|
||||||
// 验证部门名称是否重复
|
// 验证部门名称是否重复
|
||||||
LambdaQueryWrapper<DepartmentPO> wrapper = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<DepartmentPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
wrapper.eq(DepartmentPO::getName, createDepartmentDTO.getName())
|
wrapper.eq(DepartmentPO::getName, createDepartmentDTO.getName())
|
||||||
@@ -283,7 +289,7 @@ public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Departm
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 设置创建人ID
|
// 设置创建人ID
|
||||||
department.setCreateBy(currentUserContext.getCurrentUserId());
|
department.setCreateBy(createBy);
|
||||||
|
|
||||||
// 保存部门
|
// 保存部门
|
||||||
this.save(department);
|
this.save(department);
|
||||||
|
|||||||
+10
@@ -54,4 +54,14 @@ public interface PositionService extends IService<PositionPO> {
|
|||||||
* @return 岗位信息
|
* @return 岗位信息
|
||||||
*/
|
*/
|
||||||
PositionVO createPositionForCompany(CreatePositionDTO createPositionDTO, Long companyId);
|
PositionVO createPositionForCompany(CreatePositionDTO createPositionDTO, Long companyId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为指定公司创建岗位(指定创建人)
|
||||||
|
*
|
||||||
|
* @param createPositionDTO 岗位信息
|
||||||
|
* @param companyId 公司ID
|
||||||
|
* @param createBy 创建人ID(可空)
|
||||||
|
* @return 岗位信息
|
||||||
|
*/
|
||||||
|
PositionVO createPositionForCompany(CreatePositionDTO createPositionDTO, Long companyId, Long createBy);
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-1
@@ -199,6 +199,12 @@ public class PositionServiceImpl extends ServiceImpl<PositionMapper, PositionPO>
|
|||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public PositionVO createPositionForCompany(CreatePositionDTO createPositionDTO, Long companyId) {
|
public PositionVO createPositionForCompany(CreatePositionDTO createPositionDTO, Long companyId) {
|
||||||
|
return createPositionForCompany(createPositionDTO, companyId, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public PositionVO createPositionForCompany(CreatePositionDTO createPositionDTO, Long companyId, Long createBy) {
|
||||||
// 验证岗位名称是否重复
|
// 验证岗位名称是否重复
|
||||||
LambdaQueryWrapper<PositionPO> wrapper = new LambdaQueryWrapper<>();
|
LambdaQueryWrapper<PositionPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
wrapper.eq(PositionPO::getName, createPositionDTO.getName())
|
wrapper.eq(PositionPO::getName, createPositionDTO.getName())
|
||||||
@@ -220,7 +226,7 @@ public class PositionServiceImpl extends ServiceImpl<PositionMapper, PositionPO>
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 设置创建人ID
|
// 设置创建人ID
|
||||||
position.setCreateBy(currentUserContext.getCurrentUserId());
|
position.setCreateBy(createBy);
|
||||||
|
|
||||||
// 保存岗位
|
// 保存岗位
|
||||||
this.save(position);
|
this.save(position);
|
||||||
|
|||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.sys.init.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 系统初始化配置,首次部署时自动创建系统公司与超级管理员。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "ecom.init")
|
||||||
|
public class SysInitProperties {
|
||||||
|
|
||||||
|
/** 是否启用启动时自动初始化 */
|
||||||
|
private boolean autoInit = true;
|
||||||
|
|
||||||
|
/** 系统公司名称 */
|
||||||
|
private String companyName = "系统公司";
|
||||||
|
|
||||||
|
/** 超级管理员登录账号 */
|
||||||
|
private String adminLoginCode = "admin";
|
||||||
|
|
||||||
|
/** 超级管理员手机号 */
|
||||||
|
private String adminPhone = "13800000001";
|
||||||
|
|
||||||
|
/** 超级管理员姓名 */
|
||||||
|
private String adminRealName = "超级管理员";
|
||||||
|
|
||||||
|
/** 超级管理员密码;为空时随机生成并打印到日志 */
|
||||||
|
private String adminPassword = "admin123";
|
||||||
|
|
||||||
|
/** 默认状态 (0-禁用 1-正常) */
|
||||||
|
private Integer status = 1;
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.sys.init.controller;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.model.vo.InitStatusVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.service.SysInitService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 系统初始化状态查询 API(无需登录,用于诊断首次部署状态)
|
||||||
|
*/
|
||||||
|
@Tag(name = "系统初始化", description = "首次部署初始化状态")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/init")
|
||||||
|
public class InitController {
|
||||||
|
|
||||||
|
private final SysInitService sysInitService;
|
||||||
|
|
||||||
|
public InitController(SysInitService sysInitService) {
|
||||||
|
this.sysInitService = sysInitService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取初始化状态")
|
||||||
|
@GetMapping("/status")
|
||||||
|
public ApiResponse<InitStatusVO> status() {
|
||||||
|
return ApiResponse.success(sysInitService.getStatus());
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-4
@@ -1,10 +1,8 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.license.mapper;
|
package top.xyquan.ecomdmbbackend.modules.sys.init.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.po.SysInitPO;
|
|
||||||
|
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.model.po.SysInitPO;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public interface SysInitMapper extends BaseMapper<SysInitPO> {
|
public interface SysInitMapper extends BaseMapper<SysInitPO> {
|
||||||
+5
-2
@@ -1,4 +1,4 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.license.model.po;
|
package top.xyquan.ecomdmbbackend.modules.sys.init.model.po;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.IdType;
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
import com.baomidou.mybatisplus.annotation.TableId;
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
@@ -17,7 +17,10 @@ public class SysInitPO {
|
|||||||
@TableId(value = "id", type = IdType.INPUT)
|
@TableId(value = "id", type = IdType.INPUT)
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
/** 初始化步骤 0~3 */
|
/** 是否已完成初始化(新字段,兼容旧 step>=3 语义) */
|
||||||
|
private Boolean initialized;
|
||||||
|
|
||||||
|
/** 初始化步骤 0~3(旧字段,保留兼容) */
|
||||||
private Integer step;
|
private Integer step;
|
||||||
|
|
||||||
private Long adminId;
|
private Long adminId;
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.sys.init.model.vo;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化状态
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class InitStatusVO {
|
||||||
|
|
||||||
|
private boolean initialized;
|
||||||
|
|
||||||
|
private String systemCompanyName;
|
||||||
|
|
||||||
|
private String adminLoginCode;
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.sys.init.runner;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.ApplicationArguments;
|
||||||
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.config.SysInitProperties;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.service.SysInitService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用启动后自动执行系统初始化。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@Order(100)
|
||||||
|
public class SysInitRunner implements ApplicationRunner {
|
||||||
|
|
||||||
|
private final SysInitService sysInitService;
|
||||||
|
private final SysInitProperties initProperties;
|
||||||
|
|
||||||
|
public SysInitRunner(SysInitService sysInitService, SysInitProperties initProperties) {
|
||||||
|
this.sysInitService = sysInitService;
|
||||||
|
this.initProperties = initProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(ApplicationArguments args) {
|
||||||
|
if (!initProperties.isAutoInit()) {
|
||||||
|
log.info("系统自动初始化已关闭");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// 每次启动都检查并补齐基础数据(权限、菜单等)
|
||||||
|
sysInitService.ensureBaseData();
|
||||||
|
// 仅在未完成初始化时创建系统公司与超管
|
||||||
|
sysInitService.initializeIfNeeded();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("系统自动初始化失败:{}", e.getMessage(), e);
|
||||||
|
// 初始化失败不阻塞启动,便于人工排查;后续业务接口会因未初始化而受限
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+82
@@ -0,0 +1,82 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.sys.init.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.ibatis.jdbc.ScriptRunner;
|
||||||
|
import org.springframework.core.io.ClassPathResource;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.menu.mapper.MenuMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.menu.model.po.MenuPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.permission.mapper.PermissionMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.permission.model.po.PermissionPO;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.sql.Connection;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 系统基础数据初始化服务:负责 sys_permission / sys_menu / sys_menu_permission 等
|
||||||
|
* 启动时检测,缺失则通过 classpath SQL 脚本补齐。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class SysInitDataService {
|
||||||
|
|
||||||
|
private static final String SEED_SCRIPT = "sql/init/sys_seed.sql";
|
||||||
|
private static final String CHECK_MENU_NAME = "System";
|
||||||
|
|
||||||
|
private final DataSource dataSource;
|
||||||
|
private final PermissionMapper permissionMapper;
|
||||||
|
private final MenuMapper menuMapper;
|
||||||
|
|
||||||
|
public SysInitDataService(DataSource dataSource,
|
||||||
|
PermissionMapper permissionMapper,
|
||||||
|
MenuMapper menuMapper) {
|
||||||
|
this.dataSource = dataSource;
|
||||||
|
this.permissionMapper = permissionMapper;
|
||||||
|
this.menuMapper = menuMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 确保基础数据已初始化。若核心菜单/权限缺失,则执行种子脚本。
|
||||||
|
*/
|
||||||
|
public void ensureBaseData() {
|
||||||
|
if (hasBaseData()) {
|
||||||
|
log.debug("系统基础权限/菜单数据已存在,跳过种子数据初始化");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log.info("系统基础权限/菜单数据缺失,开始执行种子脚本 {} ...", SEED_SCRIPT);
|
||||||
|
runSeedScript();
|
||||||
|
log.info("系统基础权限/菜单数据初始化完成");
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasBaseData() {
|
||||||
|
Long permissionCount = permissionMapper.selectCount(
|
||||||
|
new LambdaQueryWrapper<PermissionPO>().eq(PermissionPO::getCode, "system:user:read"));
|
||||||
|
if (permissionCount == null || permissionCount == 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Long menuCount = menuMapper.selectCount(
|
||||||
|
new LambdaQueryWrapper<MenuPO>().eq(MenuPO::getName, CHECK_MENU_NAME));
|
||||||
|
return menuCount != null && menuCount > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void runSeedScript() {
|
||||||
|
ClassPathResource resource = new ClassPathResource(SEED_SCRIPT);
|
||||||
|
if (!resource.exists()) {
|
||||||
|
throw new IllegalStateException("找不到系统种子脚本: " + SEED_SCRIPT);
|
||||||
|
}
|
||||||
|
try (Connection connection = dataSource.getConnection();
|
||||||
|
InputStreamReader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
|
||||||
|
ScriptRunner runner = new ScriptRunner(connection);
|
||||||
|
runner.setSendFullScript(false);
|
||||||
|
runner.setStopOnError(false);
|
||||||
|
runner.setLogWriter(null);
|
||||||
|
runner.setErrorLogWriter(new java.io.PrintWriter(System.err));
|
||||||
|
runner.runScript(reader);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("执行系统种子脚本失败: " + SEED_SCRIPT, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+178
@@ -0,0 +1,178 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.sys.init.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.model.dto.CreateCompanyDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.service.CompanyService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.config.SysInitProperties;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.mapper.SysInitMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.model.po.SysInitPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.init.model.vo.InitStatusVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.user.mapper.UserMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 系统初始化服务:首次启动时自动创建系统公司与超级管理员。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class SysInitService {
|
||||||
|
|
||||||
|
private static final long INIT_ROW_ID = 1L;
|
||||||
|
|
||||||
|
private final SysInitMapper sysInitMapper;
|
||||||
|
private final UserMapper userMapper;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final CompanyService companyService;
|
||||||
|
private final SysInitDataService sysInitDataService;
|
||||||
|
private final SysInitProperties initProperties;
|
||||||
|
|
||||||
|
public SysInitService(SysInitMapper sysInitMapper,
|
||||||
|
UserMapper userMapper,
|
||||||
|
PasswordEncoder passwordEncoder,
|
||||||
|
CompanyService companyService,
|
||||||
|
SysInitDataService sysInitDataService,
|
||||||
|
SysInitProperties initProperties) {
|
||||||
|
this.sysInitMapper = sysInitMapper;
|
||||||
|
this.userMapper = userMapper;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.companyService = companyService;
|
||||||
|
this.sysInitDataService = sysInitDataService;
|
||||||
|
this.initProperties = initProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查并补齐系统基础数据(权限、菜单等),每次启动都可调用。
|
||||||
|
*/
|
||||||
|
public void ensureBaseData() {
|
||||||
|
sysInitDataService.ensureBaseData();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 若未初始化,则执行初始化。
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public synchronized void initializeIfNeeded() {
|
||||||
|
SysInitPO init = getOrCreateInitRow();
|
||||||
|
if (Boolean.TRUE.equals(init.getInitialized()) || (init.getStep() != null && init.getStep() >= 3)) {
|
||||||
|
log.debug("系统已完成初始化,跳过");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("系统未初始化,开始执行自动初始化...");
|
||||||
|
|
||||||
|
// 1. 确保系统权限、菜单等基础数据已存在
|
||||||
|
sysInitDataService.ensureBaseData();
|
||||||
|
|
||||||
|
// 2. 创建超级管理员
|
||||||
|
UserPO admin = createSuperAdmin();
|
||||||
|
|
||||||
|
// 3. 创建系统公司(使用超管作为负责人,绕过 License 数量限制)
|
||||||
|
CreateCompanyDTO companyDTO = new CreateCompanyDTO();
|
||||||
|
companyDTO.setName(initProperties.getCompanyName());
|
||||||
|
companyDTO.setOwnerName(initProperties.getAdminRealName());
|
||||||
|
companyDTO.setOwnerPhone(initProperties.getAdminPhone());
|
||||||
|
companyDTO.setStatus(initProperties.getStatus());
|
||||||
|
companyService.createSystemCompany(companyDTO);
|
||||||
|
|
||||||
|
// 4. 标记初始化完成
|
||||||
|
init.setInitialized(true);
|
||||||
|
init.setStep(3);
|
||||||
|
init.setAdminId(admin.getId());
|
||||||
|
init.setCompanyName(companyDTO.getName());
|
||||||
|
init.setUpdatedAt(LocalDateTime.now());
|
||||||
|
sysInitMapper.updateById(init);
|
||||||
|
|
||||||
|
log.info("系统初始化完成:系统公司=[{}],超管账号=[{}]", companyDTO.getName(), admin.getLoginCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
public InitStatusVO getStatus() {
|
||||||
|
SysInitPO init = getOrCreateInitRow();
|
||||||
|
boolean initialized = Boolean.TRUE.equals(init.getInitialized())
|
||||||
|
|| (init.getStep() != null && init.getStep() >= 3);
|
||||||
|
return InitStatusVO.builder()
|
||||||
|
.initialized(initialized)
|
||||||
|
.systemCompanyName(init.getCompanyName())
|
||||||
|
.adminLoginCode(resolveAdminLoginCode(init))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private UserPO createSuperAdmin() {
|
||||||
|
String loginCode = initProperties.getAdminLoginCode();
|
||||||
|
if (!StringUtils.hasText(loginCode)) {
|
||||||
|
throw new BusinessException("超级管理员登录账号未配置");
|
||||||
|
}
|
||||||
|
|
||||||
|
LambdaQueryWrapper<UserPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(UserPO::getLoginCode, loginCode);
|
||||||
|
UserPO existing = userMapper.selectOne(wrapper);
|
||||||
|
if (existing != null) {
|
||||||
|
log.warn("超级管理员账号 [{}] 已存在,直接使用", loginCode);
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
String rawPassword = initProperties.getAdminPassword();
|
||||||
|
boolean generated = false;
|
||||||
|
if (!StringUtils.hasText(rawPassword)) {
|
||||||
|
rawPassword = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||||
|
generated = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
UserPO user = new UserPO();
|
||||||
|
user.setLoginCode(loginCode);
|
||||||
|
user.setPhone(initProperties.getAdminPhone());
|
||||||
|
user.setPassword(passwordEncoder.encode(rawPassword));
|
||||||
|
user.setRealName(initProperties.getAdminRealName());
|
||||||
|
user.setRole("super");
|
||||||
|
user.setStatus(initProperties.getStatus());
|
||||||
|
user.setPwdSecurityLevel(3);
|
||||||
|
user.setPwdUpdateTime(LocalDateTime.now());
|
||||||
|
userMapper.insert(user);
|
||||||
|
|
||||||
|
if (generated) {
|
||||||
|
log.warn("==================================================");
|
||||||
|
log.warn("超级管理员密码已随机生成,请首次登录后尽快修改:");
|
||||||
|
log.warn("账号:{},密码:{}", loginCode, rawPassword);
|
||||||
|
log.warn("==================================================");
|
||||||
|
} else {
|
||||||
|
log.warn("==================================================");
|
||||||
|
log.warn("超级管理员使用默认密码,生产环境请务必修改:");
|
||||||
|
log.warn("账号:{},密码:{}", loginCode, rawPassword);
|
||||||
|
log.warn("==================================================");
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SysInitPO getOrCreateInitRow() {
|
||||||
|
SysInitPO init = sysInitMapper.selectById(INIT_ROW_ID);
|
||||||
|
if (init == null) {
|
||||||
|
init = new SysInitPO();
|
||||||
|
init.setId(INIT_ROW_ID);
|
||||||
|
init.setInitialized(false);
|
||||||
|
init.setStep(0);
|
||||||
|
init.setCreatedAt(LocalDateTime.now());
|
||||||
|
init.setUpdatedAt(LocalDateTime.now());
|
||||||
|
sysInitMapper.insert(init);
|
||||||
|
}
|
||||||
|
return init;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveAdminLoginCode(SysInitPO init) {
|
||||||
|
if (init.getAdminId() != null) {
|
||||||
|
UserPO user = userMapper.selectById(init.getAdminId());
|
||||||
|
if (user != null) {
|
||||||
|
return user.getLoginCode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return initProperties.getAdminLoginCode();
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -24,8 +24,8 @@ public class LicenseAspect {
|
|||||||
this.licenseValidator = licenseValidator;
|
this.licenseValidator = licenseValidator;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Around("@annotation(top.xyquan.ecomdmbbackend.modules.license.LicenseRequired)"
|
@Around("@annotation(top.xyquan.ecomdmbbackend.modules.sys.license.LicenseRequired)"
|
||||||
+ " || @annotation(top.xyquan.ecomdmbbackend.modules.license.RequiresOrderCreateLicense)")
|
+ " || @annotation(top.xyquan.ecomdmbbackend.modules.sys.license.RequiresOrderCreateLicense)")
|
||||||
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||||
if (!LicenseEnforcement.isEnforced()) {
|
if (!LicenseEnforcement.isEnforced()) {
|
||||||
return joinPoint.proceed();
|
return joinPoint.proceed();
|
||||||
|
|||||||
+15
@@ -21,10 +21,17 @@ public class LicenseInfo {
|
|||||||
private String jti;
|
private String jti;
|
||||||
private String issuer;
|
private String issuer;
|
||||||
private List<String> features;
|
private List<String> features;
|
||||||
|
private Integer maxCompanies;
|
||||||
private Instant issuedAt;
|
private Instant issuedAt;
|
||||||
private Instant expiresAt;
|
private Instant expiresAt;
|
||||||
private String rawLicenseKey;
|
private String rawLicenseKey;
|
||||||
|
|
||||||
|
/** SaaS 默认公司上限 */
|
||||||
|
private static final int DEFAULT_SAAS_COMPANY_LIMIT = 100;
|
||||||
|
|
||||||
|
/** 私有部署默认公司上限 */
|
||||||
|
private static final int DEFAULT_PRIVATE_COMPANY_LIMIT = 2;
|
||||||
|
|
||||||
/** 是否已过期 */
|
/** 是否已过期 */
|
||||||
public boolean isExpired() {
|
public boolean isExpired() {
|
||||||
return expiresAt != null && Instant.now().isAfter(expiresAt);
|
return expiresAt != null && Instant.now().isAfter(expiresAt);
|
||||||
@@ -39,4 +46,12 @@ public class LicenseInfo {
|
|||||||
public boolean isWildcardFingerprint() {
|
public boolean isWildcardFingerprint() {
|
||||||
return "*".equals(machineFingerprint);
|
return "*".equals(machineFingerprint);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 获取允许创建的最大公司数量 */
|
||||||
|
public int getMaxCompaniesOrDefault() {
|
||||||
|
if (maxCompanies != null && maxCompanies > 0) {
|
||||||
|
return maxCompanies;
|
||||||
|
}
|
||||||
|
return isWildcardFingerprint() ? DEFAULT_SAAS_COMPANY_LIMIT : DEFAULT_PRIVATE_COMPANY_LIMIT;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+9
@@ -276,6 +276,7 @@ public class LicenseValidator {
|
|||||||
.jti(jti)
|
.jti(jti)
|
||||||
.issuer(claims.getIssuer())
|
.issuer(claims.getIssuer())
|
||||||
.features(features)
|
.features(features)
|
||||||
|
.maxCompanies(integerClaim(claims, "maxCompanies"))
|
||||||
.issuedAt(claims.getIssueTime() != null ? claims.getIssueTime().toInstant() : null)
|
.issuedAt(claims.getIssueTime() != null ? claims.getIssueTime().toInstant() : null)
|
||||||
.expiresAt(claims.getExpirationTime() != null ? claims.getExpirationTime().toInstant() : null)
|
.expiresAt(claims.getExpirationTime() != null ? claims.getExpirationTime().toInstant() : null)
|
||||||
.rawLicenseKey(licenseKey)
|
.rawLicenseKey(licenseKey)
|
||||||
@@ -357,6 +358,14 @@ public class LicenseValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Integer integerClaim(JWTClaimsSet claims, String name) {
|
||||||
|
try {
|
||||||
|
return claims.getIntegerClaim(name);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private LocalDateTime toLocalDateTime(Instant instant) {
|
private LocalDateTime toLocalDateTime(Instant instant) {
|
||||||
if (instant == null) {
|
if (instant == null) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
-66
@@ -1,66 +0,0 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.license.controller;
|
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
|
||||||
import jakarta.validation.Valid;
|
|
||||||
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.RestController;
|
|
||||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.ActivateLicenseDTO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.InitAdminDTO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.InitCompanyDTO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.FingerprintVO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.InitStatusVO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.LicenseSummaryVO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.service.InitializeService;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 系统初始化向导 API(无需登录)
|
|
||||||
*/
|
|
||||||
@Tag(name = "系统初始化", description = "首次部署初始化向导")
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/init")
|
|
||||||
public class InitController {
|
|
||||||
|
|
||||||
private final InitializeService initializeService;
|
|
||||||
|
|
||||||
public InitController(InitializeService initializeService) {
|
|
||||||
this.initializeService = initializeService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(summary = "获取初始化状态")
|
|
||||||
@GetMapping("/status")
|
|
||||||
public ApiResponse<InitStatusVO> status() {
|
|
||||||
return ApiResponse.success(initializeService.getStatus());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(summary = "Step1 创建超级管理员")
|
|
||||||
@PostMapping("/admin")
|
|
||||||
public ApiResponse<Void> createAdmin(@Valid @RequestBody InitAdminDTO dto) {
|
|
||||||
initializeService.createAdmin(dto);
|
|
||||||
return ApiResponse.success("超级管理员创建成功");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(summary = "Step2 保存公司信息")
|
|
||||||
@PostMapping("/company")
|
|
||||||
public ApiResponse<Void> saveCompany(@Valid @RequestBody InitCompanyDTO dto) {
|
|
||||||
initializeService.saveCompany(dto);
|
|
||||||
return ApiResponse.success("公司信息保存成功");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(summary = "获取机器指纹")
|
|
||||||
@GetMapping("/fingerprint")
|
|
||||||
public ApiResponse<FingerprintVO> fingerprint() {
|
|
||||||
return ApiResponse.success(initializeService.getFingerprint());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(summary = "Step3 激活 License")
|
|
||||||
@PostMapping("/activate")
|
|
||||||
public ApiResponse<LicenseSummaryVO> activate(@Valid @RequestBody ActivateLicenseDTO dto) {
|
|
||||||
LicenseSummaryVO summary = initializeService.activate(dto);
|
|
||||||
return ApiResponse.success("License 激活成功", summary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+12
-7
@@ -9,10 +9,11 @@ import org.springframework.web.bind.annotation.RequestBody;
|
|||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.MachineFingerprintUtil;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.ActivateLicenseDTO;
|
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.ActivateLicenseDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.FingerprintVO;
|
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.FingerprintVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.LicenseSummaryVO;
|
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.LicenseSummaryVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.service.InitializeService;
|
import top.xyquan.ecomdmbbackend.modules.sys.license.service.LicenseService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 已登录用户的 License 管理 API
|
* 已登录用户的 License 管理 API
|
||||||
@@ -22,28 +23,32 @@ import top.xyquan.ecomdmbbackend.modules.sys.license.service.InitializeService;
|
|||||||
@RequestMapping("/system")
|
@RequestMapping("/system")
|
||||||
public class SystemLicenseController {
|
public class SystemLicenseController {
|
||||||
|
|
||||||
private final InitializeService initializeService;
|
private final LicenseService licenseService;
|
||||||
|
|
||||||
public SystemLicenseController(InitializeService initializeService) {
|
public SystemLicenseController(LicenseService licenseService) {
|
||||||
this.initializeService = initializeService;
|
this.licenseService = licenseService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取当前 License 信息")
|
@Operation(summary = "获取当前 License 信息")
|
||||||
@GetMapping("/license")
|
@GetMapping("/license")
|
||||||
public ApiResponse<LicenseSummaryVO> getLicense() {
|
public ApiResponse<LicenseSummaryVO> getLicense() {
|
||||||
return ApiResponse.success(initializeService.getLicenseSummary());
|
return ApiResponse.success(licenseService.getLicenseSummary());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "更新/续期 License")
|
@Operation(summary = "更新/续期 License")
|
||||||
@PutMapping("/license")
|
@PutMapping("/license")
|
||||||
public ApiResponse<LicenseSummaryVO> updateLicense(@Valid @RequestBody ActivateLicenseDTO dto) {
|
public ApiResponse<LicenseSummaryVO> updateLicense(@Valid @RequestBody ActivateLicenseDTO dto) {
|
||||||
LicenseSummaryVO summary = initializeService.updateLicense(dto);
|
LicenseSummaryVO summary = licenseService.updateLicense(dto);
|
||||||
return ApiResponse.success("License 更新成功", summary);
|
return ApiResponse.success("License 更新成功", summary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "获取机器指纹")
|
@Operation(summary = "获取机器指纹")
|
||||||
@GetMapping("/fingerprint")
|
@GetMapping("/fingerprint")
|
||||||
public ApiResponse<FingerprintVO> fingerprint() {
|
public ApiResponse<FingerprintVO> fingerprint() {
|
||||||
return ApiResponse.success(initializeService.getFingerprint());
|
return ApiResponse.success(FingerprintVO.builder()
|
||||||
|
.fingerprint(MachineFingerprintUtil.computeFingerprint())
|
||||||
|
.machineId(MachineFingerprintUtil.getMachineId())
|
||||||
|
.hostname(MachineFingerprintUtil.getHostname())
|
||||||
|
.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -4,11 +4,11 @@ import jakarta.validation.constraints.NotBlank;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 激活 / 更新 License 请求
|
* 激活/更新 License
|
||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
public class ActivateLicenseDTO {
|
public class ActivateLicenseDTO {
|
||||||
|
|
||||||
@NotBlank(message = "License Key 不能为空")
|
@NotBlank(message = "License 密钥不能为空")
|
||||||
private String licenseKey;
|
private String licenseKey;
|
||||||
}
|
}
|
||||||
|
|||||||
-22
@@ -1,22 +0,0 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.license.model.dto;
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 初始化 Step1:创建超级管理员
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
public class InitAdminDTO {
|
|
||||||
|
|
||||||
@NotBlank(message = "登录账号不能为空")
|
|
||||||
private String loginCode;
|
|
||||||
|
|
||||||
private String phone;
|
|
||||||
|
|
||||||
@NotBlank(message = "密码不能为空")
|
|
||||||
private String password;
|
|
||||||
|
|
||||||
@NotBlank(message = "姓名不能为空")
|
|
||||||
private String realName;
|
|
||||||
}
|
|
||||||
-18
@@ -1,18 +0,0 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.license.model.dto;
|
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 初始化 Step2:公司信息
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
public class InitCompanyDTO {
|
|
||||||
|
|
||||||
@NotBlank(message = "公司名称不能为空")
|
|
||||||
private String companyName;
|
|
||||||
|
|
||||||
private String contactPhone;
|
|
||||||
|
|
||||||
private String contactEmail;
|
|
||||||
}
|
|
||||||
-18
@@ -1,18 +0,0 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.license.model.vo;
|
|
||||||
|
|
||||||
import lombok.Builder;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 初始化状态
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
public class InitStatusVO {
|
|
||||||
|
|
||||||
private boolean initialized;
|
|
||||||
private int currentStep;
|
|
||||||
private boolean adminCreated;
|
|
||||||
private boolean companySaved;
|
|
||||||
private boolean licenseActivated;
|
|
||||||
}
|
|
||||||
+1
@@ -17,6 +17,7 @@ public class LicenseSummaryVO {
|
|||||||
private String edition;
|
private String edition;
|
||||||
private String machineFingerprint;
|
private String machineFingerprint;
|
||||||
private List<String> features;
|
private List<String> features;
|
||||||
|
private Integer maxCompanies;
|
||||||
private LocalDateTime issuedAt;
|
private LocalDateTime issuedAt;
|
||||||
private LocalDateTime expiresAt;
|
private LocalDateTime expiresAt;
|
||||||
private Long daysRemaining;
|
private Long daysRemaining;
|
||||||
|
|||||||
-213
@@ -1,213 +0,0 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.sys.license.service;
|
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseEnforcement;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseInfo;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseValidator;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.MachineFingerprintUtil;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.mapper.SysInitMapper;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.ActivateLicenseDTO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.InitAdminDTO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.InitCompanyDTO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.po.SysInitPO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.FingerprintVO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.InitStatusVO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.LicenseSummaryVO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.user.mapper.UserMapper;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.temporal.ChronoUnit;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 系统初始化与 License 管理服务
|
|
||||||
*/
|
|
||||||
@Service
|
|
||||||
public class InitializeService {
|
|
||||||
|
|
||||||
private static final long INIT_ROW_ID = 1L;
|
|
||||||
|
|
||||||
private final SysInitMapper sysInitMapper;
|
|
||||||
private final UserMapper userMapper;
|
|
||||||
private final PasswordEncoder passwordEncoder;
|
|
||||||
private final LicenseValidator licenseValidator;
|
|
||||||
|
|
||||||
public InitializeService(SysInitMapper sysInitMapper,
|
|
||||||
UserMapper userMapper,
|
|
||||||
PasswordEncoder passwordEncoder,
|
|
||||||
LicenseValidator licenseValidator) {
|
|
||||||
this.sysInitMapper = sysInitMapper;
|
|
||||||
this.userMapper = userMapper;
|
|
||||||
this.passwordEncoder = passwordEncoder;
|
|
||||||
this.licenseValidator = licenseValidator;
|
|
||||||
}
|
|
||||||
|
|
||||||
public InitStatusVO getStatus() {
|
|
||||||
SysInitPO init = getOrCreateInitRow();
|
|
||||||
int step = init.getStep() != null ? init.getStep() : 0;
|
|
||||||
return InitStatusVO.builder()
|
|
||||||
.initialized(step >= 3)
|
|
||||||
.currentStep(step)
|
|
||||||
.adminCreated(step >= 1)
|
|
||||||
.companySaved(step >= 2)
|
|
||||||
.licenseActivated(step >= 3)
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
public FingerprintVO getFingerprint() {
|
|
||||||
return FingerprintVO.builder()
|
|
||||||
.fingerprint(MachineFingerprintUtil.computeFingerprint())
|
|
||||||
.machineId(MachineFingerprintUtil.getMachineId())
|
|
||||||
.hostname(MachineFingerprintUtil.getHostname())
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void createAdmin(InitAdminDTO dto) {
|
|
||||||
SysInitPO init = getOrCreateInitRow();
|
|
||||||
if (init.getStep() != null && init.getStep() >= 3) {
|
|
||||||
throw new BusinessException("系统已完成初始化");
|
|
||||||
}
|
|
||||||
if (init.getStep() != null && init.getStep() >= 1) {
|
|
||||||
throw new BusinessException("超级管理员已创建");
|
|
||||||
}
|
|
||||||
// 检查账号唯一
|
|
||||||
if (StringUtils.hasText(dto.getLoginCode())) {
|
|
||||||
Long count = userMapper.selectCount(new LambdaQueryWrapper<UserPO>()
|
|
||||||
.eq(UserPO::getLoginCode, dto.getLoginCode()));
|
|
||||||
if (count > 0) {
|
|
||||||
throw new BusinessException("登录账号已存在");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (StringUtils.hasText(dto.getPhone())) {
|
|
||||||
Long count = userMapper.selectCount(new LambdaQueryWrapper<UserPO>()
|
|
||||||
.eq(UserPO::getPhone, dto.getPhone()));
|
|
||||||
if (count > 0) {
|
|
||||||
throw new BusinessException("手机号码已存在");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
UserPO user = new UserPO();
|
|
||||||
user.setLoginCode(dto.getLoginCode());
|
|
||||||
user.setPhone(dto.getPhone());
|
|
||||||
user.setPassword(passwordEncoder.encode(dto.getPassword()));
|
|
||||||
user.setRealName(dto.getRealName());
|
|
||||||
user.setRole("super");
|
|
||||||
user.setStatus(1);
|
|
||||||
user.setPwdSecurityLevel(3);
|
|
||||||
user.setPwdUpdateTime(LocalDateTime.now());
|
|
||||||
userMapper.insert(user);
|
|
||||||
|
|
||||||
init.setAdminId(user.getId());
|
|
||||||
init.setStep(1);
|
|
||||||
init.setUpdatedAt(LocalDateTime.now());
|
|
||||||
sysInitMapper.updateById(init);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void saveCompany(InitCompanyDTO dto) {
|
|
||||||
SysInitPO init = getOrCreateInitRow();
|
|
||||||
if (init.getStep() == null || init.getStep() < 1) {
|
|
||||||
throw new BusinessException("请先创建超级管理员");
|
|
||||||
}
|
|
||||||
if (init.getStep() >= 3) {
|
|
||||||
throw new BusinessException("系统已完成初始化");
|
|
||||||
}
|
|
||||||
init.setCompanyName(dto.getCompanyName());
|
|
||||||
init.setStep(2);
|
|
||||||
init.setUpdatedAt(LocalDateTime.now());
|
|
||||||
sysInitMapper.updateById(init);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public LicenseSummaryVO activate(ActivateLicenseDTO dto) {
|
|
||||||
SysInitPO init = getOrCreateInitRow();
|
|
||||||
if (init.getStep() == null || init.getStep() < 2) {
|
|
||||||
throw new BusinessException("请先完成前两步初始化");
|
|
||||||
}
|
|
||||||
LicenseInfo info = licenseValidator.parseAndValidate(dto.getLicenseKey().trim());
|
|
||||||
info = LicenseInfo.builder()
|
|
||||||
.subject(info.getSubject())
|
|
||||||
.companyName(StringUtils.hasText(info.getCompanyName()) ? info.getCompanyName() : init.getCompanyName())
|
|
||||||
.edition(info.getEdition())
|
|
||||||
.machineFingerprint(info.getMachineFingerprint())
|
|
||||||
.installationId(MachineFingerprintUtil.getMachineId())
|
|
||||||
.jti(info.getJti())
|
|
||||||
.issuer(info.getIssuer())
|
|
||||||
.features(info.getFeatures())
|
|
||||||
.issuedAt(info.getIssuedAt())
|
|
||||||
.expiresAt(info.getExpiresAt())
|
|
||||||
.rawLicenseKey(dto.getLicenseKey().trim())
|
|
||||||
.build();
|
|
||||||
licenseValidator.persistLicense(info);
|
|
||||||
init.setStep(3);
|
|
||||||
init.setUpdatedAt(LocalDateTime.now());
|
|
||||||
sysInitMapper.updateById(init);
|
|
||||||
return toSummary(info);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public LicenseSummaryVO updateLicense(ActivateLicenseDTO dto) {
|
|
||||||
if (!LicenseEnforcement.isEnforced()) {
|
|
||||||
throw new BusinessException("License 校验未启用,无法更新");
|
|
||||||
}
|
|
||||||
LicenseInfo info = licenseValidator.parseAndValidate(dto.getLicenseKey().trim());
|
|
||||||
licenseValidator.persistLicense(info);
|
|
||||||
return toSummary(info);
|
|
||||||
}
|
|
||||||
|
|
||||||
public LicenseSummaryVO getLicenseSummary() {
|
|
||||||
LicenseInfo info = licenseValidator.getCachedLicense();
|
|
||||||
if (info == null) {
|
|
||||||
throw new BusinessException("当前无有效 License");
|
|
||||||
}
|
|
||||||
return toSummary(info);
|
|
||||||
}
|
|
||||||
|
|
||||||
private LicenseSummaryVO toSummary(LicenseInfo info) {
|
|
||||||
LocalDateTime expiresAt = info.getExpiresAt() != null
|
|
||||||
? LocalDateTime.ofInstant(info.getExpiresAt(), java.time.ZoneId.systemDefault())
|
|
||||||
: null;
|
|
||||||
LocalDateTime issuedAt = info.getIssuedAt() != null
|
|
||||||
? LocalDateTime.ofInstant(info.getIssuedAt(), java.time.ZoneId.systemDefault())
|
|
||||||
: null;
|
|
||||||
Long daysRemaining = null;
|
|
||||||
String status = "active";
|
|
||||||
if (expiresAt != null) {
|
|
||||||
daysRemaining = ChronoUnit.DAYS.between(LocalDateTime.now(), expiresAt);
|
|
||||||
if (info.isExpired()) {
|
|
||||||
status = "expired";
|
|
||||||
} else if (daysRemaining <= 30) {
|
|
||||||
status = "expiring";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return LicenseSummaryVO.builder()
|
|
||||||
.companyName(info.getCompanyName())
|
|
||||||
.edition(info.getEdition())
|
|
||||||
.machineFingerprint(info.getMachineFingerprint())
|
|
||||||
.features(info.getFeatures() != null ? info.getFeatures() : List.of())
|
|
||||||
.issuedAt(issuedAt)
|
|
||||||
.expiresAt(expiresAt)
|
|
||||||
.daysRemaining(daysRemaining)
|
|
||||||
.status(status)
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
private SysInitPO getOrCreateInitRow() {
|
|
||||||
SysInitPO init = sysInitMapper.selectById(INIT_ROW_ID);
|
|
||||||
if (init == null) {
|
|
||||||
init = new SysInitPO();
|
|
||||||
init.setId(INIT_ROW_ID);
|
|
||||||
init.setStep(0);
|
|
||||||
init.setCreatedAt(LocalDateTime.now());
|
|
||||||
init.setUpdatedAt(LocalDateTime.now());
|
|
||||||
sysInitMapper.insert(init);
|
|
||||||
}
|
|
||||||
return init;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.sys.license.service;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseEnforcement;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseInfo;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseValidator;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.model.dto.ActivateLicenseDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.license.model.vo.LicenseSummaryVO;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* License 管理服务(不包含系统初始化逻辑)
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class LicenseService {
|
||||||
|
|
||||||
|
private final LicenseValidator licenseValidator;
|
||||||
|
|
||||||
|
public LicenseService(LicenseValidator licenseValidator) {
|
||||||
|
this.licenseValidator = licenseValidator;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public LicenseSummaryVO updateLicense(ActivateLicenseDTO dto) {
|
||||||
|
if (!LicenseEnforcement.isEnforced()) {
|
||||||
|
throw new BusinessException("License 校验未启用,无法更新");
|
||||||
|
}
|
||||||
|
LicenseInfo info = licenseValidator.parseAndValidate(dto.getLicenseKey().trim());
|
||||||
|
licenseValidator.persistLicense(info);
|
||||||
|
return toSummary(info);
|
||||||
|
}
|
||||||
|
|
||||||
|
public LicenseSummaryVO getLicenseSummary() {
|
||||||
|
LicenseInfo info = licenseValidator.getCachedLicense();
|
||||||
|
if (info == null) {
|
||||||
|
throw new BusinessException("当前无有效 License");
|
||||||
|
}
|
||||||
|
return toSummary(info);
|
||||||
|
}
|
||||||
|
|
||||||
|
public LicenseSummaryVO toSummary(LicenseInfo info) {
|
||||||
|
LocalDateTime expiresAt = info.getExpiresAt() != null
|
||||||
|
? LocalDateTime.ofInstant(info.getExpiresAt(), java.time.ZoneId.systemDefault())
|
||||||
|
: null;
|
||||||
|
LocalDateTime issuedAt = info.getIssuedAt() != null
|
||||||
|
? LocalDateTime.ofInstant(info.getIssuedAt(), java.time.ZoneId.systemDefault())
|
||||||
|
: null;
|
||||||
|
Long daysRemaining = null;
|
||||||
|
String status = "active";
|
||||||
|
if (expiresAt != null) {
|
||||||
|
daysRemaining = ChronoUnit.DAYS.between(LocalDateTime.now(), expiresAt);
|
||||||
|
if (info.isExpired()) {
|
||||||
|
status = "expired";
|
||||||
|
} else if (daysRemaining <= 30) {
|
||||||
|
status = "expiring";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return LicenseSummaryVO.builder()
|
||||||
|
.companyName(info.getCompanyName())
|
||||||
|
.edition(info.getEdition())
|
||||||
|
.machineFingerprint(info.getMachineFingerprint())
|
||||||
|
.features(info.getFeatures() != null ? info.getFeatures() : List.of())
|
||||||
|
.maxCompanies(info.getMaxCompaniesOrDefault())
|
||||||
|
.issuedAt(issuedAt)
|
||||||
|
.expiresAt(expiresAt)
|
||||||
|
.daysRemaining(daysRemaining)
|
||||||
|
.status(status)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -131,3 +131,10 @@ ecom:
|
|||||||
license-file: config/license.key
|
license-file: config/license.key
|
||||||
revocation-file: config/revoked.jti
|
revocation-file: config/revoked.jti
|
||||||
revalidate-interval: 10
|
revalidate-interval: 10
|
||||||
|
init:
|
||||||
|
auto-init: true
|
||||||
|
company-name: 系统公司
|
||||||
|
admin-login-code: admin
|
||||||
|
admin-real-name: 超级管理员
|
||||||
|
admin-phone: 13800000001
|
||||||
|
admin-password: admin123
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
-- ========================================
|
||||||
|
-- 系统基础数据初始化(权限、菜单、菜单-权限关联)
|
||||||
|
-- 由 SysInitDataService 在启动时检测并执行,仅在基础数据缺失时补齐
|
||||||
|
-- 所有 INSERT 使用 IGNORE 或 SELECT+NOT EXISTS,保证幂等
|
||||||
|
-- ========================================
|
||||||
|
|
||||||
|
-- ------------------------------------------------
|
||||||
|
-- 1. 基础权限(按模块划分,每个模块占 1000 区间)
|
||||||
|
-- 1000=系统管理 2000=组织管理 3000=电商业务 4000=数据管理 5000=开放接口
|
||||||
|
-- ------------------------------------------------
|
||||||
|
INSERT IGNORE INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) VALUES
|
||||||
|
-- 系统管理
|
||||||
|
(1000, NULL, 'MODULE:system', '系统管理', 'module', 1, '系统管理模块', 10),
|
||||||
|
(1001, 1000, 'system:user:read', '用户查看', 'api', 1, '系统管理-用户查看', 100),
|
||||||
|
(1002, 1000, 'system:user:create', '用户创建', 'api', 1, '系统管理-用户创建', 101),
|
||||||
|
(1003, 1000, 'system:user:update', '用户更新', 'api', 1, '系统管理-用户更新', 102),
|
||||||
|
(1004, 1000, 'system:user:delete', '用户删除', 'api', 1, '系统管理-用户删除', 103),
|
||||||
|
(1005, 1000, 'system:menu:read', '菜单查看', 'api', 1, '系统管理-菜单查看', 110),
|
||||||
|
(1006, 1000, 'system:menu:create', '菜单创建', 'api', 1, '系统管理-菜单创建', 111),
|
||||||
|
(1007, 1000, 'system:menu:update', '菜单更新', 'api', 1, '系统管理-菜单更新', 112),
|
||||||
|
(1008, 1000, 'system:menu:delete', '菜单删除', 'api', 1, '系统管理-菜单删除', 113),
|
||||||
|
(1009, 1000, 'system:permission:read', '权限查看', 'api', 1, '系统管理-权限查看', 120),
|
||||||
|
(1010, 1000, 'system:position:manage', '职位管理', 'api', 1, '系统管理-职位管理', 130),
|
||||||
|
(1011, 1000, 'system:company:manage', '公司管理', 'api', 1, '系统管理-公司管理', 140),
|
||||||
|
|
||||||
|
-- 组织管理
|
||||||
|
(2000, NULL, 'MODULE:org', '组织架构', 'module', 1, '组织架构模块', 20),
|
||||||
|
(2001, 2000, 'org:company:read', '公司查看', 'api', 1, '组织管理-公司查看', 200),
|
||||||
|
(2002, 2000, 'org:company:create', '公司创建', 'api', 1, '组织管理-公司创建', 201),
|
||||||
|
(2003, 2000, 'org:company:update', '公司更新', 'api', 1, '组织管理-公司更新', 202),
|
||||||
|
(2004, 2000, 'org:company:delete', '公司删除', 'api', 1, '组织管理-公司删除', 203),
|
||||||
|
(2005, 2000, 'org:department:read', '部门查看', 'api', 1, '组织管理-部门查看', 210),
|
||||||
|
(2006, 2000, 'org:department:manage', '部门管理', 'api', 1, '组织管理-部门管理', 211),
|
||||||
|
(2007, 2000, 'org:position:read', '职位查看', 'api', 1, '组织管理-职位查看', 220),
|
||||||
|
(2008, 2000, 'org:position:manage', '职位管理', 'api', 1, '组织管理-职位管理', 221),
|
||||||
|
(2009, 2000, 'org:member:read', '成员查看', 'api', 1, '组织管理-成员查看', 230),
|
||||||
|
(2010, 2000, 'org:member:manage', '成员管理', 'api', 1, '组织管理-成员管理', 231),
|
||||||
|
(2011, 2000, 'org:company-menu:assign', '公司菜单分配', 'api', 1, '组织管理-公司菜单分配', 240),
|
||||||
|
(2012, 2000, 'org:company-permission:assign', '公司权限分配', 'api', 1, '组织管理-公司权限分配', 241),
|
||||||
|
(2013, 2000, 'org:position-menu:assign', '职位菜单分配', 'api', 1, '组织管理-职位菜单分配', 242),
|
||||||
|
(2014, 2000, 'org:position-permission:assign', '职位权限分配', 'api', 1, '组织管理-职位权限分配', 243),
|
||||||
|
|
||||||
|
-- 电商业务
|
||||||
|
(3000, NULL, 'MODULE:ecom', '电商业务', 'module', 1, '电商业务模块', 30),
|
||||||
|
(3001, 3000, 'ecom:order:read', '订单查看', 'api', 1, '电商业务-订单查看', 300),
|
||||||
|
(3002, 3000, 'ecom:order:create', '订单创建', 'api', 1, '电商业务-订单创建', 301),
|
||||||
|
(3003, 3000, 'ecom:order:update', '订单更新', 'api', 1, '电商业务-订单更新', 302),
|
||||||
|
(3004, 3000, 'ecom:order:delete', '订单删除', 'api', 1, '电商业务-订单删除', 303),
|
||||||
|
(3005, 3000, 'ecom:order:import', '订单导入', 'api', 1, '电商业务-订单导入', 304),
|
||||||
|
(3006, 3000, 'ecom:order:export', '订单导出', 'api', 1, '电商业务-订单导出', 305),
|
||||||
|
(3007, 3000, 'ecom:product:read', '商品查看', 'api', 1, '电商业务-商品查看', 310),
|
||||||
|
(3008, 3000, 'ecom:product:create', '商品创建', 'api', 1, '电商业务-商品创建', 311),
|
||||||
|
(3009, 3000, 'ecom:product:update', '商品更新', 'api', 1, '电商业务-商品更新', 312),
|
||||||
|
(3010, 3000, 'ecom:product:delete', '商品删除', 'api', 1, '电商业务-商品删除', 313),
|
||||||
|
(3011, 3000, 'ecom:shop:read', '店铺查看', 'api', 1, '电商业务-店铺查看', 320),
|
||||||
|
(3012, 3000, 'ecom:shop:manage', '店铺管理', 'api', 1, '电商业务-店铺管理', 321),
|
||||||
|
|
||||||
|
-- 数据管理
|
||||||
|
(4000, NULL, 'MODULE:data', '数据管理', 'module', 1, '数据管理模块', 40),
|
||||||
|
(4001, 4000, 'data:import', '数据导入', 'api', 1, '数据管理-数据导入', 400),
|
||||||
|
(4002, 4000, 'data:export', '数据导出', 'api', 1, '数据管理-数据导出', 401),
|
||||||
|
|
||||||
|
-- 开放接口
|
||||||
|
(5000, NULL, 'MODULE:open', '开放接口', 'module', 1, '开放接口模块', 50),
|
||||||
|
(5001, 5000, 'open:api-key:manage', 'API Key管理', 'api', 1, '开放接口-API Key管理', 500);
|
||||||
|
|
||||||
|
-- ------------------------------------------------
|
||||||
|
-- 2. 基础菜单(目录 + 菜单)
|
||||||
|
-- 父级目录使用固定 id,子菜单通过名称子查询关联,兼容迁移已存在的数据
|
||||||
|
-- ------------------------------------------------
|
||||||
|
|
||||||
|
-- 系统管理目录
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
VALUES (10000, NULL, 0, 'System', '系统管理', '/system', 'BasicLayout', 'lucide:settings', 'catalog', 1, 1, 100);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'UserManagement', '用户管理', '/system/user', '/system/user/index', 'lucide:users', 'menu', 1, 1, 1
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'System';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'MenuManagement', '菜单管理', '/system/menu', '/system/menu/index', 'lucide:menu', 'menu', 1, 1, 2
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'System';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'PermissionManagement', '权限管理', '/system/permission', '/system/permission/index', 'lucide:shield', 'menu', 1, 1, 3
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'System';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'CompanyManagement', '公司管理', '/system/company', '/system/company/index', 'lucide:building-2', 'menu', 1, 1, 4
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'System';
|
||||||
|
|
||||||
|
-- 组织管理目录
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
VALUES (11000, NULL, 0, 'Org', '组织管理', '/org', 'BasicLayout', 'lucide:building', 'catalog', 1, 1, 200);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'OrgCompanyManagement', '公司管理', '/org/company', '/org/company/index', 'lucide:building-2', 'menu', 1, 1, 1
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Org';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'DepartmentManagement', '部门管理', '/org/department', '/org/department/index', 'lucide:git-branch', 'menu', 1, 1, 2
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Org';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'PositionManagement', '职位管理', '/org/position', '/org/position/index', 'lucide:briefcase', 'menu', 1, 1, 3
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Org';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'MemberManagement', '成员管理', '/org/member', '/org/member/index', 'lucide:user-cog', 'menu', 1, 1, 4
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Org';
|
||||||
|
|
||||||
|
-- 电商业务目录
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
VALUES (12000, NULL, 0, 'Ecom', '电商业务', '/ecom', 'BasicLayout', 'lucide:shopping-cart', 'catalog', 1, 1, 300);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'OrderManagement', '订单管理', '/ecom/order', '/ecom/order/index', 'lucide:clipboard-list', 'menu', 1, 1, 1
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Ecom';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'ProductManagement', '商品管理', '/ecom/product', '/ecom/product/index', 'lucide:package', 'menu', 1, 1, 2
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Ecom';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'ShopManagement', '店铺管理', '/ecom/shop', '/ecom/shop/index', 'lucide:store', 'menu', 1, 1, 3
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Ecom';
|
||||||
|
|
||||||
|
-- 数据管理目录
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
VALUES (13000, NULL, 0, 'Data', '数据管理', '/data', 'BasicLayout', 'lucide:database', 'catalog', 1, 1, 400);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'DataImport', '数据导入', '/data/import', '/data/import/index', 'lucide:upload', 'menu', 1, 1, 1
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Data';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'DataExport', '数据导出', '/data/export', '/data/export/index', 'lucide:download', 'menu', 1, 1, 2
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'Data';
|
||||||
|
|
||||||
|
-- 开放接口目录
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
VALUES (14000, NULL, 0, 'OpenApi', '开放接口', '/open', 'BasicLayout', 'lucide:key-round', 'catalog', 1, 1, 900);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `icon`, `type`, `visible`, `status`, `order`)
|
||||||
|
SELECT p.id, 0, 'OpenApiKeyManagement', 'API Key 管理', '/open/api-key', '/open/api-key/index', 'lucide:key', 'menu', 1, 1, 1
|
||||||
|
FROM `sys_menu` p WHERE p.name = 'OpenApi';
|
||||||
|
|
||||||
|
-- ------------------------------------------------
|
||||||
|
-- 3. 菜单-权限关联(通过 code/name 子查询,避免硬编码 id)
|
||||||
|
-- ------------------------------------------------
|
||||||
|
|
||||||
|
-- 用户管理菜单 -> system:user:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'system:user:%' WHERE m.name = 'UserManagement';
|
||||||
|
|
||||||
|
-- 菜单管理 -> system:menu:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'system:menu:%' WHERE m.name = 'MenuManagement';
|
||||||
|
|
||||||
|
-- 权限管理 -> system:permission:read
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'system:permission:read' WHERE m.name = 'PermissionManagement';
|
||||||
|
|
||||||
|
-- 平台公司管理 -> system:company:manage
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'system:company:manage' WHERE m.name = 'CompanyManagement';
|
||||||
|
|
||||||
|
-- 组织-公司管理 -> org:company:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'org:company:%' WHERE m.name = 'OrgCompanyManagement';
|
||||||
|
|
||||||
|
-- 部门管理 -> org:department:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'org:department:%' WHERE m.name = 'DepartmentManagement';
|
||||||
|
|
||||||
|
-- 职位管理 -> org:position:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'org:position:%' WHERE m.name = 'PositionManagement';
|
||||||
|
|
||||||
|
-- 成员管理 -> org:member:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'org:member:%' WHERE m.name = 'MemberManagement';
|
||||||
|
|
||||||
|
-- 订单管理 -> ecom:order:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ecom:order:%' WHERE m.name = 'OrderManagement';
|
||||||
|
|
||||||
|
-- 商品管理 -> ecom:product:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ecom:product:%' WHERE m.name = 'ProductManagement';
|
||||||
|
|
||||||
|
-- 店铺管理 -> ecom:shop:*
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ecom:shop:%' WHERE m.name = 'ShopManagement';
|
||||||
|
|
||||||
|
-- 数据导入 -> data:import
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'data:import' WHERE m.name = 'DataImport';
|
||||||
|
|
||||||
|
-- 数据导出 -> data:export
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'data:export' WHERE m.name = 'DataExport';
|
||||||
|
|
||||||
|
-- API Key 管理 -> open:api-key:manage
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'open:api-key:manage' WHERE m.name = 'OpenApiKeyManagement';
|
||||||
@@ -41,6 +41,7 @@ CREATE TABLE IF NOT EXISTS lc_license (
|
|||||||
expires_at TIMESTAMP NOT NULL,
|
expires_at TIMESTAMP NOT NULL,
|
||||||
revoked_at TIMESTAMP NULL,
|
revoked_at TIMESTAMP NULL,
|
||||||
max_activations INT NULL,
|
max_activations INT NULL,
|
||||||
|
max_companies INT NULL COMMENT '允许创建的最大公司数量,NULL 表示使用版本默认值',
|
||||||
activation_count INT NOT NULL DEFAULT 0,
|
activation_count INT NOT NULL DEFAULT 0,
|
||||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ export interface SignLicenseInput {
|
|||||||
edition: string;
|
edition: string;
|
||||||
features: string[];
|
features: string[];
|
||||||
expiresAt: Date;
|
expiresAt: Date;
|
||||||
|
maxCompanies?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SignLicenseResult {
|
export interface SignLicenseResult {
|
||||||
@@ -43,12 +44,16 @@ export class JwtSignerService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
const jti = uuidv4();
|
const jti = uuidv4();
|
||||||
const issuedAt = new Date();
|
const issuedAt = new Date();
|
||||||
const licenseKey = await new SignJWT({
|
const claims: Record<string, unknown> = {
|
||||||
company: input.company,
|
company: input.company,
|
||||||
machineFingerprint: input.machineFingerprint,
|
machineFingerprint: input.machineFingerprint,
|
||||||
edition: input.edition,
|
edition: input.edition,
|
||||||
features: input.features,
|
features: input.features,
|
||||||
})
|
};
|
||||||
|
if (input.maxCompanies != null && input.maxCompanies > 0) {
|
||||||
|
claims.maxCompanies = input.maxCompanies;
|
||||||
|
}
|
||||||
|
const licenseKey = await new SignJWT(claims)
|
||||||
.setProtectedHeader({ alg: 'EdDSA', typ: 'JWT', kid: this.kid })
|
.setProtectedHeader({ alg: 'EdDSA', typ: 'JWT', kid: this.kid })
|
||||||
.setIssuer('ecom-license-server')
|
.setIssuer('ecom-license-server')
|
||||||
.setSubject(input.sub)
|
.setSubject(input.sub)
|
||||||
|
|||||||
@@ -51,6 +51,9 @@ export class LcLicense {
|
|||||||
@Column({ name: 'max_activations', type: 'int', nullable: true })
|
@Column({ name: 'max_activations', type: 'int', nullable: true })
|
||||||
maxActivations!: number | null;
|
maxActivations!: number | null;
|
||||||
|
|
||||||
|
@Column({ name: 'max_companies', type: 'int', nullable: true })
|
||||||
|
maxCompanies!: number | null;
|
||||||
|
|
||||||
@Column({ name: 'activation_count', type: 'int', default: 0 })
|
@Column({ name: 'activation_count', type: 'int', default: 0 })
|
||||||
activationCount!: number;
|
activationCount!: number;
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,12 @@ export class GenerateLicenseDto {
|
|||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
features!: string[];
|
features!: string[];
|
||||||
|
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@IsOptional()
|
||||||
|
maxCompanies?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class LicenseQueryDto {
|
export class LicenseQueryDto {
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ export class LicenseService {
|
|||||||
edition: dto.edition,
|
edition: dto.edition,
|
||||||
features: dto.features,
|
features: dto.features,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
|
maxCompanies: dto.maxCompanies,
|
||||||
});
|
});
|
||||||
const license = this.licenseRepo.create({
|
const license = this.licenseRepo.create({
|
||||||
customerId: customer.id,
|
customerId: customer.id,
|
||||||
@@ -74,6 +75,7 @@ export class LicenseService {
|
|||||||
issuedAt: signed.issuedAt,
|
issuedAt: signed.issuedAt,
|
||||||
expiresAt: signed.expiresAt,
|
expiresAt: signed.expiresAt,
|
||||||
activationCount: 0,
|
activationCount: 0,
|
||||||
|
maxCompanies: dto.maxCompanies ?? null,
|
||||||
});
|
});
|
||||||
const saved = await this.licenseRepo.save(license);
|
const saved = await this.licenseRepo.save(license);
|
||||||
return {
|
return {
|
||||||
@@ -82,6 +84,7 @@ export class LicenseService {
|
|||||||
jti: saved.jti,
|
jti: saved.jti,
|
||||||
edition: saved.edition,
|
edition: saved.edition,
|
||||||
machineFingerprint: saved.machineFingerprint,
|
machineFingerprint: saved.machineFingerprint,
|
||||||
|
maxCompanies: saved.maxCompanies,
|
||||||
expiresAt: saved.expiresAt,
|
expiresAt: saved.expiresAt,
|
||||||
status: saved.status,
|
status: saved.status,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ interface GenerateResult {
|
|||||||
jti: string;
|
jti: string;
|
||||||
edition: string;
|
edition: string;
|
||||||
machineFingerprint: string;
|
machineFingerprint: string;
|
||||||
|
maxCompanies: number | null;
|
||||||
expiresAt: string;
|
expiresAt: string;
|
||||||
status: string;
|
status: string;
|
||||||
}
|
}
|
||||||
@@ -114,6 +115,14 @@ async function licenseGenerate() {
|
|||||||
validate: (v) => v.startsWith('FP-') || v === '*' || '格式应为 FP-...',
|
validate: (v) => v.startsWith('FP-') || v === '*' || '格式应为 FP-...',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const defaultMaxCompanies = fingerprint === '*' ? 100 : 2;
|
||||||
|
const maxCompaniesInput = await input({
|
||||||
|
message: `最大公司数量(默认 ${defaultMaxCompanies})`,
|
||||||
|
default: String(defaultMaxCompanies),
|
||||||
|
validate: (v) => /^\d+$/.test(v) || '请输入正整数',
|
||||||
|
});
|
||||||
|
const maxCompanies = Number(maxCompaniesInput);
|
||||||
|
|
||||||
const edition = await select({
|
const edition = await select({
|
||||||
message: '版本类型',
|
message: '版本类型',
|
||||||
choices: [
|
choices: [
|
||||||
@@ -157,6 +166,7 @@ async function licenseGenerate() {
|
|||||||
`客户 ID: ${customerId}`,
|
`客户 ID: ${customerId}`,
|
||||||
`公司: ${company}`,
|
`公司: ${company}`,
|
||||||
`指纹: ${fingerprint}`,
|
`指纹: ${fingerprint}`,
|
||||||
|
`最大公司数: ${maxCompanies}`,
|
||||||
`版本: ${edition}`,
|
`版本: ${edition}`,
|
||||||
`过期: ${expiresAt}`,
|
`过期: ${expiresAt}`,
|
||||||
`功能: ${features.join(', ')}`,
|
`功能: ${features.join(', ')}`,
|
||||||
@@ -171,6 +181,7 @@ async function licenseGenerate() {
|
|||||||
edition,
|
edition,
|
||||||
expiresAt: new Date(expiresAt).toISOString(),
|
expiresAt: new Date(expiresAt).toISOString(),
|
||||||
features,
|
features,
|
||||||
|
maxCompanies,
|
||||||
});
|
});
|
||||||
|
|
||||||
printBox(
|
printBox(
|
||||||
@@ -178,6 +189,7 @@ async function licenseGenerate() {
|
|||||||
[
|
[
|
||||||
`ID: ${result.id}`,
|
`ID: ${result.id}`,
|
||||||
`JTI: ${result.jti}`,
|
`JTI: ${result.jti}`,
|
||||||
|
`最大公司数: ${result.maxCompanies ?? (fingerprint === '*' ? 100 : 2)}`,
|
||||||
`过期: ${result.expiresAt?.slice(0, 10)}`,
|
`过期: ${result.expiresAt?.slice(0, 10)}`,
|
||||||
'',
|
'',
|
||||||
result.licenseKey,
|
result.licenseKey,
|
||||||
|
|||||||
Reference in New Issue
Block a user