| | |
| | | package cn.iocoder.yudao.module.erp.service.purchase; |
| | | |
| | | import cn.hutool.core.collection.CollUtil; |
| | | import cn.hutool.core.util.StrUtil; |
| | | import cn.iocoder.yudao.framework.common.pojo.PageResult; |
| | | import cn.iocoder.yudao.framework.common.util.object.BeanUtils; |
| | | import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi; |
| | | import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO; |
| | | import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmProcessDefinitionInfoDO; |
| | | import cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum; |
| | | import cn.iocoder.yudao.module.bpm.service.definition.BpmCategoryService; |
| | | import cn.iocoder.yudao.module.bpm.service.definition.BpmProcessDefinitionService; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.plan.ErpPurchasePlanPageReqVO; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.plan.ErpPurchasePlanRespVO; |
| | | import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.plan.ErpPurchasePlanSaveReqVO; |
| | | import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchasePlanDO; |
| | | import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchasePlanItemDO; |
| | |
| | | import cn.iocoder.yudao.module.erp.dal.redis.no.ErpNoRedisDAO; |
| | | import cn.iocoder.yudao.module.erp.enums.ErpPurchasePlanStatusEnum; |
| | | import cn.iocoder.yudao.module.erp.enums.ErpPurchaseRequestStatusEnum; |
| | | import cn.iocoder.yudao.module.mes.api.item.MesMdItemApi; |
| | | import cn.iocoder.yudao.module.mes.api.item.dto.MesMdItemSafetyStockRespDTO; |
| | | import cn.iocoder.yudao.module.mdm.api.item.MdmItemApi; |
| | | import cn.iocoder.yudao.module.mdm.api.item.dto.MdmItemRespDTO; |
| | | import cn.iocoder.yudao.module.mes.api.wms.MesWmStockApi; |
| | | import cn.iocoder.yudao.module.system.api.approval.ApprovalConfigApi; |
| | | import cn.iocoder.yudao.module.system.api.user.AdminUserApi; |
| | | import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO; |
| | | import jakarta.annotation.Resource; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.flowable.engine.repository.ProcessDefinition; |
| | | 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.time.LocalDateTime; |
| | | import java.util.*; |
| | | |
| | | import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; |
| | | import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList; |
| | | import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; |
| | | import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*; |
| | | |
| | | /** |
| | |
| | | public class ErpPurchasePlanServiceImpl implements ErpPurchasePlanService { |
| | | |
| | | /** |
| | | * BPM 采购计划审批分类编码 |
| | | * 通用审批配置的业务类型编码(对应 system_approval_config.biz_type) |
| | | */ |
| | | private static final String PURCHASE_PLAN_APPROVE_CATEGORY_CODE = "purchase_plan_approve"; |
| | | private static final String PURCHASE_PLAN_APPROVE_BIZ_TYPE = "purchase_plan_approve"; |
| | | |
| | | /** |
| | | * 需求来源:库存预警 |
| | |
| | | private ErpNoRedisDAO noRedisDAO; |
| | | |
| | | @Resource |
| | | private BpmProcessInstanceApi processInstanceApi; |
| | | @Resource |
| | | private BpmCategoryService bpmCategoryService; |
| | | @Resource |
| | | private BpmProcessDefinitionService bpmProcessDefinitionService; |
| | | private ApprovalConfigApi approvalConfigApi; |
| | | |
| | | @Resource |
| | | private AdminUserApi adminUserApi; |
| | | |
| | | @Resource |
| | | private MesMdItemApi mesMdItemApi; |
| | | private MdmItemApi mdmItemApi; |
| | | @Resource |
| | | private MesWmStockApi mesWmStockApi; |
| | | |
| | |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void submitPurchasePlan(Long id, String processDefinitionKey, Long userId) { |
| | | // 1. 校验存在 + 草稿状态 |
| | | ErpPurchasePlanDO plan = validatePurchasePlanCanModify(id); |
| | | public void submitPurchasePlan(Long id) { |
| | | // 1. 校验存在 + 可提交状态(草稿 / 审核不通过) |
| | | ErpPurchasePlanDO plan = validatePurchasePlanExists(id); |
| | | if (!ErpPurchasePlanStatusEnum.DRAFT.getStatus().equals(plan.getStatus()) |
| | | && !ErpPurchasePlanStatusEnum.REJECT.getStatus().equals(plan.getStatus())) { |
| | | throw exception(PURCHASE_PLAN_SUBMIT_FAIL_NOT_ALLOWED); |
| | | } |
| | | // 2. 校验是否有明细 |
| | | List<ErpPurchasePlanItemDO> items = purchasePlanItemMapper.selectListByPlanId(id); |
| | | if (CollUtil.isEmpty(items)) { |
| | | throw exception(PURCHASE_PLAN_ITEM_EMPTY); |
| | | } |
| | | // 3. 创建 BPM 流程实例 |
| | | String processInstanceId = processInstanceApi.createProcessInstance(userId, |
| | | new BpmProcessInstanceCreateReqDTO() |
| | | .setProcessDefinitionKey(processDefinitionKey) |
| | | .setBusinessKey(String.valueOf(id))); |
| | | // 4. 更新采购计划状态为审批中 |
| | | purchasePlanMapper.updateById(new ErpPurchasePlanDO() |
| | | .setId(id) |
| | | .setStatus(ErpPurchasePlanStatusEnum.PROCESS.getStatus()) |
| | | .setProcessInstanceId(processInstanceId)); |
| | | // 3. 校验审批配置已启用且配置了有效审批人(未配置时抛出带明确提示的业务异常) |
| | | approvalConfigApi.validateApprovalEnabledAndGetApprovers(PURCHASE_PLAN_APPROVE_BIZ_TYPE); |
| | | // 4. 状态置为审批中,并清空上一轮审核结果,避免残留「审核不通过」的原因 |
| | | purchasePlanMapper.submitAndResetAuditInfo(id, ErpPurchasePlanStatusEnum.PROCESS.getStatus()); |
| | | } |
| | | |
| | | @Override |
| | | public List<Map<String, Object>> getPurchasePlanApproveProcessDefinitionList() { |
| | | // 1. 校验分类和流程定义是否存在 |
| | | validatePurchasePlanApproveCategoryAndProcessDefinition(); |
| | | // 2. 获取分类下的流程定义信息 |
| | | List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService |
| | | .getProcessDefinitionInfoListByCategory(PURCHASE_PLAN_APPROVE_CATEGORY_CODE); |
| | | if (CollUtil.isEmpty(definitionInfoList)) { |
| | | return Collections.emptyList(); |
| | | public Set<Long> getPurchasePlanApproverUserIds() { |
| | | return approvalConfigApi.getApproverUserIds(PURCHASE_PLAN_APPROVE_BIZ_TYPE); |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public void auditPurchasePlan(Long id, Boolean pass, String reviewRemark) { |
| | | // 1. 校验存在 |
| | | ErpPurchasePlanDO plan = validatePurchasePlanExists(id); |
| | | // 2. 校验处于审批中状态 |
| | | if (!ErpPurchasePlanStatusEnum.PROCESS.getStatus().equals(plan.getStatus())) { |
| | | throw exception(PURCHASE_PLAN_AUDIT_FAIL_NOT_PROCESS); |
| | | } |
| | | // 3. 遍历获取流程定义详情,过滤激活状态,保留最新版本 |
| | | Map<String, ProcessDefinition> latestVersionMap = new HashMap<>(); |
| | | for (BpmProcessDefinitionInfoDO info : definitionInfoList) { |
| | | ProcessDefinition pd = bpmProcessDefinitionService.getProcessDefinition(info.getProcessDefinitionId()); |
| | | if (pd == null || pd.isSuspended()) { |
| | | continue; |
| | | // 3. 校验当前登录用户是该业务类型的审批人(或签:任一人均可审核) |
| | | Long userId = getLoginUserId(); |
| | | approvalConfigApi.validateApprover(PURCHASE_PLAN_APPROVE_BIZ_TYPE, userId); |
| | | // 4. 审核不通过:必须填写原因,状态置为审核不通过,退回编制人修改后可重新提交 |
| | | if (!Boolean.TRUE.equals(pass)) { |
| | | if (StrUtil.isBlank(reviewRemark)) { |
| | | throw exception(PURCHASE_PLAN_AUDIT_REJECT_REASON_REQUIRED); |
| | | } |
| | | ProcessDefinition existing = latestVersionMap.get(pd.getKey()); |
| | | if (existing == null || pd.getVersion() > existing.getVersion()) { |
| | | latestVersionMap.put(pd.getKey(), pd); |
| | | purchasePlanMapper.auditPurchasePlan(id, ErpPurchasePlanStatusEnum.REJECT.getStatus(), |
| | | userId, getUserNickname(userId), reviewRemark); |
| | | return; |
| | | } |
| | | // 5. 审核通过:记录审核人与审核意见,状态置为审核通过 |
| | | purchasePlanMapper.auditPurchasePlan(id, ErpPurchasePlanStatusEnum.APPROVE.getStatus(), |
| | | userId, getUserNickname(userId), reviewRemark); |
| | | // 6. 审核通过且未生成申请,自动生成采购申请 |
| | | if (!Boolean.TRUE.equals(plan.getGeneratedFlag())) { |
| | | try { |
| | | List<Long> requestIds = doGeneratePurchaseRequests(plan); |
| | | log.info("[auditPurchasePlan] 采购计划({}) 自动生成采购申请({})", id, requestIds); |
| | | } catch (Exception e) { |
| | | // 不抛出异常,避免影响审核结果落库;生成失败可由用户手动触发 |
| | | log.error("[auditPurchasePlan] 采购计划({}) 自动生成采购申请失败", id, e); |
| | | } |
| | | } |
| | | // 4. 返回流程定义列表 |
| | | List<Map<String, Object>> result = new ArrayList<>(); |
| | | for (ProcessDefinition pd : latestVersionMap.values()) { |
| | | Map<String, Object> item = new HashMap<>(); |
| | | item.put("id", pd.getId()); |
| | | item.put("key", pd.getKey()); |
| | | item.put("name", pd.getName()); |
| | | result.add(item); |
| | | } |
| | | |
| | | /** |
| | | * 获取用户昵称 |
| | | * |
| | | * @param userId 用户编号 |
| | | * @return 昵称,用户不存在时返回 null |
| | | */ |
| | | private String getUserNickname(Long userId) { |
| | | if (userId == null) { |
| | | return null; |
| | | } |
| | | return result; |
| | | AdminUserRespDTO user = adminUserApi.getUser(userId); |
| | | return user == null ? null : user.getNickname(); |
| | | } |
| | | |
| | | @Override |
| | |
| | | } |
| | | |
| | | @Override |
| | | public List<ErpPurchasePlanRespVO.Item> getStockAlertSuggestItems() { |
| | | // 1. 获取启用的物料基础数据(包含默认仓库、安全/最低/最高库存) |
| | | List<MdmItemRespDTO> items = mdmItemApi.getItemListByStatus(0).getCheckedData(); |
| | | if (CollUtil.isEmpty(items)) { |
| | | throw exception(PURCHASE_PLAN_STOCK_ALERT_NO_ITEM); |
| | | } |
| | | // 2. 按默认仓库库存规划建议采购量 |
| | | List<ErpPurchasePlanRespVO.Item> planItems = new ArrayList<>(); |
| | | for (MdmItemRespDTO item : items) { |
| | | ErpPurchasePlanRespVO.Item planItem = buildStockAlertSuggestItem(item); |
| | | if (planItem != null) { |
| | | planItems.add(planItem); |
| | | } |
| | | } |
| | | if (CollUtil.isEmpty(planItems)) { |
| | | throw exception(PURCHASE_PLAN_STOCK_ALERT_NO_ITEM); |
| | | } |
| | | return planItems; |
| | | } |
| | | |
| | | @Override |
| | | @Transactional(rollbackFor = Exception.class) |
| | | public ErpPurchasePlanDO generatePlanFromStockAlert(String name, Long supplierId) { |
| | | // 1. 获取启用安全库存的物料 |
| | | List<MesMdItemSafetyStockRespDTO> safetyStockItems = mesMdItemApi.getSafetyStockItemList(); |
| | | if (CollUtil.isEmpty(safetyStockItems)) { |
| | | throw exception(PURCHASE_PLAN_ITEM_EMPTY); |
| | | // 1. 获取库存预警建议采购明细 |
| | | List<ErpPurchasePlanRespVO.Item> suggestItems = getStockAlertSuggestItems(); |
| | | if (CollUtil.isEmpty(suggestItems)) { |
| | | throw exception(PURCHASE_PLAN_STOCK_ALERT_NO_ITEM); |
| | | } |
| | | // 2. 计算缺量,生成计划明细 |
| | | List<ErpPurchasePlanSaveReqVO.Item> items = new ArrayList<>(); |
| | | for (MesMdItemSafetyStockRespDTO item : safetyStockItems) { |
| | | if (item.getMinStock() == null) { |
| | | continue; |
| | | } |
| | | BigDecimal stock = mesWmStockApi.getStockQuantity(item.getId()); |
| | | BigDecimal shortage = item.getMinStock().subtract(stock == null ? BigDecimal.ZERO : stock); |
| | | if (shortage.compareTo(BigDecimal.ZERO) <= 0) { |
| | | continue; |
| | | } |
| | | ErpPurchasePlanSaveReqVO.Item planItem = new ErpPurchasePlanSaveReqVO.Item(); |
| | | planItem.setProductId(item.getMdmItemId()); |
| | | planItem.setProductUnitId(item.getUnitMeasureId()); |
| | | planItem.setCount(shortage); |
| | | items.add(planItem); |
| | | } |
| | | if (CollUtil.isEmpty(items)) { |
| | | throw exception(PURCHASE_PLAN_ITEM_EMPTY); |
| | | } |
| | | // 2. 转换为保存明细 |
| | | List<ErpPurchasePlanSaveReqVO.Item> planItems = convertList(suggestItems, item -> |
| | | BeanUtils.toBean(item, ErpPurchasePlanSaveReqVO.Item.class)); |
| | | // 3. 创建草稿采购计划 |
| | | ErpPurchasePlanSaveReqVO createReqVO = new ErpPurchasePlanSaveReqVO(); |
| | | createReqVO.setName(name != null ? name : "库存预警采购计划"); |
| | | createReqVO.setDemandSource(DEMAND_SOURCE_STOCK_ALERT); |
| | | createReqVO.setPlanDate(LocalDateTime.now()); |
| | | createReqVO.setSupplierId(supplierId); |
| | | createReqVO.setItems(items); |
| | | createReqVO.setItems(planItems); |
| | | Long planId = createPurchasePlan(createReqVO); |
| | | return purchasePlanMapper.selectById(planId); |
| | | } |
| | | |
| | | /** |
| | | * 根据单个物料的默认仓库库存构建建议采购明细 |
| | | * |
| | | * @param item 物料基础数据 |
| | | * @return 建议采购明细;无需补货时返回 null |
| | | */ |
| | | private ErpPurchasePlanRespVO.Item buildStockAlertSuggestItem(MdmItemRespDTO item) { |
| | | // 1. 未配置默认仓库或最低库存(无补货基准)的物料不参与规划 |
| | | if (item.getWarehouseId() == null || item.getMinStock() == null) { |
| | | return null; |
| | | } |
| | | // 2. 查询默认仓库的当前库存 |
| | | BigDecimal currentStock = mesWmStockApi.getStockQuantity(item.getId(), item.getWarehouseId()); |
| | | if (currentStock == null) { |
| | | currentStock = BigDecimal.ZERO; |
| | | } |
| | | // 3. 默认仓库库存不低于最低库存时不触发补货 |
| | | if (currentStock.compareTo(item.getMinStock()) >= 0) { |
| | | return null; |
| | | } |
| | | // 4. 补货目标:优先补到安全库存,未配置则回落最高库存,最后取最低库存 |
| | | BigDecimal targetStock = item.getSafetyStock() != null ? item.getSafetyStock() |
| | | : (item.getMaxStock() != null ? item.getMaxStock() : item.getMinStock()); |
| | | BigDecimal count = targetStock.subtract(currentStock); |
| | | if (count.compareTo(BigDecimal.ZERO) <= 0) { |
| | | return null; |
| | | } |
| | | ErpPurchasePlanRespVO.Item planItem = new ErpPurchasePlanRespVO.Item(); |
| | | planItem.setProductId(item.getId()); |
| | | planItem.setProductName(item.getName()); |
| | | planItem.setProductUnitId(item.getUnitMeasureId()); |
| | | planItem.setCount(count); |
| | | planItem.setDemandTime(LocalDate.now()); |
| | | planItem.setRemark(String.format("默认仓库库存%s,安全库存%s,最低库存%s,最高库存%s,建议采购量%s", |
| | | currentStock, item.getSafetyStock(), item.getMinStock(), item.getMaxStock(), count)); |
| | | return planItem; |
| | | } |
| | | |
| | | @Override |
| | |
| | | return ErpPurchasePlanStatusEnum.CANCEL.getStatus(); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | private void validatePurchasePlanApproveCategoryAndProcessDefinition() { |
| | | List<cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmCategoryDO> categories = |
| | | bpmCategoryService.getCategoryListByCode(Collections.singletonList(PURCHASE_PLAN_APPROVE_CATEGORY_CODE)); |
| | | if (CollUtil.isEmpty(categories)) { |
| | | throw exception(PURCHASE_PLAN_BPM_CATEGORY_NOT_EXISTS); |
| | | } |
| | | List<BpmProcessDefinitionInfoDO> definitionInfoList = bpmProcessDefinitionService |
| | | .getProcessDefinitionInfoListByCategory(PURCHASE_PLAN_APPROVE_CATEGORY_CODE); |
| | | if (CollUtil.isEmpty(definitionInfoList)) { |
| | | throw exception(PURCHASE_PLAN_BPM_PROCESS_DEFINITION_NOT_EXISTS); |
| | | } |
| | | } |
| | | |
| | | private ErpPurchasePlanDO validatePurchasePlanExists(Long id) { |