add:结构车间需求单

This commit is contained in:
zhaoyf
2026-11-11 20:17:57 +08:00
parent 0b7ad4abc9
commit 3a75b2237e
13 changed files with 1226 additions and 0 deletions

View File

@@ -53,4 +53,12 @@ public class RegionConstant {
public static final String R001 = "R001";
public static final String R002 = "R002";
/**
* 结构件库
* <p>
* MES 需求单同步时按仓库编码分流到结构件需求单(pm_demand_structure),
* 下推出库完成按 SAP PP055 回传领料出库。
*/
public static final String H005 = "H005";
}

View File

@@ -19,6 +19,7 @@ import org.nl.wms.ext_manage.service.dto.*;
import org.nl.wms.pm_manage.demand.service.IPlatingDemandService;
import org.nl.wms.pm_manage.demand.service.IPmDemandPlatingService;
import org.nl.wms.pm_manage.demand.service.IPmDemandService;
import org.nl.wms.pm_manage.demand.service.IPmDemandStructureService;
import org.nl.wms.pm_manage.demand.service.IPartDemandService;
import org.nl.wms.pm_manage.demand.service.IMaterialWarehouseMappingService;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandParam;
@@ -67,6 +68,8 @@ public class MesToWmsController {
@Autowired
private IPartDemandService partDemandService;
@Autowired
private IPmDemandStructureService structureDemandService;
@Autowired
private IMaterialWarehouseMappingService materialWarehouseMappingService;
@Autowired
private IPlatingDemandService platingDemandService;
@@ -160,6 +163,7 @@ public class MesToWmsController {
ArrayList<PmDemandParam> pmDemandParams = new ArrayList<>();
ArrayList<PmDemandParam> pmDemandPlatingParams = new ArrayList<>();
ArrayList<PmDemandParam> partDemandParams = new ArrayList<>();
ArrayList<PmDemandParam> structureDemandParams = new ArrayList<>();
Map<String, String> warehouseByMaterial = materialWarehouseMappingService.getWarehouseByMaterialCodes(
params.stream().map(PmDemandParam::getSkuCode).collect(Collectors.toSet()));
for (PmDemandParam param : params) {
@@ -168,6 +172,8 @@ public class MesToWmsController {
pmDemandPlatingParams.add(param);
} else if (RegionConstant.ASSEMBLY_PART_STORE_CODE.equals(warehouseCode)) {
partDemandParams.add(param);
} else if (RegionConstant.H005.equals(warehouseCode)) {
structureDemandParams.add(param);
} else {
pmDemandParams.add(param);
}
@@ -175,6 +181,7 @@ public class MesToWmsController {
iPmDemandService.batchCreate(pmDemandParams);
iPmDemandPlatingService.batchCreate(pmDemandPlatingParams);
partDemandService.batchCreate(partDemandParams);
structureDemandService.batchCreate(structureDemandParams);
return ResponseData.build();
}

View File

@@ -174,6 +174,25 @@ PDA 扫码后调用以下接口收货:
- **Steus 控制码**:MES 触发接口入参中的 `Steus` 字段(五个半成品流转接口 DTO 均已接收,示例见 `PlatingInboundDto.steus`)。
生产入库回传(PP066)前判断入参 `Steus`:为 `ZP02` 时不回传;其余值(含未传)照常回传。出库投料(PP055)不受该字段控制。
## 结构件需求单领料出库(H005 → PP055)
- 同步:`POST /app/restful/api/v3/wms/mesRequisitionSync`,按物料映射仓库(`pm_material_warehouse_mapping`,缺失取入参 `WarehouseCode`)
分流;仓库为 `H005`(结构件库)时落 `pm_demand_structure`(`IPmDemandStructureService#batchCreate`),
入参 `Status=1` 的行按取消处理。
- **下发即分配**:新增时直接写 `inventory_dis = H005`、状态 `01`(分配),不需要人工分配仓库,页面直接下推;
页面 `wms/pm_manage/structureDemand/index` 只保留下推出库与删除。建表脚本见 `sql/20261111_pm_demand_structure.sql`。
- 下推:`POST /api/pmDemandStructure/push`,生成一张 WMS **生产出库**单(仓库取需求单 `inventory_dis`,为空兜底 H005),
明细 `callback_strategy = sapStructureDemandOut`、`source_bill_code`/`source_billdtl_id` = 需求单ID、`source_bill_table = pm_demand_structure`;
需求单状态置为下发(`10`)。
- 回传:出库单**整单完成** → `SapStructureDemandOut`(`impl/sap`)按需求单绑定的工单
(`work_order_code` 用 `|` 分隔)逐一过账 PP055,口径同 `SapProductionOutboundDelivery`:
- 每个工单取该物料在工单BOM中的行,本次过账数量 = min(本次已分配数量, `bom_qty - use_bom_qty`),BOM已领完则跳过;
- 需求单编号以 `G`/`D` 开头才带 `rsnum`/`rspos`,其余按计划外投料(空预留号);
- `aufnr`=工单号(取 `-` 前段)、`matnr`=物料、`lgort`=出库单仓库(兜底需求单分配仓库)、`erfmg`=过账数量、`tl`=空;
- 过账成功累加工单BOM的 `use_bom_qty`;结果逐工单写 `pm_stock_return`(类型=生产出库),失败记录走回传记录页面重发;
- 回写需求单 `assign_qty`,达到需求数量后置为完成(`80`)。
1.从SAP调拨入库没有了,WMS调拨会有-》SAP转储

View File

@@ -0,0 +1,74 @@
package org.nl.wms.pm_manage.demand.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import org.nl.common.base.ResponseData;
import org.nl.common.domain.query.PageQuery;
import org.nl.common.logging.annotation.Log;
import org.nl.wms.pm_manage.demand.service.IPmDemandStructureService;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandDto;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandParam;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandQuery;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
/**
* 结构件需求单(H005 结构件库)
* <p>
* MES 下发即分配结构件库并置为分配状态,页面只保留查询、下推出库、删除。
*/
@RestController
@RequestMapping("/api/pmDemandStructure")
@SaIgnore
public class StructureDemandController {
@Resource
private IPmDemandStructureService structureDemandService;
@GetMapping
@Log("查询结构件需求单")
public ResponseEntity<Object> queryAll(PmDemandQuery query, PageQuery page) {
return ResponseData.build(structureDemandService.queryPage(query, page), HttpStatus.OK);
}
@PostMapping
@Log("新增结构件需求单")
public ResponseEntity<Object> create(@Valid @RequestBody PmDemandParam param) {
structureDemandService.create(param);
return ResponseData.build();
}
@PutMapping
@Log("修改结构件需求单")
public ResponseEntity<Object> update(@Valid @RequestBody PmDemandDto param) {
structureDemandService.update(param);
return ResponseData.build();
}
@DeleteMapping
@Log("删除结构件需求单")
@Transactional(rollbackFor = Exception.class)
public ResponseEntity<Object> delete(@RequestBody String[] ids) {
structureDemandService.deleteByIds(Arrays.asList(ids));
return ResponseData.build();
}
@PostMapping("/push")
@Log("结构件需求单下推出库")
public ResponseEntity<Object> push(@RequestBody List<PmDemandDto> pmDemandDtos) {
structureDemandService.pushDemand(pmDemandDtos);
return ResponseData.build();
}
}

View File

@@ -0,0 +1,37 @@
package org.nl.wms.pm_manage.demand.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.nl.common.domain.query.PageQuery;
import org.nl.wms.pm_manage.demand.service.dao.PmDemandStructure;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandDto;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandParam;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandQuery;
import java.util.List;
/**
* 结构件需求单(H005 结构件库)
* <p>
* MES 下发时直接分配结构件库并置为分配状态,因此不提供库存分配相关操作。
*/
public interface IPmDemandStructureService extends IService<PmDemandStructure> {
Page<PmDemandDto> queryPage(PmDemandQuery query, PageQuery pageQuery);
void create(PmDemandParam param);
/**
* MES 批量下发:新增需求单(默认分配结构件库、状态分配),状态为 1 的行按取消处理(MES 撤回)
*/
void batchCreate(List<PmDemandParam> param);
void update(PmDemandDto param);
void deleteByIds(List<String> ids);
/**
* 下推:生成 WMS 出库单,出库完成后按 PP055 回传 SAP 领料出库
*/
void pushDemand(List<PmDemandDto> pmDemandDtos);
}

View File

@@ -0,0 +1,88 @@
package org.nl.wms.pm_manage.demand.service.dao;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 结构件需求单(H005 结构件库)
* <p>
* MES 需求单同步接口按物料映射仓库分流,
* 下推生成「生产出库」单,出库完成由 {@code sapStructureDemandOut} 回传 SAP PP055 领料出库。
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("pm_demand_structure")
public class PmDemandStructure extends Model<PmDemandStructure> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.INPUT)
private String id;
private String creator;
@TableField("create_time")
private String create_time;
private Integer priority;
private String status;
private String seq_no;
@TableField("work_order")
private String work_order;
@TableField("work_order_code")
private String work_order_code;
@TableField("sku_code")
private String sku_code;
@TableField("sku_name")
private String sku_name;
private BigDecimal qty;
private BigDecimal assign_qty;
private String unit;
@TableField("target_area")
private String target_area;
@TableField("target_house_code")
private String target_house_code;
@TableField("carrier_type")
private String carrier_type;
@TableField("production_line")
private String production_line;
@TableField("is_deleted")
private Integer is_deleted;
private String sn;
@TableField("create_at")
private String create_at;
@TableField("inventory_dis")
private String inventory_dis;
private String lk_container;
private String max_load;
private String warehouse_code;
@Override
protected Serializable pkVal() {
return this.id;
}
}

View File

@@ -0,0 +1,14 @@
package org.nl.wms.pm_manage.demand.service.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.nl.wms.pm_manage.demand.service.dao.PmDemandStructure;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandDto;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandQuery;
import java.util.List;
public interface PmDemandStructureMapper extends BaseMapper<PmDemandStructure> {
List<PmDemandDto> queryPage(@Param("query") PmDemandQuery query);
}

View File

@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nl.wms.pm_manage.demand.service.dao.mapper.PmDemandStructureMapper">
<resultMap id="DemandDtoMap" type="org.nl.wms.pm_manage.demand.service.dto.PmDemandDto">
<result property="id" column="id"/>
<result property="creator" column="creator"/>
<result property="createTime" column="create_time"/>
<result property="priority" column="priority"/>
<result property="status" column="status"/>
<result property="seqNo" column="seq_no"/>
<result property="workOrder" column="work_order"/>
<result property="workOrderCode" column="work_order_code"/>
<result property="skuCode" column="sku_code"/>
<result property="skuName" column="sku_name"/>
<result property="qty" column="qty"/>
<result property="assignQty" column="assign_qty"/>
<result property="unit" column="unit"/>
<result property="targetArea" column="target_area"/>
<result property="targetHouseCode" column="target_house_code"/>
<result property="carrierType" column="carrier_type"/>
<result property="isDeleted" column="is_deleted"/>
<result property="productionLine" column="production_line"/>
<result property="sn" column="sn"/>
<result property="createAt" column="create_at"/>
<result property="inventoryDis" column="inventory_dis"/>
</resultMap>
<select id="queryPage" resultMap="DemandDtoMap">
select d.*
from pm_demand_structure d
where 1 = 1
<if test="query.status == 90">
and is_deleted = 1
</if>
<if test="query.status != 90">
and is_deleted = 0
</if>
<if test="query.id != null and query.id != ''">
and d.id = #{query.id}
</if>
<if test="query.creator != null and query.creator != ''">
and d.creator like concat('%', #{query.creator}, '%')
</if>
<if test="query.status != null">
and d.status = #{query.status}
</if>
<if test="query.workOrder != null and query.workOrder != ''">
and d.work_order like concat('%', #{query.workOrder}, '%')
</if>
<if test="query.skuCode != null and query.skuCode != ''">
and (d.sku_code like concat('%', #{query.skuCode}, '%') or d.sku_name like concat('%', #{query.skuCode}, '%'))
</if>
<if test="query.productionLine != null and query.productionLine != ''">
and d.production_line like concat('%', #{query.productionLine}, '%')
</if>
<if test="query.targetArea != null and query.targetArea != ''">
and d.target_area like concat('%', #{query.targetArea}, '%')
</if>
<if test="query.startTime != null and query.startTime != ''">
and d.create_time &gt;= #{query.startTime}
</if>
<if test="query.endTime != null and query.endTime != ''">
and d.create_time &lt;= #{query.endTime}
</if>
order by d.create_time desc,d.work_order,d.priority desc
</select>
</mapper>

View File

@@ -0,0 +1,314 @@
package org.nl.wms.pm_manage.demand.service.impl;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nl.common.domain.constant.RegionConstant;
import org.nl.common.domain.query.PageQuery;
import org.nl.common.exception.BadRequestException;
import org.nl.wms.basedata_manage.service.IMdMeMaterialbaseService;
import org.nl.wms.basedata_manage.service.IMdPbMeasureunitService;
import org.nl.wms.basedata_manage.service.dao.MdMeMaterialbase;
import org.nl.wms.basedata_manage.service.dao.MdPbMeasureunit;
import org.nl.wms.ext_manage.api.MesApi;
import org.nl.wms.pm_manage.demand.service.IPmDemandStructureService;
import org.nl.wms.pm_manage.demand.service.dao.PmDemandStructure;
import org.nl.wms.pm_manage.demand.service.dao.mapper.PmDemandStructureMapper;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandDto;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandParam;
import org.nl.wms.pm_manage.demand.service.dto.PmDemandQuery;
import org.nl.wms.pm_manage.demand.service.enums.DemandStatus;
import org.nl.wms.warehouse_manage.enums.IOSEnum;
import org.nl.wms.warehouse_manage.inAndOut.service.IOutBillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.nl.common.domain.query.PageQuery.trimStringFields;
/**
* 结构件需求单(H005 结构件库)
* <p>
* MES 下发即落到本表,直接分配结构件库(H005)、状态置为分配,操作员无需再做库存分配,直接下推出库。
* 下推出库的类型为「生产出库」,出库明细的回传策略为 {@code sapStructureDemandOut},
* 出库完成按 SAP PP055 回传领料出库(按工单BOM剩余量过账,见 SapStructureDemandOut)。
*/
@Service
@Slf4j
public class PmDemandStructureServiceImpl extends ServiceImpl<PmDemandStructureMapper, PmDemandStructure>
implements IPmDemandStructureService {
private static final String DEFAULT_UNIT_NAME = "PCS";
@Autowired
private IOutBillService iOutBillService;
@Autowired
private IMdMeMaterialbaseService iMdMeMaterialbaseService;
@Autowired
private IMdPbMeasureunitService iMdPbMeasureunitService;
@Autowired
private MesApi mesApi;
@Override
public Page<PmDemandDto> queryPage(PmDemandQuery query, PageQuery pageQuery) {
trimStringFields(query);
long total = baseMapper.selectCount(new LambdaQueryWrapper<PmDemandStructure>()
.eq(query.getStatus() == null || query.getStatus() != 90, PmDemandStructure::getIs_deleted, 0)
.eq(query.getStatus() != null && query.getStatus() == 90, PmDemandStructure::getIs_deleted, 1)
.like(!StringUtils.isEmpty(query.getProductionLine()), PmDemandStructure::getProduction_line, query.getProductionLine())
.like(!StringUtils.isEmpty(query.getTargetArea()), PmDemandStructure::getTarget_area, query.getTargetArea())
.le(!StringUtils.isEmpty(query.getEndTime()), PmDemandStructure::getCreate_time, query.getEndTime())
.ge(!StringUtils.isEmpty(query.getStartTime()), PmDemandStructure::getCreate_time, query.getStartTime())
.eq(Objects.nonNull(query.getStatus()), PmDemandStructure::getStatus, query.getStatus())
.like(Objects.nonNull(query.getSkuCode()), PmDemandStructure::getSku_code, query.getSkuCode())
.like(Objects.nonNull(query.getWorkOrder()), PmDemandStructure::getWork_order, query.getWorkOrder())
);
com.github.pagehelper.Page<Object> page = PageHelper.startPage(pageQuery.getPage() + 1, pageQuery.getSize(), false);
List<PmDemandDto> records = this.baseMapper.queryPage(query);
Page<PmDemandDto> dtoPage = new Page<>(page.getPageNum(), page.getPageSize(), total);
dtoPage.setRecords(records);
return dtoPage;
}
@Override
public void create(PmDemandParam param) {
PmDemandStructure exist = StringUtils.isBlank(param.getId()) ? null : this.getById(param.getId());
PmDemandStructure demand = new PmDemandStructure();
demand.setId(param.getId());
demand.setCreator(param.getCreator());
demand.setCreate_time(param.getCreateTime());
demand.setPriority(param.getPriority());
demand.setSeq_no(param.getSeqNo());
demand.setWork_order(param.getWorkOrder());
demand.setWork_order_code(param.getWorkOrderCode());
demand.setSku_code(param.getSkuCode());
demand.setSku_name(param.getSkuName());
demand.setQty(param.getQty());
demand.setUnit(param.getUnit());
demand.setTarget_area(param.getTargetArea());
demand.setTarget_house_code(param.getTargetHouseCode());
demand.setCarrier_type(param.getCarrierType());
demand.setProduction_line(param.getProductionLine());
demand.setSn(param.getSn());
demand.setMax_load(param.getMaxLoad());
demand.setWarehouse_code(param.getWarehouseCode());
if (exist == null) {
demand.setIs_deleted(0);
demand.setCreate_at(DateUtil.now());
// 结构件库下发即按结构件库分配,操作员可直接下推
demand.setStatus(DemandStatus.DIS.getValue());
demand.setInventory_dis(RegionConstant.H005);
this.save(demand);
return;
}
// MES 重推同一需求单:已下推/完成的不回退状态与分配仓库
demand.setCreate_at(exist.getCreate_at());
if (DemandStatus.CREATE.getValue().equals(exist.getStatus())
|| DemandStatus.DIS.getValue().equals(exist.getStatus())) {
demand.setStatus(DemandStatus.DIS.getValue());
demand.setInventory_dis(StringUtils.isBlank(exist.getInventory_dis())
? RegionConstant.H005 : exist.getInventory_dis());
}
this.updateById(demand);
}
@Override
public void batchCreate(List<PmDemandParam> param) {
if (CollectionUtils.isEmpty(param)) {
return;
}
for (PmDemandParam pmDemandParam : param) {
if (StringUtils.isEmpty(pmDemandParam.getTargetHouseCode())) {
throw new BadRequestException("目标库位为空!");
}
// MES 撤回:状态 1 表示取消该需求单
if (Objects.equals(pmDemandParam.getStatus(), "1")) {
this.update(new LambdaUpdateWrapper<PmDemandStructure>()
.eq(PmDemandStructure::getId, pmDemandParam.getId())
.set(PmDemandStructure::getStatus, DemandStatus.CANCEL.getValue())
.set(PmDemandStructure::getIs_deleted, 1));
continue;
}
this.create(pmDemandParam);
}
}
@Override
public void update(PmDemandDto param) {
PmDemandStructure dbDemand = this.getById(param.getId());
if (dbDemand == null) {
throw new BadRequestException("需求单不存在");
}
PmDemandStructure demand = new PmDemandStructure();
demand.setId(param.getId());
demand.setCreator(param.getCreator());
demand.setCreate_time(param.getCreateTime());
demand.setPriority(param.getPriority());
demand.setStatus(param.getStatus());
demand.setWork_order(param.getWorkOrder());
demand.setSku_code(param.getSkuCode());
demand.setSku_name(param.getSkuName());
demand.setQty(param.getQty());
demand.setAssign_qty(param.getAssignQty());
demand.setUnit(param.getUnit());
demand.setTarget_area(param.getTargetArea());
demand.setProduction_line(param.getProductionLine());
demand.setSn(param.getSn());
demand.setCreate_at(dbDemand.getCreate_at());
this.updateById(demand);
}
@Override
public void deleteByIds(List<String> ids) {
if (CollectionUtils.isEmpty(ids)) {
return;
}
final List<PmDemandStructure> pmDemands = this.listByIds(ids);
for (PmDemandStructure pmDemand : pmDemands) {
if (!DemandStatus.CREATE.getValue().equals(pmDemand.getStatus())
&& !DemandStatus.DIS.getValue().equals(pmDemand.getStatus())) {
throw new BadRequestException("删除失败,已经执行的需求单无法删除");
}
}
for (String id : ids) {
try {
mesApi.delMesDemand(id);
} catch (Exception e) {
// MES 删除通知失败不阻塞 WMS 删除,避免脏数据无法清理
log.error("删除结构件需求单{}时通知MES失败:{}", id, e.getMessage());
}
this.update(new LambdaUpdateWrapper<PmDemandStructure>()
.eq(PmDemandStructure::getId, id)
.set(PmDemandStructure::getStatus, DemandStatus.CANCEL.getValue())
.set(PmDemandStructure::getIs_deleted, 1));
}
}
@Override
public void pushDemand(List<PmDemandDto> pmDemandDtos) {
if (CollectionUtils.isEmpty(pmDemandDtos)) {
throw new BadRequestException("下推失败,请求数据不能为空");
}
List<String> ids = pmDemandDtos.stream().map(PmDemandDto::getId).collect(Collectors.toList());
List<PmDemandStructure> disList = this.list(new LambdaQueryWrapper<PmDemandStructure>()
.in(PmDemandStructure::getId, ids)
.last("FOR UPDATE"));
if (CollectionUtils.isEmpty(disList)) {
throw new BadRequestException("下推失败,需求单不存在");
}
disList.forEach(item -> {
if (!DemandStatus.DIS.getValue().equals(item.getStatus())) {
throw new BadRequestException("下推失败,单据状态已更新请刷新重新推送");
}
});
// 下发即分配结构件库,历史/异常数据未写仓库时兜底为 H005,保证出库单仓库不为空
List<PmDemandStructure> blankWarehouse = disList.stream()
.filter(item -> StringUtils.isBlank(item.getInventory_dis()))
.collect(Collectors.toList());
if (!blankWarehouse.isEmpty()) {
blankWarehouse.forEach(item -> item.setInventory_dis(RegionConstant.H005));
this.updateBatchById(blankWarehouse);
}
pmDemandDtos.forEach(dto -> {
if (StringUtils.isBlank(dto.getInventoryDis())) {
dto.setInventoryDis(RegionConstant.H005);
}
});
JSONObject billParam = convertDemandsToBillParam(pmDemandDtos);
iOutBillService.saveBill(billParam);
this.update(new LambdaUpdateWrapper<PmDemandStructure>()
.set(PmDemandStructure::getStatus, DemandStatus.SEND.getValue())
.in(PmDemandStructure::getId, ids));
}
/**
* 组装 WMS 出库单参数:类型生产出库,明细回传策略 sapStructureDemandOut(SAP PP055 领料出库)
*/
private JSONObject convertDemandsToBillParam(List<PmDemandDto> demands) {
if (CollectionUtils.isEmpty(demands)) {
throw new BadRequestException("需求单数据为空");
}
PmDemandDto firstDemand = demands.get(0);
JSONObject billParam = new JSONObject();
billParam.put("stor_code", firstDemand.getInventoryDis());
billParam.put("biz_date", DateUtil.today());
billParam.put("bill_type", IOSEnum.BILL_TYPE.code("生产出库"));
billParam.put("remark", "结构件需求单下推生成");
List<MdMeMaterialbase> materialbases = iMdMeMaterialbaseService
.list(new LambdaQueryWrapper<MdMeMaterialbase>()
.in(MdMeMaterialbase::getMaterial_code,
demands.stream().map(PmDemandDto::getSkuCode).collect(Collectors.toList()))
.select(MdMeMaterialbase::getQty_unit_id,
MdMeMaterialbase::getMaterial_id,
MdMeMaterialbase::getMaterial_code));
Map<String, MdMeMaterialbase> codeToIdMap = materialbases.stream()
.collect(Collectors.toMap(MdMeMaterialbase::getMaterial_code, Function.identity()));
List<JSONObject> tableData = new ArrayList<>();
for (PmDemandDto demand : demands) {
MdMeMaterialbase materialbase = codeToIdMap.get(demand.getSkuCode());
if (materialbase == null) {
throw new BadRequestException("下推失败," + demand.getSkuCode() + "在WMS中不存在");
}
JSONObject detailRow = new JSONObject();
detailRow.put("material_code", demand.getSkuCode());
detailRow.put("material_id", materialbase.getMaterial_id());
detailRow.put("qty_unit_name", demand.getUnit());
// st_ivt_iostorinvdtl.qty_unit_id 非空,物料未维护单位时用默认单位兜底
detailRow.put("qty_unit_id", resolveQuantityUnitId(materialbase.getQty_unit_id()));
detailRow.put("qty", demand.getQty());
detailRow.put("source_bill_code", demand.getId());
// 出库完成回传 SAP PP055 领料出库
detailRow.put("callback_strategy", "sapStructureDemandOut");
detailRow.put("source_bill_type", "需求单");
detailRow.put("source_billdtl_id", demand.getId());
detailRow.put("source_bill_table", "pm_demand_structure");
detailRow.put("remark", "关联工单:" + demand.getWorkOrder());
detailRow.put("load_port", demand.getTargetArea());
detailRow.put("vehicle_type", demand.getCarrierType());
tableData.add(detailRow);
}
billParam.put("tableData", tableData);
return billParam;
}
/**
* 取计量单位标识,物料未维护单位时用默认单位 PCS 兜底。
*/
private String resolveQuantityUnitId(String qtyUnitId) {
if (StringUtils.isNotBlank(qtyUnitId)) {
return qtyUnitId;
}
MdPbMeasureunit defaultUnit = findPcsMeasureUnit();
if (defaultUnit == null || StringUtils.isBlank(defaultUnit.getMeasure_unit_id())) {
throw new BadRequestException("下推失败:默认计量单位" + DEFAULT_UNIT_NAME + "在计量单位表中不存在,请先维护");
}
log.warn("物料未维护计量单位,使用默认单位{}兜底,measure_unit_id={}", DEFAULT_UNIT_NAME, defaultUnit.getMeasure_unit_id());
return defaultUnit.getMeasure_unit_id();
}
private MdPbMeasureunit findPcsMeasureUnit() {
MdPbMeasureunit unit = iMdPbMeasureunitService.getOne(new LambdaQueryWrapper<MdPbMeasureunit>()
.eq(MdPbMeasureunit::getUnit_code, DEFAULT_UNIT_NAME).last("limit 1"));
if (unit != null) {
return unit;
}
return iMdPbMeasureunitService.getOne(new LambdaQueryWrapper<MdPbMeasureunit>()
.apply("UPPER(unit_name) = {0}", DEFAULT_UNIT_NAME).last("limit 1"));
}
}

View File

@@ -0,0 +1,303 @@
package org.nl.wms.warehouse_manage.stockReturn.strategy.core.impl.sap;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.nl.common.exception.BadRequestException;
import org.nl.wms.ext_manage.sap.api.SapApi;
import org.nl.wms.ext_manage.sap.api.dto.ProductionOutboundBody;
import org.nl.wms.ext_manage.sap.api.dto.ProductionOutboundHeader;
import org.nl.wms.ext_manage.sap.api.dto.ProductionOutboundRequest;
import org.nl.wms.ext_manage.sap.enums.SapConstant;
import org.nl.wms.pm_manage.demand.service.IPmDemandStructureService;
import org.nl.wms.pm_manage.demand.service.dao.PmDemandStructure;
import org.nl.wms.pm_manage.demand.service.enums.DemandStatus;
import org.nl.wms.system_manage.enums.SysParamConstant;
import org.nl.wms.system_manage.service.param.ISysParamService;
import org.nl.wms.system_manage.service.param.dao.Param;
import org.nl.wms.warehouse_manage.enums.IOSEnum;
import org.nl.wms.warehouse_manage.inAndOut.service.dao.IOStorInv;
import org.nl.wms.warehouse_manage.inAndOut.service.dao.IOStorInvDtl;
import org.nl.wms.warehouse_manage.inAndOut.service.dao.mapper.IOStorInvDtlMapper;
import org.nl.wms.warehouse_manage.inAndOut.service.dao.mapper.IOStorInvMapper;
import org.nl.wms.warehouse_manage.stockReturn.service.IPmStockReturnService;
import org.nl.wms.warehouse_manage.stockReturn.service.dao.PmStockReturn;
import org.nl.wms.warehouse_manage.stockReturn.service.enums.StockReturnStatusEnum;
import org.nl.wms.warehouse_manage.stockReturn.strategy.core.CallbackStrategy;
import org.nl.wms.welding_manage.service.work_order.IWorkOrderService;
import org.nl.wms.welding_manage.service.work_order.dao.WorkOrderBomDao;
import org.nl.wms.welding_manage.service.work_order.dao.WorkOrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
/**
* 结构件需求单下推出库完成,回传 SAP PP055 领料出库。
* <p>
* 与生产需求单({@link SapProductionOutboundDelivery})口径一致:一个需求单可能绑定多个工单
* ({@code pm_demand_structure.work_order_code} 用 {@code |} 分隔),出库是实时多次过账,因此:
* <ul>
* <li>按工单逐一过账,每个工单取该物料在工单BOM中的行;</li>
* <li>本次过账数量 = min(本次已分配数量, {@code bom_qty} - {@code use_bom_qty}),BOM已领完的工单跳过,避免重复过账;</li>
* <li>过账成功后累加工单BOM的 {@code use_bom_qty};</li>
* <li>出库明细的 {@code source_bill_code} 即 {@code pm_demand_structure.id},
* {@code assign_qty} 为该明细的已分配(实际出库)数量。</li>
* </ul>
* 出库单整单完成才回传;回传结果写入 pm_stock_return,失败记录可通过回传记录页面手动重发。
*/
@Slf4j
@Service(value = "sapStructureDemandOut")
public class SapStructureDemandOut implements CallbackStrategy {
private static final DateTimeFormatter DATE_BASIC = DateTimeFormatter.BASIC_ISO_DATE;
@Autowired
private IPmDemandStructureService structureDemandService;
@Autowired
private IWorkOrderService iWorkOrderService;
@Autowired
private SapApi sapApi;
@Autowired
private IOStorInvMapper ioStorInvMapper;
@Autowired
private IOStorInvDtlMapper ioStorInvDtlMapper;
@Autowired
private IPmStockReturnService iPmStockReturnService;
@Autowired
private ISysParamService sysParamService;
@Override
public void buildCallback(IOStorInvDtl param) {
if (param == null || StrUtil.isBlank(param.getSource_bill_code())) {
throw new BadRequestException("结构件领料出库回传失败:来源需求单号为空");
}
String demandId = param.getSource_bill_code().trim();
PmDemandStructure demand = structureDemandService.getById(demandId);
if (demand == null) {
throw new BadRequestException("结构件需求单不存在:" + demandId);
}
// 整单完成才过账,避免部分明细完成时提前过账
String finishedStatus = IOSEnum.BILL_STATUS.code("完成");
if (StrUtil.isNotBlank(param.getIostorinv_id())) {
Integer unFinishCount = ioStorInvDtlMapper.selectCount(new LambdaQueryWrapper<IOStorInvDtl>()
.eq(IOStorInvDtl::getIostorinv_id, param.getIostorinv_id())
.ne(IOStorInvDtl::getBill_status, finishedStatus));
if (unFinishCount != null && unFinishCount > 0) {
return;
}
}
IOStorInv bill = StrUtil.isBlank(param.getIostorinv_id()) ? null
: ioStorInvMapper.selectById(param.getIostorinv_id());
// 存储地点优先取出库单仓库,兜底需求单分配的仓库
String lgort = bill == null ? "" : StrUtil.blankToDefault(bill.getStor_code(), "");
if (StrUtil.isBlank(lgort)) {
lgort = StrUtil.blankToDefault(demand.getInventory_dis(), "");
}
if (StrUtil.isBlank(lgort)) {
throw new BadRequestException("结构件领料出库回传失败:需求单" + demandId + "存储地点为空");
}
String materialCode = StrUtil.blankToDefault(param.getMaterial_code(), demand.getSku_code());
if (StrUtil.isBlank(materialCode)) {
throw new BadRequestException("结构件领料出库回传失败:需求单" + demandId + "物料为空");
}
BigDecimal feedbackQty = nvl(param.getAssign_qty());
if (feedbackQty.signum() <= 0) {
log.warn("结构件需求单{}出库明细{}已分配数量为0,跳过回传SAP", demandId, param.getIostorinvdtl_id());
return;
}
BigDecimal postedTotal = postByBomRemain(demand, materialCode, lgort,
StrUtil.blankToDefault(param.getIostorinv_id(), demand.getId()),
bill == null ? null : bill.getBill_code(), feedbackQty);
if (postedTotal.compareTo(feedbackQty) != 0) {
log.info("结构件需求单{}出库数量{}与按BOM剩余量过账数量{}不一致,领料以BOM口径为准",
demandId, feedbackQty, postedTotal);
}
// 回写需求单已出库数量,取满即完成
demand.setAssign_qty(feedbackQty);
if (feedbackQty.compareTo(nvl(demand.getQty())) >= 0
&& !DemandStatus.FINISH.getValue().equals(demand.getStatus())) {
demand.setStatus(DemandStatus.FINISH.getValue());
}
structureDemandService.updateById(demand);
}
/**
* 按工单BOM剩余量逐工单过账 PP055,并在过账成功后累加工单BOM的已用数量。
*
* @return 本次实际过账的数量合计
*/
private BigDecimal postByBomRemain(PmDemandStructure demand, String materialCode, String lgort,
String requestId, String billCode, BigDecimal feedbackQty) {
List<String> orderCodes = splitWorkOrders(demand.getWork_order_code());
if (orderCodes.isEmpty()) {
throw new BadRequestException("结构件需求单" + demand.getId() + "未绑定工单");
}
List<WorkOrderDao> workOrderList = iWorkOrderService.list(new LambdaQueryWrapper<WorkOrderDao>()
.in(WorkOrderDao::getOrder_code, orderCodes));
if (workOrderList.isEmpty()) {
throw new BadRequestException("未找到工单:" + orderCodes);
}
String today = LocalDate.now().format(DATE_BASIC);
// 带预留号过账:需求单编号以 G/D 开头(生产订单),其余按计划外投料
boolean withReserve = isReserveDemand(demand.getWork_order());
// 待过账数量
BigDecimal remaining = feedbackQty;
BigDecimal postedTotal = BigDecimal.ZERO;
for (WorkOrderDao workOrder : workOrderList) {
String rsnum = "";
String rspos = "";
BigDecimal postQty = remaining;
WorkOrderBomDao bom = null;
if (withReserve) {
bom = matchBomItem(iWorkOrderService.getOrderBomItem(workOrder.getOrder_code()), materialCode);
if (bom == null) {
String msg = String.format("结构件需求单[%s]工单[%s]未匹配到物料[%s]的BOM行,无法过账",
demand.getId(), workOrder.getOrder_code(), materialCode);
log.error(msg);
throw new BadRequestException(msg);
}
rsnum = StrUtil.blankToDefault(StrUtil.trim(bom.getRsnum()), "");
rspos = StrUtil.blankToDefault(StrUtil.trim(bom.getRspos()), "");
BigDecimal usedQty = nvl(bom.getUse_bom_qty());
// BOM剩余过账数量 = BOM数量 - 已用BOM数量
BigDecimal bomRemain = nvl(bom.getBom_qty()).subtract(usedQty);
if (bomRemain.signum() <= 0) {
log.info("结构件需求单{}工单{}物料{}BOM已领完(bom_qty={},use_bom_qty={}),跳过过账",
demand.getId(), workOrder.getOrder_code(), materialCode, bom.getBom_qty(), usedQty);
continue;
}
postQty = remaining.min(bomRemain);
}
if (postQty.signum() <= 0) {
break;
}
// 请求号需全局唯一,SAP 侧按 docno 识别一次过账;一个工单一次请求,便于按工单隔离失败
String docno = "FEED" + System.currentTimeMillis();
ProductionOutboundRequest request = buildRequest(docno, today, workOrder, materialCode,
lgort, rsnum, rspos, postQty);
PmStockReturn stockReturn = new PmStockReturn();
stockReturn.setRequest_Id(requestId);
stockReturn.setBill_code(billCode);
stockReturn.setRequest_type(IOSEnum.BILL_TYPE.code("生产出库"));
stockReturn.setStatus(StockReturnStatusEnum.TODO.getCode());
stockReturn.setCreate_time(DateUtil.now());
stockReturn.setRequest_data(JSON.toJSONString(request));
boolean success = false;
try {
JSONObject sapResult = sapApi.productionOutbound(request);
success = true;
stockReturn.setStatus(StockReturnStatusEnum.SUCESS.getCode());
stockReturn.setProcess_time(DateUtil.now());
JSONObject record = new JSONObject();
record.put("request", request);
record.put("response", sapResult);
stockReturn.setRequest_data(record.toJSONString());
} catch (Exception e) {
String error = String.format("结构件需求单%s工单%s领料出库回传SAP失败[%s]",
demand.getId(), workOrder.getOrder_code(), e.getMessage());
log.error(error);
Param forceReturn = sysParamService.findByCode(SysParamConstant.FORCE_RETURN);
if (ObjectUtils.isNotEmpty(forceReturn) && "1".equals(forceReturn.getValue())) {
throw new BadRequestException(error);
}
stockReturn.setError_msg(e.getMessage());
stockReturn.setStatus(StockReturnStatusEnum.FAIL.getCode());
stockReturn.setProcess_time(DateUtil.now());
}
iPmStockReturnService.save(stockReturn);
if (success && bom != null) {
// 维护BOM已用数量(原子累加)
iWorkOrderService.updateBomUseQty(bom.getId(), nvl(bom.getUse_bom_qty()).add(postQty));
}
postedTotal = postedTotal.add(postQty);
remaining = remaining.subtract(postQty);
if (remaining.signum() <= 0) {
break;
}
}
return postedTotal;
}
/**
* 组装单个工单的单条 PP055 报文:数量按 BOM 剩余量过账
*/
private ProductionOutboundRequest buildRequest(String docno, String today, WorkOrderDao workOrder,
String materialCode, String lgort, String rsnum, String rspos,
BigDecimal postQty) {
ProductionOutboundRequest request = new ProductionOutboundRequest();
ProductionOutboundHeader header = new ProductionOutboundHeader();
header.setIntfId(SapConstant.INTF_PP055);
header.setSrcSystem(SapConstant.SRC_SYSTEM);
header.setDestSystem(SapConstant.DEST_SYSTEM);
header.setRequesttime(System.currentTimeMillis());
request.setHeader(header);
ProductionOutboundBody body = new ProductionOutboundBody();
body.setDocno(docno);
body.setBudat(today);
body.setBldat(today);
body.setMatnr(materialCode);
body.setWerks(SapConstant.WERKS);
body.setLgort(lgort);
body.setAufnr(workOrder.getOrder_code().split("-")[0]);
body.setErfmg(postQty.doubleValue());
body.setRsnum(rsnum);
body.setRspos(rspos);
// tl 为空表示投料
body.setTl("");
request.setBody(Collections.singletonList(body));
return request;
}
/**
* 需求单编号以 G/D 开头时为生产订单领料,需带预留号/行项目;其余按计划外投料过账
*/
private boolean isReserveDemand(String workOrder) {
String code = StrUtil.trim(workOrder);
if (StrUtil.isBlank(code)) {
return false;
}
return code.startsWith("G") || code.startsWith("D");
}
private List<String> splitWorkOrders(String workOrderCodes) {
List<String> orderCodes = new ArrayList<>();
if (StrUtil.isBlank(workOrderCodes)) {
return orderCodes;
}
for (String code : workOrderCodes.split(Pattern.quote("|"))) {
String trimmed = StrUtil.trim(code);
if (StrUtil.isNotBlank(trimmed) && !orderCodes.contains(trimmed)) {
orderCodes.add(trimmed);
}
}
return orderCodes;
}
private WorkOrderBomDao matchBomItem(List<WorkOrderBomDao> orderBomItem, String materialCode) {
if (orderBomItem == null || orderBomItem.isEmpty() || StrUtil.isBlank(materialCode)) {
return null;
}
for (WorkOrderBomDao bomItem : orderBomItem) {
if (bomItem != null && StrUtil.equals(bomItem.getMaterial_code(), materialCode)) {
return bomItem;
}
}
return null;
}
private BigDecimal nvl(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
}