package cn.iocoder.yudao.module.hrm.service.salary; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.util.object.BeanUtils; import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.hrm.controller.admin.salary.vo.HrmSocialSecuritySchemeImportExcelVO; import cn.iocoder.yudao.module.hrm.controller.admin.salary.vo.HrmSocialSecuritySchemeImportRespVO; import cn.iocoder.yudao.module.hrm.controller.admin.salary.vo.HrmSocialSecuritySchemeSaveReqVO; import cn.iocoder.yudao.module.hrm.dal.dataobject.salary.HrmSocialSecuritySchemeDO; import cn.iocoder.yudao.module.hrm.dal.dataobject.salary.HrmSocialSecuritySchemeDeptDO; import cn.iocoder.yudao.module.hrm.dal.mysql.salary.HrmSocialSecuritySchemeDeptMapper; import cn.iocoder.yudao.module.hrm.dal.mysql.salary.HrmSocialSecuritySchemeMapper; import cn.iocoder.yudao.module.hrm.util.HrmImportUtils; import cn.iocoder.yudao.module.system.api.dept.DeptApi; import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO; import jakarta.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList; import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.*; /** * 社保公积金方案 Service 实现类 * * 方案的缴纳比例按「方案 - 适用部门」关联表生效;一个部门只能绑定一个方案,未绑定任何部门的方案作为全局默认方案。 * * @author 超级管理员 */ @Service @Validated public class HrmSocialSecuritySchemeServiceImpl implements HrmSocialSecuritySchemeService { /** * 启用状态 */ private static final Integer STATUS_ENABLE = 0; @Resource private HrmSocialSecuritySchemeMapper schemeMapper; @Resource private HrmSocialSecuritySchemeDeptMapper schemeDeptMapper; @Resource private DeptApi deptApi; @Override @Transactional(rollbackFor = Exception.class) public Long createScheme(HrmSocialSecuritySchemeSaveReqVO createReqVO) { HrmSocialSecuritySchemeDO scheme = BeanUtils.toBean(createReqVO, HrmSocialSecuritySchemeDO.class); schemeMapper.insert(scheme); saveSchemeDepts(scheme.getId(), createReqVO.getName(), createReqVO.getDeptIds()); return scheme.getId(); } @Override @Transactional(rollbackFor = Exception.class) public void updateScheme(HrmSocialSecuritySchemeSaveReqVO updateReqVO) { validateSchemeExists(updateReqVO.getId()); schemeMapper.updateById(BeanUtils.toBean(updateReqVO, HrmSocialSecuritySchemeDO.class)); saveSchemeDepts(updateReqVO.getId(), updateReqVO.getName(), updateReqVO.getDeptIds()); } @Override @Transactional(rollbackFor = Exception.class) public void deleteScheme(Long id) { validateSchemeExists(id); schemeDeptMapper.deleteBySchemeId(id); schemeMapper.deleteById(id); } @Override public HrmSocialSecuritySchemeDO getScheme(Long id) { return schemeMapper.selectById(id); } @Override public List getSchemeList(Integer status) { return schemeMapper.selectListByStatus(status); } @Override public List getSchemeDeptIds(Long schemeId) { return schemeDeptMapper.selectListBySchemeId(schemeId).stream() .map(HrmSocialSecuritySchemeDeptDO::getDeptId) .toList(); } @Override public Map> getSchemeDeptIdMap(Collection schemeIds) { if (CollUtil.isEmpty(schemeIds)) { return Map.of(); } return schemeDeptMapper.selectListBySchemeIds(schemeIds).stream() .collect(Collectors.groupingBy(HrmSocialSecuritySchemeDeptDO::getSchemeId, Collectors.mapping(HrmSocialSecuritySchemeDeptDO::getDeptId, Collectors.toList()))); } @Override public HrmSocialSecuritySchemeDO resolveSchemeByDeptId(Long deptId, LocalDate periodDate) { // 1. 优先取该部门绑定的方案 if (deptId != null) { List boundSchemeIds = schemeDeptMapper.selectListByDeptId(deptId).stream() .map(HrmSocialSecuritySchemeDeptDO::getSchemeId) .toList(); HrmSocialSecuritySchemeDO scheme = pickLatestEnabled(boundSchemeIds, periodDate); if (scheme != null) { return scheme; } } // 2. 兜底取全局默认方案:未绑定任何部门的方案中生效日期最新者 Set boundSchemeIds = schemeDeptMapper.selectAllBoundSchemeIds(); List globalSchemeIds = schemeMapper.selectListByStatus(STATUS_ENABLE).stream() .map(HrmSocialSecuritySchemeDO::getId) .filter(id -> !boundSchemeIds.contains(id)) .toList(); return pickLatestEnabled(globalSchemeIds, periodDate); } /** * 从候选方案中取「生效日期不晚于核算期间」的最新一条启用方案 * * 若全部候选方案都晚于核算期间(例如刚建好下月才生效的方案就提前核算),则退化为取其中生效日期最新的一条, * 避免核算金额静默落到代码里的默认比例上。 */ private HrmSocialSecuritySchemeDO pickLatestEnabled(Collection schemeIds, LocalDate periodDate) { if (CollUtil.isEmpty(schemeIds)) { return null; } List schemes = schemeMapper.selectList( new LambdaQueryWrapperX() .in(HrmSocialSecuritySchemeDO::getId, schemeIds) .eq(HrmSocialSecuritySchemeDO::getStatus, STATUS_ENABLE) .orderByDesc(HrmSocialSecuritySchemeDO::getEffectiveDate) .orderByDesc(HrmSocialSecuritySchemeDO::getId)); if (CollUtil.isEmpty(schemes)) { return null; } return schemes.stream() .filter(scheme -> scheme.getEffectiveDate() == null || !scheme.getEffectiveDate().isAfter(periodDate)) .findFirst() .orElse(schemes.get(0)); } /** * 整组替换方案的适用部门:先校验,再删旧行、插新行 */ private void saveSchemeDepts(Long schemeId, String schemeName, List deptIds) { List distinctDeptIds = CollUtil.isEmpty(deptIds) ? List.of() : deptIds.stream().filter(Objects::nonNull).distinct().toList(); if (CollUtil.isNotEmpty(distinctDeptIds)) { // 部门必须存在 deptApi.validateDeptList(distinctDeptIds); // 一个部门只能绑定一个方案 validateDeptNotBoundByOtherScheme(schemeId, schemeName, distinctDeptIds); } schemeDeptMapper.deleteBySchemeId(schemeId); distinctDeptIds.forEach(deptId -> schemeDeptMapper.insert( HrmSocialSecuritySchemeDeptDO.builder().schemeId(schemeId).deptId(deptId).build())); } /** * 校验这些部门没有被别的方案占用 */ private void validateDeptNotBoundByOtherScheme(Long schemeId, String schemeName, List deptIds) { List bindings = schemeDeptMapper.selectListByDeptIds(deptIds); if (CollUtil.isEmpty(bindings)) { return; } // 名称解析只放在异常分支,避免正常保存多查表 for (HrmSocialSecuritySchemeDeptDO binding : bindings) { if (Objects.equals(binding.getSchemeId(), schemeId)) { continue; } HrmSocialSecuritySchemeDO otherScheme = schemeMapper.selectById(binding.getSchemeId()); DeptRespDTO dept = deptApi.getDept(binding.getDeptId()); throw exception(SOCIAL_SECURITY_SCHEME_DEPT_EXISTS, dept != null ? dept.getName() : "ID=" + binding.getDeptId(), otherScheme != null ? otherScheme.getName() : "ID=" + binding.getSchemeId(), schemeName); } } @Override @Transactional(rollbackFor = Exception.class) public HrmSocialSecuritySchemeImportRespVO importSocialSecuritySchemeList( List importList, Boolean updateSupport) { // 1. 过滤空行(方案名称为空视为空行) importList = filterList(importList, item -> StrUtil.isNotBlank(item.getName())); if (CollUtil.isEmpty(importList)) { throw exception(HRM_IMPORT_LIST_IS_EMPTY); } // 2. 预加载部门名称索引、已有方案名称索引 Map> deptIdMap = HrmImportUtils.groupDeptIdsByName(deptApi); Map existingMap = getSchemeList(null).stream() .collect(Collectors.toMap(HrmSocialSecuritySchemeDO::getName, item -> item, (a, b) -> a)); // 3. 逐行导入 HrmSocialSecuritySchemeImportRespVO respVO = HrmSocialSecuritySchemeImportRespVO.builder() .createNames(new ArrayList<>()) .updateNames(new ArrayList<>()) .failureNames(new LinkedHashMap<>()) .build(); for (int i = 0; i < importList.size(); i++) { HrmSocialSecuritySchemeImportExcelVO row = importList.get(i); String rowKey = "第" + (i + 2) + "行"; try { String name = HrmImportUtils.requireText(row.getName(), "方案名称"); if (row.getEffectiveDate() == null) { throw exception(HRM_IMPORT_FIELD_REQUIRED, "生效日期"); } validateRatios(row); List deptIds = parseDeptIds(row.getDeptNames(), deptIdMap); Integer status = StrUtil.isBlank(row.getStatus()) ? STATUS_ENABLE : HrmImportUtils.matchEnum(row.getStatus(), "状态", new String[]{"启用", "禁用"}, new Integer[]{0, 1}); HrmSocialSecuritySchemeSaveReqVO reqVO = new HrmSocialSecuritySchemeSaveReqVO(); reqVO.setName(name); reqVO.setEffectiveDate(row.getEffectiveDate()); reqVO.setPensionCompanyRatio(row.getPensionCompanyRatio()); reqVO.setPensionPersonalRatio(row.getPensionPersonalRatio()); reqVO.setMedicalCompanyRatio(row.getMedicalCompanyRatio()); reqVO.setMedicalPersonalRatio(row.getMedicalPersonalRatio()); reqVO.setUnemploymentCompanyRatio(row.getUnemploymentCompanyRatio()); reqVO.setUnemploymentPersonalRatio(row.getUnemploymentPersonalRatio()); reqVO.setWorkInjuryRatio(row.getWorkInjuryRatio()); reqVO.setMaternityRatio(row.getMaternityRatio()); reqVO.setHousingFundCompanyRatio(row.getHousingFundCompanyRatio()); reqVO.setHousingFundPersonalRatio(row.getHousingFundPersonalRatio()); reqVO.setDefaultSocialSecurityBase(row.getDefaultSocialSecurityBase()); reqVO.setDefaultHousingFundBase(row.getDefaultHousingFundBase()); reqVO.setRemark(row.getRemark()); reqVO.setStatus(status); reqVO.setDeptIds(deptIds); HrmSocialSecuritySchemeDO existing = existingMap.get(name); if (existing != null) { if (!Boolean.TRUE.equals(updateSupport)) { throw new ServiceException(HRM_IMPORT_DATA_EXISTS.getCode(), "方案名称【" + name + "】已存在,如需覆盖请勾选「已存在时更新」"); } reqVO.setId(existing.getId()); updateScheme(reqVO); respVO.getUpdateNames().add(name); continue; } createScheme(reqVO); respVO.getCreateNames().add(name); } catch (ServiceException ex) { respVO.getFailureNames().put(rowKey, ex.getMessage()); } catch (Exception ex) { respVO.getFailureNames().put(rowKey, "导入失败:" + ex.getMessage()); } } return respVO; } /** * 缴纳比例统一按小数填写(16% 填 0.16),超过 1 基本是把百分数直接填进来了 */ private void validateRatios(HrmSocialSecuritySchemeImportExcelVO row) { validateRatio("养老保险企业比例", row.getPensionCompanyRatio()); validateRatio("养老保险个人比例", row.getPensionPersonalRatio()); validateRatio("医疗保险企业比例", row.getMedicalCompanyRatio()); validateRatio("医疗保险个人比例", row.getMedicalPersonalRatio()); validateRatio("失业保险企业比例", row.getUnemploymentCompanyRatio()); validateRatio("失业保险个人比例", row.getUnemploymentPersonalRatio()); validateRatio("工伤保险企业比例", row.getWorkInjuryRatio()); validateRatio("生育保险企业比例", row.getMaternityRatio()); validateRatio("公积金企业比例", row.getHousingFundCompanyRatio()); validateRatio("公积金个人比例", row.getHousingFundPersonalRatio()); } private void validateRatio(String label, BigDecimal value) { if (value == null) { return; } if (value.compareTo(BigDecimal.ZERO) < 0 || value.compareTo(BigDecimal.ONE) > 0) { throw exception(HRM_IMPORT_FIELD_INVALID, label, value.toPlainString(), "0 到 1 之间的小数(如 16% 填 0.16),无需缴纳填 0"); } } /** * 适用部门按顿号/逗号分隔的部门名称解析为 ID 列表,为空表示全局默认方案 */ private List parseDeptIds(String deptNames, Map> deptIdMap) { if (StrUtil.isBlank(deptNames)) { return List.of(); } return Arrays.stream(deptNames.split("[,,、;;\\s]+")) .map(String::trim) .filter(StrUtil::isNotBlank) .map(deptName -> HrmImportUtils.resolveDeptId(deptIdMap, deptName, "适用部门")) .distinct() .collect(Collectors.toList()); } private HrmSocialSecuritySchemeDO validateSchemeExists(Long id) { HrmSocialSecuritySchemeDO scheme = schemeMapper.selectById(id); if (scheme == null) { throw exception(SOCIAL_SECURITY_SCHEME_NOT_EXISTS); } return scheme; } }