package common.ecommerce.yqn.adapter; import common.ecommerce.shared.support.Money; import common.ecommerce.warehouse.model.InboundBatch; import common.ecommerce.warehouse.model.InboundCarton; import common.ecommerce.warehouse.model.InboundCommand; import common.ecommerce.warehouse.model.InboundLine; import common.ecommerce.warehouse.model.InboundOrder; import common.ecommerce.warehouse.model.InboundOrderLine; import common.ecommerce.warehouse.model.InboundStatus; import common.ecommerce.yqn.dto.YqnDtos; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.List; /** * 运去哪入库计划报文映射(API 97)。 */ public final class YqnInboundMapper { private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); /** 容器号:4 位大写字母 + 7 位数字。 */ private static final java.util.regex.Pattern CONTAINER_NO = java.util.regex.Pattern.compile("^[A-Z]{4}\\d{7}$"); private YqnInboundMapper() { } /** 统一命令 → 运去哪创建入库计划请求。 */ public static YqnDtos.CreateInboundPlanRequest toRequest(InboundCommand cmd, String warehouseCode) { requireContainerNo(cmd.containerNo()); YqnDtos.CreateInboundPlanRequest req = new YqnDtos.CreateInboundPlanRequest(); req.warehouseCode = warehouseCode; req.orderNo = cmd.inboundRequestNo(); req.inventoryType = cmd.inventoryType(); req.batchNumber = cmd.factoryBatchNo(); req.currency = cmd.currency(); req.estimateArriveTime = formatDate(cmd.estimateArriveDate()); req.expectArriveDate = formatDate(cmd.expectArriveDate()); req.predictionShipDate = formatDate(cmd.predictionShipDate()); req.originCountry = cmd.originCountry(); req.shipperName = cmd.shipperName(); req.shipperAddress = cmd.shipperAddress(); req.shipperContact = cmd.shipperContact(); req.shipperPhone = cmd.shipperPhone(); req.containerNo = cmd.containerNo(); req.remark = cmd.remark(); // openapi 只支持自发头程;给 1 会被仓拒绝,这里前置挡掉 req.logisticsType = 0; req.productItems = toProductItems(cmd.lines()); req.cartonItems = toCartonItems(cmd.cartons()); req.batchItems = toBatchItems(cmd.batches()); return req; } private static List toProductItems( List lines) { List items = new ArrayList(lines.size()); for (InboundLine line : lines) { YqnDtos.CreateInboundPlanRequest.InboundProductItem item = new YqnDtos.CreateInboundPlanRequest.InboundProductItem(); item.sku = skuOf(line.providerSku(), line.omsSku()); item.qty = line.quantity(); Money cost = line.cost(); item.cost = cost == null ? null : cost.amount().doubleValue(); items.add(item); } return items; } private static List toCartonItems( List cartons) { if (cartons == null || cartons.isEmpty()) { return null; } List items = new ArrayList(cartons.size()); for (InboundCarton carton : cartons) { YqnDtos.CreateInboundPlanRequest.InboundCartonItem item = new YqnDtos.CreateInboundPlanRequest.InboundCartonItem(); item.sku = carton.providerSku(); item.qty = carton.quantity(); item.cartonQty = carton.cartonQuantity() > 0 ? carton.cartonQuantity() : null; item.cartonNo = carton.cartonNo(); item.sid = carton.sid(); item.cartonWeight = positiveOrNull(carton.weightGrams()); item.cartonLength = positiveOrNull(carton.lengthCm()); item.cartonWidth = positiveOrNull(carton.widthCm()); item.cartonHeight = positiveOrNull(carton.heightCm()); items.add(item); } return items; } private static List toBatchItems( List batches) { if (batches == null || batches.isEmpty()) { return null; } List items = new ArrayList(batches.size()); for (InboundBatch batch : batches) { YqnDtos.CreateInboundPlanRequest.InboundBatchItem item = new YqnDtos.CreateInboundPlanRequest.InboundBatchItem(); item.sku = batch.providerSku(); item.cartonNo = batch.cartonNo(); item.qty = batch.quantity(); List params = new ArrayList(batch.params().size()); for (InboundBatch.BatchParam param : batch.params()) { YqnDtos.CreateInboundPlanRequest.BatchAttr attr = new YqnDtos.CreateInboundPlanRequest.BatchAttr(); attr.batchAttriKey = param.key(); attr.batchAttriValue = param.value(); params.add(attr); } item.batchParam = params; items.add(item); } return items; } /** 运去哪对集装箱号有格式要求,传错会被仓拒绝;本地先挡,省一个来回。 */ static void requireContainerNo(String containerNo) { if (containerNo == null || containerNo.trim().isEmpty()) { return; } if (!CONTAINER_NO.matcher(containerNo.trim()).matches()) { throw new IllegalArgumentException( "yqn containerNo must be 4 uppercase letters + 7 digits, got: " + containerNo); } } static String formatDate(LocalDate date) { return date == null ? null : DATE.format(date); } static String skuOf(String providerSku, String omsSku) { if (providerSku != null && !providerSku.trim().isEmpty()) { return providerSku.trim(); } return omsSku; } private static Double positiveOrNull(double v) { return v > 0 ? v : null; } // ------------------------------------------------------------------ 查询 /** 运去哪入库状态码 → 统一状态。未知码归 {@link InboundStatus#UNKNOWN},不猜。 */ static InboundStatus toStatus(String rawStatus) { if (rawStatus == null || rawStatus.trim().isEmpty()) { return InboundStatus.UNKNOWN; } switch (rawStatus.trim()) { case "0": return InboundStatus.DRAFT; case "5": return InboundStatus.PENDING_REVIEW; case "6": return InboundStatus.REJECTED; case "8": return InboundStatus.PENDING_PACKING; case "10": return InboundStatus.PENDING_SHIPMENT; case "16": return InboundStatus.RECEIVING; case "17": return InboundStatus.RECEIVED; case "20": return InboundStatus.PENDING_STORAGE; case "25": return InboundStatus.STORING; case "70": return InboundStatus.COMPLETED; case "100": return InboundStatus.CANCELLED; default: return InboundStatus.UNKNOWN; } } /** 入库计划详情 → 统一入库单(API 101)。 */ public static InboundOrder toOrder(YqnDtos.InboundPlanInfo info, String warehouseCode, ZoneId zone) { return InboundOrder.builder() .inboundRequestNo(firstNonBlank(info.sourceNo, info.inboundPlanOrderNo)) .providerInboundId(info.inboundPlanOrderNo) .warehouseCode(firstNonBlank(info.orgWarehouseCode, warehouseCode)) .status(toStatus(info.inboundPlanOrderStatus)) .rawStatus(info.inboundPlanOrderStatus) .inventoryType(intOf(info.inventoryType)) .boxCount(intOf(info.cartonQty)) .createdAt(null) .receivedAt(parseDate(info.firstReceptionDate, zone)) .estimatedArrivalAt(parseDate(info.estimateArriveTime, zone)) .actualArrivalAt(parseDate(info.actualArriveTime, zone)) .shipperName(info.shipperName) .shipperContact(info.shipperContact) .shipperPhone(info.shipperPhone) .shipperAddress(info.shipperAddress) .totalWeightKg(info.totalWeight) .totalVolumeCbm(info.totalVolume) .remark(info.remark) .lines(toOrderLines(info.planProductDetailParamList, zone)) .build(); } private static List toOrderLines( List details, ZoneId zone) { if (details == null || details.isEmpty()) { return java.util.Collections.emptyList(); } List lines = new ArrayList(details.size()); for (YqnDtos.InboundPlanInfo.PlanProductDetail detail : details) { if (detail.sku == null || detail.sku.trim().isEmpty()) { continue; } lines.add(InboundOrderLine.builder() .providerSku(detail.sku.trim()) .plannedQuantity(intOf(detail.qty)) .packedQuantity(intOf(detail.qtyPacked)) .receivedQuantity(intOf(detail.qtyReceived)) .receivedSaleableQuantity(intOf(detail.qtyReceivedSaleable)) .receivedUnsaleableQuantity(intOf(detail.qtyReceivedUnsaleable)) .receivedAt(parseTime(detail.receivedTime, zone)) .build()); } return lines; } /** 文档里的日期字段是 {@code yyyy-MM-dd},也可能是完整时间;两种都接。 */ static Instant parseDate(String value, ZoneId zone) { if (value == null || value.trim().isEmpty()) { return null; } String v = value.trim(); try { return LocalDate.parse(v, DATE).atStartOfDay(zone == null ? DEFAULT_ZONE : zone).toInstant(); } catch (DateTimeParseException ignored) { // 落到下面按完整时间解析 } try { return java.time.LocalDateTime.parse(v, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) .atZone(zone == null ? DEFAULT_ZONE : zone).toInstant(); } catch (DateTimeParseException ignored) { try { return Instant.parse(v); } catch (DateTimeParseException alsoIgnored) { return null; } } } static Instant parseTime(String value, ZoneId zone) { return parseDate(value, zone); } static int intOf(String value) { if (value == null || value.trim().isEmpty()) { return 0; } try { return Integer.parseInt(value.trim()); } catch (NumberFormatException e) { return 0; } } static int intOf(Integer value) { return value == null ? 0 : value; } private static String firstNonBlank(String a, String b) { if (a != null && !a.trim().isEmpty()) { return a.trim(); } return b; } private static final ZoneId DEFAULT_ZONE = ZoneId.of("Asia/Shanghai"); }