37 changed files with 4026 additions and 43 deletions
@ -0,0 +1,28 @@
@@ -0,0 +1,28 @@
|
||||
package common.ecommerce.warehouse.capability; |
||||
|
||||
import common.ecommerce.warehouse.model.ChannelRecommendQuery; |
||||
import common.ecommerce.warehouse.model.ChannelRecommendResult; |
||||
import common.ecommerce.warehouse.sdk.WarehouseAdapter; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
|
||||
/** |
||||
* 最优渠道推荐能力:给定 SKU 与目的地邮编,由仓给出推荐仓 + 渠道与全部报价。 |
||||
* |
||||
* <p><b>与 {@link WarehouseFeeEstimateCapable} 不是一回事</b>:那个要求调用方 |
||||
* 指定包裹尺寸重量与物流渠道,问「这么发多少钱」;本能力只给货品与邮编, |
||||
* 由仓回答「发哪儿、走哪条渠道、多少钱」。</p> |
||||
* |
||||
* <p>只读操作,无幂等要求。</p> |
||||
*/ |
||||
public interface WarehouseChannelRecommendCapable extends WarehouseAdapter { |
||||
|
||||
/** |
||||
* 询价并取推荐方案。 |
||||
* |
||||
* @param query SKU 与件数、目的地邮编;必填项在构造期已校验 |
||||
* @return 仓方推荐方案 + 全部仓 × 渠道报价 |
||||
* @throws common.ecommerce.warehouse.error.WarehouseUnsupportedCapabilityException |
||||
* 该仓不声明 {@code CHANNEL_RECOMMEND} |
||||
*/ |
||||
ChannelRecommendResult recommend(WarehouseContext ctx, ChannelRecommendQuery query); |
||||
} |
||||
@ -0,0 +1,129 @@
@@ -0,0 +1,129 @@
|
||||
package common.ecommerce.warehouse.model; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.Collections; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 最优渠道询价条件:按商品 SKU + 目的地邮编,让仓给出推荐渠道与各仓各渠道报价。 |
||||
* |
||||
* <p><b>与 {@link FeeEstimateQuery} 不是一回事</b>:那个要求调用方给包裹尺寸重量与 |
||||
* 指定物流渠道,属于「已知怎么发、问多少钱」;本类只给货品与邮编,由仓决定 |
||||
* 「发哪个仓、走哪个渠道、多少钱」,所以不需要尺寸重量。</p> |
||||
* |
||||
* <p>只读操作,无幂等要求。</p> |
||||
*/ |
||||
public final class ChannelRecommendQuery { |
||||
|
||||
private final List<SkuQuantity> products; |
||||
private final String postalCode; |
||||
/** 是否需要签名服务;null 表示按仓默认。 */ |
||||
private final Boolean signatureRequired; |
||||
/** 指定发货仓;(null/空)表示让仓在所有仓里择优。 */ |
||||
private final String warehouseCode; |
||||
|
||||
private ChannelRecommendQuery(Builder b) { |
||||
if (b.products.isEmpty()) { |
||||
throw new IllegalArgumentException("products must not be empty"); |
||||
} |
||||
this.products = Collections.unmodifiableList(new ArrayList<SkuQuantity>(b.products)); |
||||
this.postalCode = require(b.postalCode, "postalCode"); |
||||
this.signatureRequired = b.signatureRequired; |
||||
this.warehouseCode = b.warehouseCode; |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
public List<SkuQuantity> products() { |
||||
return products; |
||||
} |
||||
|
||||
/** 目的地邮编。 */ |
||||
public String postalCode() { |
||||
return postalCode; |
||||
} |
||||
|
||||
/** 是否需要签名服务;null 表示不传。 */ |
||||
public Boolean signatureRequired() { |
||||
return signatureRequired; |
||||
} |
||||
|
||||
/** 指定发货仓;null 表示由仓择优。 */ |
||||
public String warehouseCode() { |
||||
return warehouseCode; |
||||
} |
||||
|
||||
private static String require(String v, String name) { |
||||
if (v == null || v.trim().isEmpty()) { |
||||
throw new IllegalArgumentException(name + " must not be blank"); |
||||
} |
||||
return v.trim(); |
||||
} |
||||
|
||||
/** 一行商品:SKU 与件数。 */ |
||||
public static final class SkuQuantity { |
||||
|
||||
private final String sku; |
||||
private final int quantity; |
||||
|
||||
public SkuQuantity(String sku, int quantity) { |
||||
if (sku == null || sku.trim().isEmpty()) { |
||||
throw new IllegalArgumentException("sku must not be blank"); |
||||
} |
||||
if (quantity <= 0) { |
||||
throw new IllegalArgumentException("quantity must be positive"); |
||||
} |
||||
this.sku = sku.trim(); |
||||
this.quantity = quantity; |
||||
} |
||||
|
||||
public String sku() { |
||||
return sku; |
||||
} |
||||
|
||||
public int quantity() { |
||||
return quantity; |
||||
} |
||||
} |
||||
|
||||
public static final class Builder { |
||||
|
||||
private final List<SkuQuantity> products = new ArrayList<SkuQuantity>(); |
||||
private String postalCode; |
||||
private Boolean signatureRequired; |
||||
private String warehouseCode; |
||||
|
||||
public Builder product(String sku, int quantity) { |
||||
this.products.add(new SkuQuantity(sku, quantity)); |
||||
return this; |
||||
} |
||||
|
||||
public Builder products(List<SkuQuantity> products) { |
||||
if (products != null) { |
||||
this.products.addAll(products); |
||||
} |
||||
return this; |
||||
} |
||||
|
||||
public Builder postalCode(String v) { |
||||
this.postalCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder signatureRequired(Boolean v) { |
||||
this.signatureRequired = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder warehouseCode(String v) { |
||||
this.warehouseCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public ChannelRecommendQuery build() { |
||||
return new ChannelRecommendQuery(this); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,341 @@
@@ -0,0 +1,341 @@
|
||||
package common.ecommerce.warehouse.model; |
||||
|
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.Collections; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 最优渠道询价结果:一个仓方的推荐结论 + 全部仓 × 渠道的报价明细。 |
||||
* |
||||
* <p>文档给两层:一层是「最优方案」(单条),一层是「所有仓库费用列表」。 |
||||
* 两层都保留——只给最优就没法比价,只给明细又得让每个调用方自己算最小值。</p> |
||||
* |
||||
* <p>这是<b>报价</b>,不是账单:实际费用以出库结算为准。</p> |
||||
*/ |
||||
public final class ChannelRecommendResult { |
||||
|
||||
/** 接入通道。 */ |
||||
private final WarehouseProvider sourceProvider; |
||||
/** 最优方案;仓方没给出时为 null。 */ |
||||
private final OptimalPlan optimalPlan; |
||||
/** 所有仓库的报价;可能为空。 */ |
||||
private final List<WarehouseQuote> warehouseQuotes; |
||||
|
||||
private ChannelRecommendResult(Builder b) { |
||||
this.sourceProvider = b.sourceProvider; |
||||
this.optimalPlan = b.optimalPlan; |
||||
this.warehouseQuotes = Collections.unmodifiableList(new ArrayList<WarehouseQuote>(b.warehouseQuotes)); |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
public WarehouseProvider sourceProvider() { |
||||
return sourceProvider; |
||||
} |
||||
|
||||
/** 最优方案;可能为 null。 */ |
||||
public OptimalPlan optimalPlan() { |
||||
return optimalPlan; |
||||
} |
||||
|
||||
/** 所有仓库的报价;可能为空。 */ |
||||
public List<WarehouseQuote> warehouseQuotes() { |
||||
return warehouseQuotes; |
||||
} |
||||
|
||||
/** 仓方的推荐方案。 */ |
||||
public static final class OptimalPlan { |
||||
|
||||
private final String warehouseCode; |
||||
private final String serviceCode; |
||||
private final Money total; |
||||
|
||||
private OptimalPlan(Builder b) { |
||||
this.warehouseCode = require(b.warehouseCode, "warehouseCode"); |
||||
this.serviceCode = require(b.serviceCode, "serviceCode"); |
||||
this.total = b.total; |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
/** 推荐发货仓。 */ |
||||
public String warehouseCode() { |
||||
return warehouseCode; |
||||
} |
||||
|
||||
/** 推荐物流方式(仓方渠道码)。 */ |
||||
public String serviceCode() { |
||||
return serviceCode; |
||||
} |
||||
|
||||
/** 总费用;仓方未给时为 null。 */ |
||||
public Money total() { |
||||
return total; |
||||
} |
||||
|
||||
private static String require(String v, String name) { |
||||
if (v == null || v.trim().isEmpty()) { |
||||
throw new IllegalArgumentException(name + " must not be blank"); |
||||
} |
||||
return v.trim(); |
||||
} |
||||
|
||||
public static final class Builder { |
||||
private String warehouseCode; |
||||
private String serviceCode; |
||||
private Money total; |
||||
|
||||
public Builder warehouseCode(String v) { |
||||
this.warehouseCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder serviceCode(String v) { |
||||
this.serviceCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder total(Money v) { |
||||
this.total = v; |
||||
return this; |
||||
} |
||||
|
||||
public OptimalPlan build() { |
||||
return new OptimalPlan(this); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** 单个仓库的报价:库存是否够 + 各渠道报价。 */ |
||||
public static final class WarehouseQuote { |
||||
|
||||
private final String warehouseCode; |
||||
/** 库存是否足够;null 表示仓方没给。 */ |
||||
private final Boolean inventoryEnough; |
||||
/** 库存不足的原因;正常为空。 */ |
||||
private final String insufficientStockError; |
||||
private final List<ServiceQuote> services; |
||||
|
||||
private WarehouseQuote(Builder b) { |
||||
this.warehouseCode = require(b.warehouseCode, "warehouseCode"); |
||||
this.inventoryEnough = b.inventoryEnough; |
||||
this.insufficientStockError = b.insufficientStockError; |
||||
this.services = Collections.unmodifiableList(new ArrayList<ServiceQuote>(b.services)); |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
public String warehouseCode() { |
||||
return warehouseCode; |
||||
} |
||||
|
||||
/** 库存是否足够;null 表示未知。 */ |
||||
public Boolean inventoryEnough() { |
||||
return inventoryEnough; |
||||
} |
||||
|
||||
/** 库存不足的原因;无则为 null。 */ |
||||
public String insufficientStockError() { |
||||
return insufficientStockError; |
||||
} |
||||
|
||||
/** 该仓下的渠道报价;可能为空。 */ |
||||
public List<ServiceQuote> services() { |
||||
return services; |
||||
} |
||||
|
||||
private static String require(String v, String name) { |
||||
if (v == null || v.trim().isEmpty()) { |
||||
throw new IllegalArgumentException(name + " must not be blank"); |
||||
} |
||||
return v.trim(); |
||||
} |
||||
|
||||
public static final class Builder { |
||||
private String warehouseCode; |
||||
private Boolean inventoryEnough; |
||||
private String insufficientStockError; |
||||
private final List<ServiceQuote> services = new ArrayList<ServiceQuote>(); |
||||
|
||||
public Builder warehouseCode(String v) { |
||||
this.warehouseCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder inventoryEnough(Boolean v) { |
||||
this.inventoryEnough = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder insufficientStockError(String v) { |
||||
this.insufficientStockError = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder service(ServiceQuote v) { |
||||
this.services.add(v); |
||||
return this; |
||||
} |
||||
|
||||
public WarehouseQuote build() { |
||||
return new WarehouseQuote(this); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** 单个物流渠道的报价。 */ |
||||
public static final class ServiceQuote { |
||||
|
||||
private final String serviceCode; |
||||
private final Money total; |
||||
private final List<FeeItem> fees; |
||||
|
||||
private ServiceQuote(Builder b) { |
||||
this.serviceCode = require(b.serviceCode, "serviceCode"); |
||||
this.total = b.total; |
||||
this.fees = Collections.unmodifiableList(new ArrayList<FeeItem>(b.fees)); |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
/** 物流方式(仓方渠道码)。 */ |
||||
public String serviceCode() { |
||||
return serviceCode; |
||||
} |
||||
|
||||
/** 总费用;仓方未给时为 null。 */ |
||||
public Money total() { |
||||
return total; |
||||
} |
||||
|
||||
/** 费用明细。 */ |
||||
public List<FeeItem> fees() { |
||||
return fees; |
||||
} |
||||
|
||||
private static String require(String v, String name) { |
||||
if (v == null || v.trim().isEmpty()) { |
||||
throw new IllegalArgumentException(name + " must not be blank"); |
||||
} |
||||
return v.trim(); |
||||
} |
||||
|
||||
public static final class Builder { |
||||
private String serviceCode; |
||||
private Money total; |
||||
private final List<FeeItem> fees = new ArrayList<FeeItem>(); |
||||
|
||||
public Builder serviceCode(String v) { |
||||
this.serviceCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder total(Money v) { |
||||
this.total = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder fee(FeeItem v) { |
||||
this.fees.add(v); |
||||
return this; |
||||
} |
||||
|
||||
public ServiceQuote build() { |
||||
return new ServiceQuote(this); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** 一条费用明细。 */ |
||||
public static final class FeeItem { |
||||
|
||||
/** 一级分类,如「快递费」。 */ |
||||
private final String bigFeeType; |
||||
/** 费用项,如「燃油附加费」。 */ |
||||
private final String feeType; |
||||
private final Money fee; |
||||
|
||||
private FeeItem(Builder b) { |
||||
this.bigFeeType = b.bigFeeType; |
||||
this.feeType = b.feeType; |
||||
this.fee = b.fee; |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
public String bigFeeType() { |
||||
return bigFeeType; |
||||
} |
||||
|
||||
public String feeType() { |
||||
return feeType; |
||||
} |
||||
|
||||
public Money fee() { |
||||
return fee; |
||||
} |
||||
|
||||
public static final class Builder { |
||||
private String bigFeeType; |
||||
private String feeType; |
||||
private Money fee; |
||||
|
||||
public Builder bigFeeType(String v) { |
||||
this.bigFeeType = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder feeType(String v) { |
||||
this.feeType = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder fee(Money v) { |
||||
this.fee = v; |
||||
return this; |
||||
} |
||||
|
||||
public FeeItem build() { |
||||
return new FeeItem(this); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static final class Builder { |
||||
private WarehouseProvider sourceProvider; |
||||
private OptimalPlan optimalPlan; |
||||
private final List<WarehouseQuote> warehouseQuotes = new ArrayList<WarehouseQuote>(); |
||||
|
||||
public Builder sourceProvider(WarehouseProvider v) { |
||||
this.sourceProvider = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder optimalPlan(OptimalPlan v) { |
||||
this.optimalPlan = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder warehouseQuote(WarehouseQuote v) { |
||||
this.warehouseQuotes.add(v); |
||||
return this; |
||||
} |
||||
|
||||
public ChannelRecommendResult build() { |
||||
return new ChannelRecommendResult(this); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,131 @@
@@ -0,0 +1,131 @@
|
||||
package common.ecommerce.warehouse.model; |
||||
|
||||
import java.time.LocalDate; |
||||
|
||||
/** |
||||
* 库龄查询条件。 |
||||
* |
||||
* <p>库龄按计费日期区间查,必须给区间;不给会拉到全部历史,对账时无从解释。</p> |
||||
*/ |
||||
public final class InventoryAgeQuery { |
||||
|
||||
private final LocalDate startDate; |
||||
private final LocalDate endDate; |
||||
/** 仓 code;null 表示用账户配置的仓。 */ |
||||
private final String warehouseCode; |
||||
/** 产品 SKU;null 表示不限。 */ |
||||
private final String providerSku; |
||||
private final int pageSize; |
||||
private final String cursor; |
||||
/** 是否返回费率与计费体积;null 表示按仓默认。 */ |
||||
private final Boolean includeFeeRate; |
||||
|
||||
private InventoryAgeQuery(Builder b) { |
||||
if (b.startDate == null || b.endDate == null) { |
||||
throw new IllegalArgumentException("startDate and endDate are required"); |
||||
} |
||||
if (b.endDate.isBefore(b.startDate)) { |
||||
throw new IllegalArgumentException("endDate must not be earlier than startDate"); |
||||
} |
||||
this.startDate = b.startDate; |
||||
this.endDate = b.endDate; |
||||
this.warehouseCode = b.warehouseCode; |
||||
this.providerSku = b.providerSku; |
||||
this.pageSize = b.pageSize; |
||||
this.cursor = b.cursor; |
||||
this.includeFeeRate = b.includeFeeRate; |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
/** 计费日期区间起点(含)。 */ |
||||
public LocalDate startDate() { |
||||
return startDate; |
||||
} |
||||
|
||||
/** 计费日期区间终点(含)。 */ |
||||
public LocalDate endDate() { |
||||
return endDate; |
||||
} |
||||
|
||||
/** 仓 code;null 表示用账户配置的仓。 */ |
||||
public String warehouseCode() { |
||||
return warehouseCode; |
||||
} |
||||
|
||||
/** 产品 SKU;null 表示不限。 */ |
||||
public String providerSku() { |
||||
return providerSku; |
||||
} |
||||
|
||||
public int pageSize() { |
||||
return pageSize; |
||||
} |
||||
|
||||
public String cursor() { |
||||
return cursor; |
||||
} |
||||
|
||||
/** 是否返回费率;null 表示按仓默认。 */ |
||||
public Boolean includeFeeRate() { |
||||
return includeFeeRate; |
||||
} |
||||
|
||||
public static final class Builder { |
||||
private LocalDate startDate; |
||||
private LocalDate endDate; |
||||
private String warehouseCode; |
||||
private String providerSku; |
||||
private int pageSize = 100; |
||||
private String cursor; |
||||
private Boolean includeFeeRate; |
||||
|
||||
public Builder startDate(LocalDate v) { |
||||
this.startDate = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder endDate(LocalDate v) { |
||||
this.endDate = v; |
||||
return this; |
||||
} |
||||
|
||||
/** 计费日期区间。 */ |
||||
public Builder dateRange(LocalDate start, LocalDate end) { |
||||
this.startDate = start; |
||||
this.endDate = end; |
||||
return this; |
||||
} |
||||
|
||||
public Builder warehouseCode(String v) { |
||||
this.warehouseCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder providerSku(String v) { |
||||
this.providerSku = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder pageSize(int v) { |
||||
this.pageSize = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder cursor(String v) { |
||||
this.cursor = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder includeFeeRate(Boolean v) { |
||||
this.includeFeeRate = v; |
||||
return this; |
||||
} |
||||
|
||||
public InventoryAgeQuery build() { |
||||
return new InventoryAgeQuery(this); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,189 @@
@@ -0,0 +1,189 @@
|
||||
package common.ecommerce.warehouse.model; |
||||
|
||||
import common.ecommerce.shared.support.Money; |
||||
|
||||
import java.time.Instant; |
||||
|
||||
/** |
||||
* 一条库龄记录(按计费日 × 仓库 × SKU × 入库柜号)。 |
||||
* |
||||
* <p>库龄是<b>计费视角</b>的数据,不是库存快照:同一 SKU 在不同入库批次 / 柜号下 |
||||
* 有不同的库龄天数与费率,按天累计出仓储费。所以单独建模,不塞进 |
||||
* {@link InventorySnapshot}——后者回答「现在有多少货」。</p> |
||||
* |
||||
* <p>只读查询结果,无幂等要求。</p> |
||||
*/ |
||||
public final class InventoryAgeRecord { |
||||
|
||||
private final String warehouseCode; |
||||
private final String providerSku; |
||||
/** 计费日期(仓方 {@code dt});仓方按天出账。 */ |
||||
private final Instant billingDate; |
||||
/** 入库柜号;无则为 null。 */ |
||||
private final String cabinetNo; |
||||
/** 实际入库时间(UTC)。 */ |
||||
private final Instant inStockAt; |
||||
/** 库龄天数;仓方原值。 */ |
||||
private final int ageDays; |
||||
/** 库存数量(该批次)。 */ |
||||
private final int quantity; |
||||
/** 总体积(立方米,仓方 {@code total_volume_cbm});可能为 null。 */ |
||||
private final java.math.BigDecimal totalVolumeCbm; |
||||
/** 计费数量。 */ |
||||
private final int billingQuantity; |
||||
/** 费率;仓方未给为 null。 */ |
||||
private final java.math.BigDecimal feeRate; |
||||
/** 当日费用;仓方未给为 null。 */ |
||||
private final Money fee; |
||||
|
||||
private InventoryAgeRecord(Builder b) { |
||||
this.warehouseCode = require(b.warehouseCode, "warehouseCode"); |
||||
this.providerSku = require(b.providerSku, "providerSku"); |
||||
this.billingDate = java.util.Objects.requireNonNull(b.billingDate, "billingDate"); |
||||
this.cabinetNo = b.cabinetNo; |
||||
this.inStockAt = b.inStockAt; |
||||
this.ageDays = b.ageDays; |
||||
this.quantity = b.quantity; |
||||
this.totalVolumeCbm = b.totalVolumeCbm; |
||||
this.billingQuantity = b.billingQuantity; |
||||
this.feeRate = b.feeRate; |
||||
this.fee = b.fee; |
||||
} |
||||
|
||||
public static Builder builder() { |
||||
return new Builder(); |
||||
} |
||||
|
||||
public String warehouseCode() { |
||||
return warehouseCode; |
||||
} |
||||
|
||||
public String providerSku() { |
||||
return providerSku; |
||||
} |
||||
|
||||
/** 计费日期。 */ |
||||
public Instant billingDate() { |
||||
return billingDate; |
||||
} |
||||
|
||||
/** 入库柜号;无则为 null。 */ |
||||
public String cabinetNo() { |
||||
return cabinetNo; |
||||
} |
||||
|
||||
/** 实际入库时间;仓方未给为 null。 */ |
||||
public Instant inStockAt() { |
||||
return inStockAt; |
||||
} |
||||
|
||||
/** 库龄天数。 */ |
||||
public int ageDays() { |
||||
return ageDays; |
||||
} |
||||
|
||||
/** 库存数量(该批次)。 */ |
||||
public int quantity() { |
||||
return quantity; |
||||
} |
||||
|
||||
/** 总体积(立方米);未给为 null。 */ |
||||
public java.math.BigDecimal totalVolumeCbm() { |
||||
return totalVolumeCbm; |
||||
} |
||||
|
||||
/** 计费数量。 */ |
||||
public int billingQuantity() { |
||||
return billingQuantity; |
||||
} |
||||
|
||||
/** 费率;未给为 null。 */ |
||||
public java.math.BigDecimal feeRate() { |
||||
return feeRate; |
||||
} |
||||
|
||||
/** 当日费用;未给为 null。 */ |
||||
public Money fee() { |
||||
return fee; |
||||
} |
||||
|
||||
private static String require(String v, String n) { |
||||
if (v == null || v.trim().isEmpty()) { |
||||
throw new IllegalArgumentException(n + " must not be blank"); |
||||
} |
||||
return v.trim(); |
||||
} |
||||
|
||||
public static final class Builder { |
||||
private String warehouseCode; |
||||
private String providerSku; |
||||
private Instant billingDate; |
||||
private String cabinetNo; |
||||
private Instant inStockAt; |
||||
private int ageDays; |
||||
private int quantity; |
||||
private java.math.BigDecimal totalVolumeCbm; |
||||
private int billingQuantity; |
||||
private java.math.BigDecimal feeRate; |
||||
private Money fee; |
||||
|
||||
public Builder warehouseCode(String v) { |
||||
this.warehouseCode = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder providerSku(String v) { |
||||
this.providerSku = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder billingDate(Instant v) { |
||||
this.billingDate = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder cabinetNo(String v) { |
||||
this.cabinetNo = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder inStockAt(Instant v) { |
||||
this.inStockAt = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder ageDays(int v) { |
||||
this.ageDays = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder quantity(int v) { |
||||
this.quantity = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder totalVolumeCbm(java.math.BigDecimal v) { |
||||
this.totalVolumeCbm = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder billingQuantity(int v) { |
||||
this.billingQuantity = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder feeRate(java.math.BigDecimal v) { |
||||
this.feeRate = v; |
||||
return this; |
||||
} |
||||
|
||||
public Builder fee(Money v) { |
||||
this.fee = v; |
||||
return this; |
||||
} |
||||
|
||||
public InventoryAgeRecord build() { |
||||
return new InventoryAgeRecord(this); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,155 @@
@@ -0,0 +1,155 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.ChannelRecommendQuery; |
||||
import common.ecommerce.warehouse.model.ChannelRecommendResult; |
||||
import common.ecommerce.xincang.dto.XincangDtos; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 最优渠道报文映射({@code api.calculate_order_v3})。 |
||||
* |
||||
* <p>请求体:{@code products[{sku, qty}]} + {@code postcode} + {@code is_sign}, |
||||
* 币种固定 USD(信仓文档金额口径)。</p> |
||||
* |
||||
* <p>响应两层都映射:{@code optimalPlan} 原样给,{@code warehouseFeeList} |
||||
* 逐仓逐渠道展开,费用项保留一级分类与费用名。</p> |
||||
*/ |
||||
public final class XincangChannelRecommendMapper { |
||||
|
||||
private static final String CURRENCY_USD = "USD"; |
||||
/** 信仓只收「是 / 否」。 */ |
||||
private static final String YES = "是"; |
||||
private static final String NO = "否"; |
||||
/** 未指定时按「否」下发(文档必填项)。 */ |
||||
private static final String DEFAULT_SIGN = NO; |
||||
|
||||
private XincangChannelRecommendMapper() { |
||||
} |
||||
|
||||
/** 统一询价条件 → 信仓请求体。 */ |
||||
public static XincangDtos.CalculateV3Request toRequest(ChannelRecommendQuery query) { |
||||
XincangDtos.CalculateV3Request req = new XincangDtos.CalculateV3Request(); |
||||
List<XincangDtos.CalculateV3Request.Product> products = |
||||
new ArrayList<XincangDtos.CalculateV3Request.Product>(query.products().size()); |
||||
for (ChannelRecommendQuery.SkuQuantity item : query.products()) { |
||||
XincangDtos.CalculateV3Request.Product product = new XincangDtos.CalculateV3Request.Product(); |
||||
product.sku = item.sku(); |
||||
product.qty = String.valueOf(item.quantity()); |
||||
products.add(product); |
||||
} |
||||
req.products = products; |
||||
req.postcode = query.postalCode(); |
||||
req.isSign = query.signatureRequired() == null |
||||
? DEFAULT_SIGN |
||||
: (query.signatureRequired() ? YES : NO); |
||||
req.warehouseCode = blankToNull(query.warehouseCode()); |
||||
return req; |
||||
} |
||||
|
||||
/** 信仓响应 → 统一结果。 */ |
||||
public static ChannelRecommendResult toResult(XincangDtos.CalculateV3Result rst) { |
||||
ChannelRecommendResult.Builder builder = ChannelRecommendResult.builder() |
||||
.sourceProvider(WarehouseProvider.XINCANG); |
||||
if (rst.optimalPlan != null) { |
||||
builder.optimalPlan(ChannelRecommendResult.OptimalPlan.builder() |
||||
.warehouseCode(blankToNull(rst.optimalPlan.warehouse) == null |
||||
? "-" : rst.optimalPlan.warehouse.trim()) |
||||
.serviceCode(blankToNull(rst.optimalPlan.serviceCode) == null |
||||
? "-" : rst.optimalPlan.serviceCode.trim()) |
||||
.total(parseMoney(rst.optimalPlan.sum)) |
||||
.build()); |
||||
} |
||||
if (rst.warehouseFeeList != null) { |
||||
for (XincangDtos.CalculateV3Result.WarehouseFee warehouse : rst.warehouseFeeList) { |
||||
if (warehouse == null) { |
||||
continue; |
||||
} |
||||
builder.warehouseQuote(toQuote(warehouse)); |
||||
} |
||||
} |
||||
return builder.build(); |
||||
} |
||||
|
||||
private static ChannelRecommendResult.WarehouseQuote toQuote( |
||||
XincangDtos.CalculateV3Result.WarehouseFee warehouse) { |
||||
ChannelRecommendResult.WarehouseQuote.Builder builder = |
||||
ChannelRecommendResult.WarehouseQuote.builder() |
||||
.warehouseCode(blankToNull(warehouse.warehouse) == null |
||||
? "-" : warehouse.warehouse.trim()) |
||||
.inventoryEnough(parseFlag(warehouse.isInventoryEnough)) |
||||
.insufficientStockError(blankToNull(warehouse.insufficientStockError)); |
||||
if (warehouse.logisticsService != null) { |
||||
for (XincangDtos.CalculateV3Result.LogisticsService service : warehouse.logisticsService) { |
||||
if (service == null || blankToNull(service.serviceCode) == null) { |
||||
continue; |
||||
} |
||||
builder.service(toService(service)); |
||||
} |
||||
} |
||||
return builder.build(); |
||||
} |
||||
|
||||
private static ChannelRecommendResult.ServiceQuote toService( |
||||
XincangDtos.CalculateV3Result.LogisticsService service) { |
||||
ChannelRecommendResult.ServiceQuote.Builder builder = |
||||
ChannelRecommendResult.ServiceQuote.builder() |
||||
.serviceCode(service.serviceCode.trim()) |
||||
.total(parseMoney(service.sum)); |
||||
if (service.fees != null) { |
||||
for (XincangDtos.CalculateV3Result.Fee fee : service.fees) { |
||||
if (fee == null) { |
||||
continue; |
||||
} |
||||
builder.fee(ChannelRecommendResult.FeeItem.builder() |
||||
.bigFeeType(blankToNull(fee.bigFeeType)) |
||||
.feeType(blankToNull(fee.feeType)) |
||||
.fee(parseMoney(fee.customerFee)) |
||||
.build()); |
||||
} |
||||
} |
||||
return builder.build(); |
||||
} |
||||
|
||||
/** |
||||
* 库存是否足够:文档示例给的是 {@code "1"} / {@code "0"}。 |
||||
* |
||||
* <p>历史接口里 {@code isInventoryEnough} 有过 boolean 改成 string 的破坏性变更 |
||||
* (见迁移说明),所以这里同时接受 {@code 1/0} 与 {@code true/false}; |
||||
* 认不出返回 null,不猜。</p> |
||||
*/ |
||||
static Boolean parseFlag(String raw) { |
||||
if (raw == null) { |
||||
return null; |
||||
} |
||||
String s = raw.trim(); |
||||
if ("1".equals(s) || "true".equalsIgnoreCase(s) || "是".equals(s)) { |
||||
return Boolean.TRUE; |
||||
} |
||||
if ("0".equals(s) || "false".equalsIgnoreCase(s) || "否".equals(s)) { |
||||
return Boolean.FALSE; |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
/** 金额字符串 → USD;空值 / 非法返回 null。 */ |
||||
static Money parseMoney(String raw) { |
||||
if (raw == null || raw.trim().isEmpty()) { |
||||
return null; |
||||
} |
||||
try { |
||||
BigDecimal amount = new BigDecimal(raw.trim()); |
||||
return Money.of(amount, CURRENCY_USD); |
||||
} catch (RuntimeException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
private static String blankToNull(String v) { |
||||
return v == null || v.trim().isEmpty() ? null : v.trim(); |
||||
} |
||||
} |
||||
@ -0,0 +1,268 @@
@@ -0,0 +1,268 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.shared.support.Page; |
||||
import common.ecommerce.warehouse.model.InventoryAgeQuery; |
||||
import common.ecommerce.warehouse.model.InventoryAgeRecord; |
||||
import common.ecommerce.warehouse.model.InventoryQuery; |
||||
import common.ecommerce.warehouse.model.InventorySnapshot; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import common.ecommerce.xincang.dto.XincangDtos; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.time.Instant; |
||||
import java.time.LocalDate; |
||||
import java.time.LocalDateTime; |
||||
import java.time.format.DateTimeFormatter; |
||||
import java.time.format.DateTimeParseException; |
||||
import java.util.ArrayList; |
||||
import java.util.LinkedHashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* 库存与库龄报文映射。 |
||||
* |
||||
* <ul> |
||||
* <li>实时库存 {@code GET api.stocklist}</li> |
||||
* <li>库龄列表 {@code GET api.stockagelist}</li> |
||||
* </ul> |
||||
* |
||||
* <p>平台字段名只出现在本类与 {@link XincangDtos};时间按北京时间解析成 UTC。</p> |
||||
*/ |
||||
public final class XincangInventoryMapper { |
||||
|
||||
private static final DateTimeFormatter DATE_TIME = |
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); |
||||
private static final String CURRENCY_USD = "USD"; |
||||
/** 仓方分页上限文档未标明,先按 100 保守截断。 */ |
||||
static final int MAX_PAGE_SIZE = 100; |
||||
|
||||
private XincangInventoryMapper() { |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- 实时库存
|
||||
|
||||
/** |
||||
* 库存查询条件 → query 参数。 |
||||
* |
||||
* <p>{@code warehouse_code} 是信仓必填项:调用方指定优先,否则用账户配置的仓; |
||||
* 两者都没有就拒绝,避免把整个租户的库存拉下来。</p> |
||||
*/ |
||||
public static Map<String, Object> toStockParams(InventoryQuery query, String defaultWarehouseCode) { |
||||
String warehouseCode = firstNonBlank( |
||||
query.warehouseCodes().isEmpty() ? null : query.warehouseCodes().get(0), |
||||
defaultWarehouseCode); |
||||
if (warehouseCode == null) { |
||||
throw new IllegalArgumentException( |
||||
"xincang stocklist requires warehouse_code; none given and account has none"); |
||||
} |
||||
// 信仓只支持单个 warehouse_code;给了多个仓时不能静默只查第一个
|
||||
if (query.warehouseCodes().size() > 1) { |
||||
throw new IllegalArgumentException( |
||||
"xincang stocklist accepts a single warehouse_code, got " |
||||
+ query.warehouseCodes()); |
||||
} |
||||
Map<String, Object> params = new LinkedHashMap<String, Object>(); |
||||
params.put("warehouse_code", warehouseCode); |
||||
if (!query.providerSkus().isEmpty()) { |
||||
params.put("product_no", query.providerSkus().get(0)); |
||||
} |
||||
params.put("page", pageNumber(query.cursor())); |
||||
params.put("limit", pageSize(query.pageSize())); |
||||
return params; |
||||
} |
||||
|
||||
/** 库存响应 → 快照分页。 */ |
||||
public static Page<InventorySnapshot> toSnapshots(XincangDtos.StockListResult rst, |
||||
String fallbackWarehouseCode, |
||||
Instant asOf, |
||||
int currentPage, |
||||
int pageSize) { |
||||
List<InventorySnapshot> out = new ArrayList<InventorySnapshot>(); |
||||
if (rst != null && rst.data != null) { |
||||
for (XincangDtos.StockListResult.StockRow row : rst.data) { |
||||
if (row == null || blank(row.productSku)) { |
||||
continue; |
||||
} |
||||
out.add(InventorySnapshot.builder() |
||||
.warehouseCode(firstNonBlank(row.warehouseCode, fallbackWarehouseCode)) |
||||
.providerSku(row.productSku.trim()) |
||||
.available(intOf(row.canSaleSkuCount)) |
||||
.onHand(intOf(row.realStock)) |
||||
.inTransit(intOf(row.shipSkuCount)) |
||||
.reserved(intOf(row.useSkuCount)) |
||||
// 信仓不区分可售 / 不可售库位,统一按可售
|
||||
.inventoryType(0) |
||||
.asOfUtc(asOf) |
||||
.productName(blankToNull(row.chnName)) |
||||
.pendingOutbound(intOf(row.waitSkuCount)) |
||||
.alertQuantity(intOf(row.alarmCount)) |
||||
.volumeCbm(decimalOf(row.volumeCm)) |
||||
.build()); |
||||
} |
||||
} |
||||
return Page.of(out, nextCursor(currentPage, pageSize, out.size())); |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- 库龄
|
||||
|
||||
/** 库龄查询条件 → query 参数。 */ |
||||
public static Map<String, Object> toAgeParams(InventoryAgeQuery query, String defaultWarehouseCode) { |
||||
Map<String, Object> params = new LinkedHashMap<String, Object>(); |
||||
// bill_date 是「起 - 止」的单值字符串
|
||||
params.put("bill_date", query.startDate().format(DATE) + " - " + query.endDate().format(DATE)); |
||||
putIfPresent(params, "warehouse_code", firstNonBlank(query.warehouseCode(), defaultWarehouseCode)); |
||||
putIfPresent(params, "key", query.providerSku()); |
||||
params.put("page", pageNumber(query.cursor())); |
||||
params.put("limit", pageSize(query.pageSize())); |
||||
if (query.includeFeeRate() != null) { |
||||
params.put("is_need_fee_rate", query.includeFeeRate() ? 1 : 0); |
||||
} |
||||
return params; |
||||
} |
||||
|
||||
/** 库龄响应 → 记录分页。 */ |
||||
public static Page<InventoryAgeRecord> toAgeRecords(XincangDtos.StockAgeListResult rst, |
||||
String fallbackWarehouseCode, |
||||
int currentPage, |
||||
int pageSize) { |
||||
List<InventoryAgeRecord> out = new ArrayList<InventoryAgeRecord>(); |
||||
if (rst != null && rst.data != null) { |
||||
for (XincangDtos.StockAgeListResult.AgeRow row : rst.data) { |
||||
if (row == null || blank(row.productSku)) { |
||||
continue; |
||||
} |
||||
Instant billingDate = parseDate(row.dt); |
||||
if (billingDate == null) { |
||||
// 计费日期是必填主键,解析不出就没法定位这条记录,跳过而不是猜今天
|
||||
continue; |
||||
} |
||||
out.add(InventoryAgeRecord.builder() |
||||
.warehouseCode(firstNonBlank(row.warehouseCode, fallbackWarehouseCode)) |
||||
.providerSku(row.productSku.trim()) |
||||
.billingDate(billingDate) |
||||
.cabinetNo(blankToNull(row.cabinetNo)) |
||||
.inStockAt(parseTime(row.inStockTime)) |
||||
.ageDays(intOf(row.feeDays)) |
||||
.quantity(intOf(row.skuCount)) |
||||
.totalVolumeCbm(decimalOf(row.totalVolumeCbm)) |
||||
.billingQuantity(intOf(row.feeCount)) |
||||
.feeRate(decimalOf(row.configPrice)) |
||||
.fee(parseMoney(row.sumFee)) |
||||
.build()); |
||||
} |
||||
} |
||||
return Page.of(out, nextCursor(currentPage, pageSize, out.size())); |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- internals
|
||||
|
||||
/** |
||||
* 有下一页时返回下一页页码。 |
||||
* |
||||
* <p>信仓分页是 {@code page} / {@code limit},游标存字符串化页码;按「本页是否满页」 |
||||
* 判断还有没有下一页——{@code count} 在部分响应里缺失,不能依赖。</p> |
||||
*/ |
||||
static String nextCursor(int currentPage, int pageSize, int fetched) { |
||||
return fetched >= pageSize ? String.valueOf(currentPage + 1) : null; |
||||
} |
||||
|
||||
static int pageNumber(String cursor) { |
||||
if (blank(cursor)) { |
||||
return 1; |
||||
} |
||||
try { |
||||
int v = Integer.parseInt(cursor.trim()); |
||||
return v > 0 ? v : 1; |
||||
} catch (NumberFormatException e) { |
||||
return 1; |
||||
} |
||||
} |
||||
|
||||
static int pageSize(int requested) { |
||||
if (requested <= 0) { |
||||
return 20; |
||||
} |
||||
return Math.min(requested, MAX_PAGE_SIZE); |
||||
} |
||||
|
||||
static Instant parseTime(String raw) { |
||||
if (blank(raw)) { |
||||
return null; |
||||
} |
||||
try { |
||||
return LocalDateTime.parse(raw.trim(), DATE_TIME) |
||||
.atZone(XincangConstants.SYSTEM_ZONE).toInstant(); |
||||
} catch (DateTimeParseException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
static Instant parseDate(String raw) { |
||||
if (blank(raw)) { |
||||
return null; |
||||
} |
||||
try { |
||||
return LocalDate.parse(raw.trim(), DATE) |
||||
.atStartOfDay(XincangConstants.SYSTEM_ZONE).toInstant(); |
||||
} catch (DateTimeParseException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
static Money parseMoney(String raw) { |
||||
if (blank(raw)) { |
||||
return null; |
||||
} |
||||
try { |
||||
return Money.of(new BigDecimal(raw.trim()), CURRENCY_USD); |
||||
} catch (RuntimeException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
static int intOf(String raw) { |
||||
if (blank(raw)) { |
||||
return 0; |
||||
} |
||||
try { |
||||
return (int) Math.round(Double.parseDouble(raw.trim())); |
||||
} catch (NumberFormatException e) { |
||||
return 0; |
||||
} |
||||
} |
||||
|
||||
static BigDecimal decimalOf(String raw) { |
||||
if (blank(raw)) { |
||||
return null; |
||||
} |
||||
try { |
||||
return new BigDecimal(raw.trim()); |
||||
} catch (NumberFormatException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
static String firstNonBlank(String a, String b) { |
||||
if (!blank(a)) { |
||||
return a.trim(); |
||||
} |
||||
return blank(b) ? null : b.trim(); |
||||
} |
||||
|
||||
static String blankToNull(String v) { |
||||
return blank(v) ? null : v.trim(); |
||||
} |
||||
|
||||
static boolean blank(String v) { |
||||
return v == null || v.trim().isEmpty(); |
||||
} |
||||
|
||||
private static void putIfPresent(Map<String, Object> params, String key, String value) { |
||||
if (!blank(value)) { |
||||
params.put(key, value.trim()); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,203 @@
@@ -0,0 +1,203 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.LabelMode; |
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.OutboundLine; |
||||
import common.ecommerce.warehouse.model.OutboundOrder; |
||||
import common.ecommerce.warehouse.model.ShipTo; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import common.ecommerce.xincang.dto.XincangDtos; |
||||
import common.ecommerce.xincang.enums.XincangOrderStatus; |
||||
|
||||
import java.time.Instant; |
||||
import java.time.LocalDate; |
||||
import java.time.LocalDateTime; |
||||
import java.time.format.DateTimeFormatter; |
||||
import java.time.format.DateTimeParseException; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 信仓订单详情报文 → 统一模型({@code GET api.get_order})。 |
||||
* |
||||
* <p>平台字段名只出现在本类与 {@link XincangDtos}。 |
||||
* 时间字段是北京时间 {@code yyyy-MM-dd HH:mm:ss},统一折算成 UTC。</p> |
||||
*/ |
||||
public final class XincangOrderDetailMapper { |
||||
|
||||
private static final DateTimeFormatter DATE_TIME = |
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); |
||||
private static final String CURRENCY_USD = "USD"; |
||||
|
||||
private XincangOrderDetailMapper() { |
||||
} |
||||
|
||||
/** |
||||
* 订单详情 → {@link OutboundOrder}。 |
||||
* |
||||
* @param detail 详情;调用方保证非 null |
||||
* @param ctx 本次调用上下文(仓编码兜底) |
||||
*/ |
||||
public static OutboundOrder toOrder(XincangDtos.OrderDetail detail, WarehouseContext ctx) { |
||||
OutboundStatus status = XincangOrderStatus.toCore(detail.state); |
||||
return OutboundOrder.builder() |
||||
.warehouseCode(firstNonBlank(detail.warehouseCode, ctx.providerWarehouseId())) |
||||
// 双号:信仓详情只回系统单号 order_no;
|
||||
// outboundRequestNo 用它兜底,业务侧参考号进 orderRef
|
||||
.outboundRequestNo(firstNonBlank(detail.orderNo, detail.ckh)) |
||||
.providerOrderId(blankToNull(detail.orderNo)) |
||||
.orderRef(blankToNull(detail.ckh)) |
||||
.labelMode(labelModeOf(detail.orderType)) |
||||
.status(status) |
||||
.rawStatus(detail.state) |
||||
.carrierCode(blankToNull(detail.logisticsType)) |
||||
.trackingNumber(blankToNull(detail.trackingNumber)) |
||||
.requestedAt(parseTime(detail.gmtCreate)) |
||||
.shippedAt(parseTime(detail.deliveredTime)) |
||||
.sourceProvider(WarehouseProvider.XINCANG) |
||||
.lines(toLines(detail)) |
||||
.shipTo(toShipTo(detail)) |
||||
.exceptionCode(blankToNull(detail.apiError)) |
||||
.estimatedShippingFee(parseMoney(detail.totalAmount)) |
||||
.currency(CURRENCY_USD) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* 面单模式:{@code order_type=wayfair} 是自供面单,其余是仓自有面单。 |
||||
* |
||||
* <p>{@code LabelMode} 表达的正是「谁出面单」,与信仓 order_type 语义一致。</p> |
||||
*/ |
||||
static LabelMode labelModeOf(String orderType) { |
||||
return "wayfair".equalsIgnoreCase(orderType) ? LabelMode.PLATFORM_LABEL : LabelMode.WAREHOUSE_LABEL; |
||||
} |
||||
|
||||
/** |
||||
* 商品行。 |
||||
* |
||||
* <p>详情同时给了 {@code products[]}(一票多件)和 {@code product_sku} / {@code sku_count} |
||||
* 单值字段;前者非空时以它为准,为空才退回单值字段。数量缺失或非正的行直接跳过—— |
||||
* {@link OutboundLine} 要求数量为正,保留会在构造期抛异常。</p> |
||||
*/ |
||||
static List<OutboundLine> toLines(XincangDtos.OrderDetail detail) { |
||||
List<OutboundLine> lines = new ArrayList<OutboundLine>(); |
||||
if (detail.products != null && !detail.products.isEmpty()) { |
||||
int index = 0; |
||||
for (XincangDtos.OrderDetailProduct product : detail.products) { |
||||
if (product == null || blank(product.sku)) { |
||||
continue; |
||||
} |
||||
int qty = parsePositiveInt(product.qty); |
||||
if (qty <= 0) { |
||||
continue; |
||||
} |
||||
index++; |
||||
lines.add(OutboundLine.builder() |
||||
.lineNo(String.valueOf(index)) |
||||
.omsSku(product.sku.trim()) |
||||
.providerSku(product.sku.trim()) |
||||
.quantity(qty) |
||||
.declareName(blankToNull(product.nameZhCn)) |
||||
.build()); |
||||
} |
||||
return lines; |
||||
} |
||||
int qty = parsePositiveInt(detail.skuCount); |
||||
if (!blank(detail.productSku) && qty > 0) { |
||||
lines.add(OutboundLine.builder() |
||||
.lineNo("1") |
||||
.omsSku(detail.productSku.trim()) |
||||
.providerSku(detail.productSku.trim()) |
||||
.quantity(qty) |
||||
.declareName(blankToNull(detail.productName)) |
||||
.build()); |
||||
} |
||||
return lines; |
||||
} |
||||
|
||||
private static ShipTo toShipTo(XincangDtos.OrderDetail detail) { |
||||
if (blank(detail.country) && blank(detail.address) && blank(detail.receiveUser)) { |
||||
return null; |
||||
} |
||||
return ShipTo.builder() |
||||
.name(blankToNull(detail.receiveUser)) |
||||
.phone(blankToNull(detail.phone)) |
||||
.email(blankToNull(detail.email)) |
||||
.countryCode(blankToNull(detail.country)) |
||||
.stateOrProvince(blankToNull(detail.province)) |
||||
.city(blankToNull(detail.city)) |
||||
.addressLine1(blankToNull(detail.address)) |
||||
.addressLine2(blankToNull(detail.address2)) |
||||
.postalCode(blankToNull(detail.postcode)) |
||||
.build(); |
||||
} |
||||
|
||||
/** 北京时间 {@code yyyy-MM-dd HH:mm:ss} → UTC;空值 / 非法返回 null。 */ |
||||
static Instant parseTime(String raw) { |
||||
if (blank(raw)) { |
||||
return null; |
||||
} |
||||
try { |
||||
return LocalDateTime.parse(raw.trim(), DATE_TIME) |
||||
.atZone(XincangConstants.SYSTEM_ZONE).toInstant(); |
||||
} catch (DateTimeParseException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
/** 日期 {@code yyyy-MM-dd} → 北京时间当天 0 点的 UTC 时刻;空值 / 非法返回 null。 */ |
||||
static Instant parseDate(String raw) { |
||||
if (blank(raw)) { |
||||
return null; |
||||
} |
||||
try { |
||||
return LocalDate.parse(raw.trim(), DATE) |
||||
.atStartOfDay(XincangConstants.SYSTEM_ZONE).toInstant(); |
||||
} catch (DateTimeParseException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
/** 金额 → USD;空值 / 非法返回 null(负值保留,费用可能有冲抵)。 */ |
||||
static Money parseMoney(String raw) { |
||||
if (blank(raw)) { |
||||
return null; |
||||
} |
||||
try { |
||||
return Money.of(raw.trim(), CURRENCY_USD); |
||||
} catch (RuntimeException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
static int parsePositiveInt(String raw) { |
||||
if (blank(raw)) { |
||||
return 0; |
||||
} |
||||
try { |
||||
int v = Integer.parseInt(raw.trim()); |
||||
return v > 0 ? v : 0; |
||||
} catch (NumberFormatException e) { |
||||
return 0; |
||||
} |
||||
} |
||||
|
||||
static String firstNonBlank(String a, String b) { |
||||
if (!blank(a)) { |
||||
return a.trim(); |
||||
} |
||||
return blank(b) ? null : b.trim(); |
||||
} |
||||
|
||||
static String blankToNull(String v) { |
||||
return blank(v) ? null : v.trim(); |
||||
} |
||||
|
||||
static boolean blank(String v) { |
||||
return v == null || v.trim().isEmpty(); |
||||
} |
||||
} |
||||
@ -0,0 +1,57 @@
@@ -0,0 +1,57 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.warehouse.enums.TransferStatus; |
||||
import common.ecommerce.warehouse.enums.TransferType; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.TransferOrder; |
||||
import common.ecommerce.xincang.dto.XincangDtos; |
||||
import common.ecommerce.xincang.enums.XincangTransferState; |
||||
|
||||
/** |
||||
* 信仓转运详情报文 → 统一模型({@code GET fba.fba_detail})。 |
||||
* |
||||
* <p>信仓的转运 = 从信仓发往平台仓,统一模型里固定为 {@link TransferType#OUTBOUND}。</p> |
||||
*/ |
||||
public final class XincangTransferDetailMapper { |
||||
|
||||
private XincangTransferDetailMapper() { |
||||
} |
||||
|
||||
/** |
||||
* 转运详情 → {@link TransferOrder}。 |
||||
* |
||||
* @param detail 详情;调用方保证非 null |
||||
*/ |
||||
public static TransferOrder toOrder(XincangDtos.TransferDetail detail) { |
||||
TransferStatus status = XincangTransferState.toCore(detail.state); |
||||
return TransferOrder.builder() |
||||
// 双号:fba_no 是业务侧单号,order_no 是仓侧单号
|
||||
.transferRequestNo(XincangOrderDetailMapper.firstNonBlank( |
||||
detail.fbaNo, detail.orderNo)) |
||||
.providerTransferNo(XincangOrderDetailMapper.blankToNull(detail.orderNo)) |
||||
.fromWarehouseCode(XincangOrderDetailMapper.blankToNull(detail.fromWarehouseName)) |
||||
.toWarehouseCode(XincangOrderDetailMapper.blankToNull(detail.destWarehouseName)) |
||||
.type(TransferType.OUTBOUND) |
||||
.status(status) |
||||
.rawStatus(detail.state) |
||||
.sourceProvider(WarehouseProvider.XINCANG) |
||||
.totalQuantity(totalQuantityOf(detail)) |
||||
.estimatedOutboundAt(XincangOrderDetailMapper.parseDate(detail.preSendTime)) |
||||
.remark(XincangOrderDetailMapper.blankToNull(detail.remark)) |
||||
.build(); |
||||
} |
||||
|
||||
/** 明细件数合计;明细缺失时返回 0(未知,不猜)。 */ |
||||
static int totalQuantityOf(XincangDtos.TransferDetail detail) { |
||||
if (detail.products == null || detail.products.isEmpty()) { |
||||
return 0; |
||||
} |
||||
int total = 0; |
||||
for (XincangDtos.TransferDetailProduct product : detail.products) { |
||||
if (product != null) { |
||||
total += XincangOrderDetailMapper.parsePositiveInt(product.skuCount); |
||||
} |
||||
} |
||||
return total; |
||||
} |
||||
} |
||||
@ -0,0 +1,84 @@
@@ -0,0 +1,84 @@
|
||||
package common.ecommerce.xincang.enums; |
||||
|
||||
import common.ecommerce.warehouse.enums.InboundStatus; |
||||
|
||||
/** |
||||
* 信仓预报(头程入库)状态({@code forecast.forecast_detail} 的 {@code state})。 |
||||
* |
||||
* <p>码表来自 Apifox「OMS接口文档V2」预报详情: |
||||
* 0 建仓中 / 1 出运中 / 2 预报完成 / 3 在海上 / 4 送仓中 / 5 卸柜中 / |
||||
* 6 清点中 / 7 上架中 / 8 上架完成 / 9 已驳回。</p> |
||||
* |
||||
* <p>信仓没有独立的「入库单」接口,预报单即头程入库单,这里映射到统一的 |
||||
* {@link InboundStatus}。映射口径:</p> |
||||
* <ul> |
||||
* <li>0 建仓中 → 草稿(尚未提交)</li> |
||||
* <li>1 出运中 / 3 在海上 → 在途</li> |
||||
* <li>2 预报完成 → 待发货(预报已确认,等待实际发运)</li> |
||||
* <li>6 清点中 → 收货中;7 上架中 → 上架中;8 上架完成 → 已完成</li> |
||||
* </ul> |
||||
* |
||||
* <p>未知码归 {@link #UNKNOWN},不猜。</p> |
||||
*/ |
||||
public enum XincangForecastStatus { |
||||
|
||||
/** 0 建仓中。 */ |
||||
BUILDING("0", InboundStatus.DRAFT), |
||||
/** 1 出运中。 */ |
||||
SHIPPING("1", InboundStatus.IN_TRANSIT), |
||||
/** 2 预报完成。 */ |
||||
FORECAST_DONE("2", InboundStatus.PENDING_SHIPMENT), |
||||
/** 3 在海上。 */ |
||||
ON_SEA("3", InboundStatus.IN_TRANSIT), |
||||
/** 4 送仓中。 */ |
||||
DELIVERING("4", InboundStatus.IN_TRANSIT), |
||||
/** 5 卸柜中。 */ |
||||
UNLOADING("5", InboundStatus.RECEIVING), |
||||
/** 6 清点中。 */ |
||||
COUNTING("6", InboundStatus.RECEIVING), |
||||
/** 7 上架中。 */ |
||||
SHELVING("7", InboundStatus.STORING), |
||||
/** 8 上架完成。 */ |
||||
SHELVED("8", InboundStatus.COMPLETED), |
||||
/** 9 已驳回。 */ |
||||
REJECTED("9", InboundStatus.REJECTED), |
||||
/** 无法识别。 */ |
||||
UNKNOWN(null, InboundStatus.UNKNOWN); |
||||
|
||||
private final String rawCode; |
||||
private final InboundStatus core; |
||||
|
||||
XincangForecastStatus(String rawCode, InboundStatus core) { |
||||
this.rawCode = rawCode; |
||||
this.core = core; |
||||
} |
||||
|
||||
/** 信仓状态码;null 表示无法识别。 */ |
||||
public String rawCode() { |
||||
return rawCode; |
||||
} |
||||
|
||||
/** 对应的底层状态。 */ |
||||
public InboundStatus toCore() { |
||||
return core; |
||||
} |
||||
|
||||
/** 信仓状态码 → 平台枚举。 */ |
||||
public static XincangForecastStatus of(String rawStatus) { |
||||
if (rawStatus == null || rawStatus.trim().isEmpty()) { |
||||
return UNKNOWN; |
||||
} |
||||
String s = rawStatus.trim(); |
||||
for (XincangForecastStatus v : values()) { |
||||
if (s.equals(v.rawCode)) { |
||||
return v; |
||||
} |
||||
} |
||||
return UNKNOWN; |
||||
} |
||||
|
||||
/** 信仓状态码 → 底层状态。 */ |
||||
public static InboundStatus toCore(String rawStatus) { |
||||
return of(rawStatus).toCore(); |
||||
} |
||||
} |
||||
@ -0,0 +1,93 @@
@@ -0,0 +1,93 @@
|
||||
package common.ecommerce.xincang.enums; |
||||
|
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
|
||||
/** |
||||
* 信仓出库订单状态(订单列表 / 详情 / 删除接口的 {@code state})。 |
||||
* |
||||
* <p>码表来自 Apifox「OMS接口文档V2」订单详情: |
||||
* 0 待审核 / 1 待发货 / 2 拣货中 / 3 已拣货 / 4 已贴单 / 5 已发货 / |
||||
* 6 已拦截 / 7 缺货 / 8 已取消 / 10 已删除 / 11 审核中 / 12 审核失败。</p> |
||||
* |
||||
* <p>未知码归 {@link #UNKNOWN},<b>不猜</b>;原始值由调用方一起保存 |
||||
* ({@code rawStatus} + {@code sourceProvider})。</p> |
||||
*/ |
||||
public enum XincangOrderStatus { |
||||
|
||||
/** 0 待审核。 */ |
||||
PENDING_REVIEW("0", OutboundStatus.PENDING_REVIEW), |
||||
/** 1 待发货。 */ |
||||
PENDING_SHIPMENT("1", OutboundStatus.PENDING_SHIPMENT), |
||||
/** 2 拣货中。 */ |
||||
PICKING("2", OutboundStatus.PICKING), |
||||
/** 3 已拣货。 */ |
||||
PICKED("3", OutboundStatus.PICKED), |
||||
/** 4 已贴单(面单已出)。 */ |
||||
LABEL_READY("4", OutboundStatus.LABEL_READY), |
||||
/** 5 已发货。 */ |
||||
SHIPPED("5", OutboundStatus.SHIPPED), |
||||
/** 6 已拦截。 */ |
||||
INTERCEPTED("6", OutboundStatus.INTERCEPTED), |
||||
/** 7 缺货。 */ |
||||
OUT_OF_STOCK("7", OutboundStatus.OUT_OF_STOCK), |
||||
/** 8 已取消。 */ |
||||
CANCELLED("8", OutboundStatus.CANCELLED), |
||||
/** 10 已删除。 */ |
||||
DELETED("10", OutboundStatus.DELETED), |
||||
/** 11 审核中。 */ |
||||
REVIEWING("11", OutboundStatus.REVIEWING), |
||||
/** 12 审核失败。 */ |
||||
REVIEW_FAILED("12", OutboundStatus.REVIEW_FAILED), |
||||
/** 无法识别。 */ |
||||
UNKNOWN(null, OutboundStatus.UNKNOWN); |
||||
|
||||
private final String rawCode; |
||||
private final OutboundStatus core; |
||||
|
||||
XincangOrderStatus(String rawCode, OutboundStatus core) { |
||||
this.rawCode = rawCode; |
||||
this.core = core; |
||||
} |
||||
|
||||
/** 信仓状态码;null 表示无法识别。 */ |
||||
public String rawCode() { |
||||
return rawCode; |
||||
} |
||||
|
||||
/** 对应的底层状态。 */ |
||||
public OutboundStatus toCore() { |
||||
return core; |
||||
} |
||||
|
||||
/** 信仓状态码 → 平台枚举。 */ |
||||
public static XincangOrderStatus of(String rawStatus) { |
||||
if (rawStatus == null || rawStatus.trim().isEmpty()) { |
||||
return UNKNOWN; |
||||
} |
||||
String s = rawStatus.trim(); |
||||
for (XincangOrderStatus v : values()) { |
||||
if (s.equals(v.rawCode)) { |
||||
return v; |
||||
} |
||||
} |
||||
return UNKNOWN; |
||||
} |
||||
|
||||
/** 信仓状态码 → 底层状态。 */ |
||||
public static OutboundStatus toCore(String rawStatus) { |
||||
return of(rawStatus).toCore(); |
||||
} |
||||
|
||||
/** 底层状态 → 信仓状态码;无对应时返回 null(调用方决定是否拒绝)。 */ |
||||
public static String codeOf(OutboundStatus status) { |
||||
if (status == null) { |
||||
return null; |
||||
} |
||||
for (XincangOrderStatus v : values()) { |
||||
if (v.core == status) { |
||||
return v.rawCode; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
} |
||||
@ -0,0 +1,49 @@
@@ -0,0 +1,49 @@
|
||||
package common.ecommerce.xincang.enums; |
||||
|
||||
/** |
||||
* 信仓下单的订单类型({@code api.add_order_multiple} 的 {@code order_type})。 |
||||
* |
||||
* <p>信仓只接受两个值:{@code common}(非自供面单)与 {@code wayfair}(自供面单)。</p> |
||||
* |
||||
* <p><b>只在这里出现,不映射到 core</b>:这是「由谁提供面单」的仓方协议开关, |
||||
* core 已有 {@code LabelMode} 表达同一业务语义(仓出单 / 平台面单)。 |
||||
* 两者的判定口径不同——core 看 {@code LabelMode},信仓看渠道平台是不是 Wayfair—— |
||||
* 所以由适配器按自己的规则选择,不做枚举级映射,也不把仓方字符串塞进 core。</p> |
||||
*/ |
||||
public enum XincangOrderType { |
||||
|
||||
/** 非自供面单(默认)。 */ |
||||
COMMON("common"), |
||||
/** 自供面单;{@code gzh} 与 {@code face_base64} 必填。 */ |
||||
WAYFAIR("wayfair"); |
||||
|
||||
private final String rawCode; |
||||
|
||||
XincangOrderType(String rawCode) { |
||||
this.rawCode = rawCode; |
||||
} |
||||
|
||||
/** 信仓原值。 */ |
||||
public String rawCode() { |
||||
return rawCode; |
||||
} |
||||
|
||||
/** 是否需要随单提供跟踪号与面单文件。 */ |
||||
public boolean requiresSelfLabel() { |
||||
return this == WAYFAIR; |
||||
} |
||||
|
||||
/** 信仓原值 → 平台枚举;未知返回 null(调用方按错误处理)。 */ |
||||
public static XincangOrderType of(String rawCode) { |
||||
if (rawCode == null) { |
||||
return null; |
||||
} |
||||
String s = rawCode.trim(); |
||||
for (XincangOrderType v : values()) { |
||||
if (v.rawCode.equals(s)) { |
||||
return v; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
} |
||||
@ -0,0 +1,87 @@
@@ -0,0 +1,87 @@
|
||||
package common.ecommerce.xincang.enums; |
||||
|
||||
import common.ecommerce.warehouse.enums.TransferStatus; |
||||
|
||||
/** |
||||
* 信仓转运单状态({@code fba.fbalist} / {@code fba.fba_detail} 的 {@code state})。 |
||||
* |
||||
* <p>码表来自 Apifox「OMS接口文档V2」转运详情: |
||||
* 0 待审核 / 1 待处理 / 2 待拣货 / 3 待贴标 / 4 待打托 / 5 待发货 / 6 已发货 / 7 已取消。</p> |
||||
* |
||||
* <p><b>列表接口与详情接口的码表不一致</b>:列表的 {@code state} 说明里写的是 |
||||
* 「0 待审核 1 待处理 2 带拣货 3 待打托 4 待发货 5 已发货 9 取消」(少了「待贴标」、 |
||||
* 后续码值整体前移)。详情接口的码表与 {@code state_name} 说明更完整,这里以<b>详情码表</b> |
||||
* 为准;联调时如果列表返回的 {@code state} 对不上,原始值仍在 {@code rawStatus} 里, |
||||
* 只需调整本枚举,不动调用方。</p> |
||||
*/ |
||||
public enum XincangTransferState { |
||||
|
||||
/** 0 待审核。 */ |
||||
PENDING_REVIEW("0", TransferStatus.PENDING_REVIEW), |
||||
/** 1 待处理。 */ |
||||
PENDING_PROCESSING("1", TransferStatus.PENDING_PROCESSING), |
||||
/** 2 待拣货。 */ |
||||
PENDING_PICK("2", TransferStatus.PENDING_PICK), |
||||
/** 3 待贴标。 */ |
||||
PENDING_LABELING("3", TransferStatus.PENDING_LABELING), |
||||
/** 4 待打托。 */ |
||||
PENDING_PALLETIZING("4", TransferStatus.PENDING_PALLETIZING), |
||||
/** 5 待发货。 */ |
||||
PENDING_OUTBOUND("5", TransferStatus.PENDING_OUTBOUND), |
||||
/** 6 已发货。 */ |
||||
SHIPPED("6", TransferStatus.SHIPPED), |
||||
/** 7 已取消。 */ |
||||
CANCELLED("7", TransferStatus.CANCELLED), |
||||
/** 无法识别。 */ |
||||
UNKNOWN(null, TransferStatus.UNKNOWN); |
||||
|
||||
private final String rawCode; |
||||
private final TransferStatus core; |
||||
|
||||
XincangTransferState(String rawCode, TransferStatus core) { |
||||
this.rawCode = rawCode; |
||||
this.core = core; |
||||
} |
||||
|
||||
/** 信仓状态码;null 表示无法识别。 */ |
||||
public String rawCode() { |
||||
return rawCode; |
||||
} |
||||
|
||||
/** 对应的底层状态。 */ |
||||
public TransferStatus toCore() { |
||||
return core; |
||||
} |
||||
|
||||
/** 信仓状态码 → 平台枚举。 */ |
||||
public static XincangTransferState of(String rawStatus) { |
||||
if (rawStatus == null || rawStatus.trim().isEmpty()) { |
||||
return UNKNOWN; |
||||
} |
||||
String s = rawStatus.trim(); |
||||
for (XincangTransferState v : values()) { |
||||
if (s.equals(v.rawCode)) { |
||||
return v; |
||||
} |
||||
} |
||||
return UNKNOWN; |
||||
} |
||||
|
||||
/** 信仓状态码 → 底层状态。 */ |
||||
public static TransferStatus toCore(String rawStatus) { |
||||
return of(rawStatus).toCore(); |
||||
} |
||||
|
||||
/** 底层状态 → 信仓状态码;无对应时返回 null。 */ |
||||
public static String codeOf(TransferStatus status) { |
||||
if (status == null) { |
||||
return null; |
||||
} |
||||
for (XincangTransferState v : values()) { |
||||
if (v.core == status) { |
||||
return v.rawCode; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
} |
||||
@ -0,0 +1,158 @@
@@ -0,0 +1,158 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.error.PlatformBusinessException; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||
import common.ecommerce.shared.testkit.MutableClock; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.enums.CancelEligibility; |
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.error.OutboundCancelBlockedException; |
||||
import common.ecommerce.warehouse.model.CancelCommand; |
||||
import common.ecommerce.warehouse.model.CancelResult; |
||||
import common.ecommerce.warehouse.model.OutboundRef; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import org.junit.jupiter.api.BeforeEach; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Duration; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.*; |
||||
|
||||
/** |
||||
* 删除订单({@code POST api.delete_order})与取消资格预判契约测试。 |
||||
*/ |
||||
class XincangCancelOrderTest { |
||||
|
||||
private static final String BASE = XincangConstants.TEST_BASE_URL; |
||||
private static final String APP_KEY = "ak-1"; |
||||
|
||||
private static final String DETAIL_PENDING = "{\"rst\":{" |
||||
+ "\"order_no\":\"DS-1\",\"ckh\":\"OB-1\",\"state\":\"0\",\"state_name\":\"待审核\"," |
||||
+ "\"order_type\":\"common\",\"warehouse_code\":\"NJ-2605\"," |
||||
+ "\"products\":[{\"sku\":\"SKU-A\",\"qty\":\"1\"}]}," |
||||
+ "\"errno\":0,\"err\":\"\",\"trace_id\":\"t-1\"}"; |
||||
|
||||
private RecordingTransport transport; |
||||
private XincangAdapter adapter; |
||||
|
||||
@BeforeEach |
||||
void setUp() { |
||||
transport = RecordingTransport.create(); |
||||
MutableClock clock = MutableClock.atUtc("2026-11-10T00:00:00Z"); |
||||
transport.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||
"{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-1}\",\"token_expire_time\":\"" |
||||
+ java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), |
||||
XincangConstants.SYSTEM_ZONE) |
||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) |
||||
+ "\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-login\"}")); |
||||
adapter = new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), |
||||
new InMemoryTokenStore(), new InMemoryLockProvider(), clock); |
||||
} |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("XC-NJ-2605", WarehouseProvider.XINCANG, "NJ-2605", |
||||
WarehouseConnection.of(BASE, ChannelSecret.builder() |
||||
.appKey(APP_KEY).appSecret("sk").build()), |
||||
"req-1", Clock.systemUTC()); |
||||
} |
||||
|
||||
@Test |
||||
void cancelByProviderOrderId() { |
||||
transport.route(XincangConstants.PATH_ORDER_DELETE, req -> Responses.ok( |
||||
"{\"rst\":true,\"errno\":0,\"err\":\"\",\"trace_id\":\"t-del\"}")); |
||||
CancelCommand cmd = CancelCommand.builder() |
||||
.providerOrderId("DS-1") |
||||
.outboundRequestNo("OB-1") |
||||
.build(); |
||||
|
||||
CancelResult result = adapter.cancel(ctx(), cmd); |
||||
|
||||
common.ecommerce.http.HttpRequest req = transport.lastDataRequest(); |
||||
assertEquals("POST", req.method()); |
||||
assertTrue(req.url().contains("/api.delete_order?"), req.url()); |
||||
assertTrue(req.url().contains("order_no=DS-1"), req.url()); |
||||
assertFalse(req.url().contains("ckh="), "有仓单号时不再传参考号"); |
||||
assertTrue(req.url().contains("token=%7BT-1%7D"), req.url()); |
||||
assertNull(req.body(), "删除订单无请求体"); |
||||
|
||||
assertTrue(result.cancelled()); |
||||
assertEquals(CancelEligibility.FREE, result.eligibility()); |
||||
assertEquals("DS-1", result.providerOrderId()); |
||||
assertEquals("OB-1", result.outboundRequestNo()); |
||||
} |
||||
|
||||
@Test |
||||
void cancelFallsBackToReferenceNumber() { |
||||
transport.route(XincangConstants.PATH_ORDER_DELETE, req -> Responses.ok( |
||||
"{\"rst\":true,\"errno\":0,\"err\":\"\"}")); |
||||
CancelCommand cmd = CancelCommand.builder().outboundRequestNo("OB-1").build(); |
||||
|
||||
adapter.cancel(ctx(), cmd); |
||||
|
||||
String url = transport.lastDataRequest().url(); |
||||
assertTrue(url.contains("ckh=OB-1"), url); |
||||
assertFalse(url.contains("order_no="), url); |
||||
} |
||||
|
||||
@Test |
||||
void refusedDeletionBecomesBlockedException() { |
||||
transport.route(XincangConstants.PATH_ORDER_DELETE, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":-1," |
||||
+ "\"err\":\"DS-BZY01-26101500005在该状态下不允许修改\",\"trace_id\":\"t-bad\"}")); |
||||
|
||||
OutboundCancelBlockedException e = assertThrows(OutboundCancelBlockedException.class, |
||||
() -> adapter.cancel(ctx(), CancelCommand.builder().providerOrderId("DS-1").build())); |
||||
assertTrue(e.getMessage().contains("该状态下不允许修改"), e.getMessage()); |
||||
assertFalse(e.retryable()); |
||||
} |
||||
|
||||
@Test |
||||
void checkCancelUsesOrderStatus() { |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok(DETAIL_PENDING)); |
||||
|
||||
assertEquals(CancelEligibility.FREE, |
||||
adapter.checkCancel(ctx(), OutboundRef.ofProviderOrderId("DS-1"))); |
||||
} |
||||
|
||||
@Test |
||||
void checkCancelMapsTerminalStatesToBlocked() { |
||||
assertBlocked(OutboundStatus.SHIPPED); |
||||
assertBlocked(OutboundStatus.CANCELLED); |
||||
assertBlocked(OutboundStatus.INTERCEPTED); |
||||
assertBlocked(OutboundStatus.DELETED); |
||||
assertBlocked(OutboundStatus.UNKNOWN); |
||||
} |
||||
|
||||
@Test |
||||
void checkCancelAllowsPreShipmentStates() { |
||||
assertFree(OutboundStatus.PENDING_REVIEW); |
||||
assertFree(OutboundStatus.PENDING_SHIPMENT); |
||||
assertFree(OutboundStatus.REVIEWING); |
||||
assertFree(OutboundStatus.PICKING); |
||||
assertFree(OutboundStatus.PICKED); |
||||
} |
||||
|
||||
@Test |
||||
void checkCancelPropagatesLookupFailure() { |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":-1,\"err\":\"订单不存在\",\"trace_id\":\"t-404\"}")); |
||||
|
||||
assertThrows(PlatformBusinessException.class, |
||||
() -> adapter.checkCancel(ctx(), OutboundRef.ofProviderOrderId("DS-X"))); |
||||
} |
||||
|
||||
private static void assertBlocked(OutboundStatus status) { |
||||
assertEquals(CancelEligibility.BLOCKED, XincangAdapter.cancelEligibilityOf(status), status.name()); |
||||
} |
||||
|
||||
private static void assertFree(OutboundStatus status) { |
||||
assertEquals(CancelEligibility.FREE, XincangAdapter.cancelEligibilityOf(status), status.name()); |
||||
} |
||||
} |
||||
@ -0,0 +1,198 @@
@@ -0,0 +1,198 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||
import common.ecommerce.shared.testkit.MutableClock; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.enums.WarehouseCapability; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.ChannelRecommendQuery; |
||||
import common.ecommerce.warehouse.model.ChannelRecommendResult; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import org.junit.jupiter.api.BeforeEach; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Duration; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.*; |
||||
|
||||
/** |
||||
* 最优渠道({@code api.calculate_order_v3})契约测试。 |
||||
*/ |
||||
class XincangChannelRecommendTest { |
||||
|
||||
private static final String BASE = XincangConstants.TEST_BASE_URL; |
||||
private static final String APP_KEY = "ak-1"; |
||||
|
||||
/** 文档成功示例(截取两层结构)。 */ |
||||
private static final String OK_BODY = "{\"rst\":{" |
||||
+ "\"optimalPlan\":{\"warehouse\":\"CA-3790\",\"service_code\":\"GOFO-G\",\"sum\":\"20.87\"}," |
||||
+ "\"warehouseFeeList\":[" |
||||
+ "{\"warehouse\":\"CA-3790\",\"isInventoryEnough\":\"1\",\"insufficientStockError\":\"\"," |
||||
+ "\"logisticsService\":[" |
||||
+ "{\"service_code\":\"GOFO-G\",\"sum\":\"20.87\",\"fees\":[" |
||||
+ "{\"big_fee_type\":\"快递费\",\"fee_type\":\"基础费\",\"customer_fee\":\"11.87\"}," |
||||
+ "{\"big_fee_type\":\"快递费\",\"fee_type\":\"燃油附加费\",\"customer_fee\":\"5.64\"}]}," |
||||
+ "{\"service_code\":\"USPS-G\",\"sum\":\"22.10\",\"fees\":[]}]}," |
||||
+ "{\"warehouse\":\"NJ-2605\",\"isInventoryEnough\":\"0\"," |
||||
+ "\"insufficientStockError\":\"库存不足\",\"logisticsService\":[]}" |
||||
+ "]}," |
||||
+ "\"errno\":0,\"err\":\"\",\"trace_id\":\"t-v3\"}"; |
||||
|
||||
private RecordingTransport transport; |
||||
private XincangAdapter adapter; |
||||
|
||||
@BeforeEach |
||||
void setUp() { |
||||
transport = RecordingTransport.create(); |
||||
MutableClock clock = MutableClock.atUtc("2026-11-10T00:00:00Z"); |
||||
transport.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||
"{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-1}\",\"token_expire_time\":\"" |
||||
+ java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), |
||||
XincangConstants.SYSTEM_ZONE) |
||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) |
||||
+ "\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-login\"}")); |
||||
adapter = new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), |
||||
new InMemoryTokenStore(), new InMemoryLockProvider(), clock); |
||||
} |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("XC-CA-3790", WarehouseProvider.XINCANG, "CA-3790", |
||||
WarehouseConnection.of(BASE, ChannelSecret.builder() |
||||
.appKey(APP_KEY).appSecret("sk").build()), |
||||
"req-1", Clock.systemUTC()); |
||||
} |
||||
|
||||
private static ChannelRecommendQuery query() { |
||||
return ChannelRecommendQuery.builder() |
||||
.product("NOTEBOOK-MULTI-3", 9) |
||||
.product("BOX-PENS-10", 3) |
||||
.postalCode("937862") |
||||
.signatureRequired(false) |
||||
.build(); |
||||
} |
||||
|
||||
@Test |
||||
void sendsDocumentedRequestShape() { |
||||
transport.route(XincangConstants.PATH_CHANNEL_RECOMMEND, req -> Responses.ok(OK_BODY)); |
||||
|
||||
adapter.recommend(ctx(), query()); |
||||
|
||||
common.ecommerce.http.HttpRequest req = transport.lastDataRequest(); |
||||
assertTrue(req.url().contains("/api.calculate_order_v3?token=%7BT-1%7D"), req.url()); |
||||
assertEquals("application/json", req.contentType()); |
||||
|
||||
String body = req.body(); |
||||
assertTrue(body.contains("\"sku\":\"NOTEBOOK-MULTI-3\""), body); |
||||
assertTrue(body.contains("\"qty\":\"9\""), body); |
||||
assertTrue(body.contains("\"sku\":\"BOX-PENS-10\""), body); |
||||
assertTrue(body.contains("\"qty\":\"3\""), body); |
||||
assertTrue(body.contains("\"postcode\":\"937862\""), body); |
||||
assertTrue(body.contains("\"is_sign\":\"否\""), body); |
||||
// 未指定仓库时不下发 warehouse_code
|
||||
assertFalse(body.contains("warehouse_code"), body); |
||||
} |
||||
|
||||
@Test |
||||
void mapsOptimalPlanAndAllQuotes() { |
||||
transport.route(XincangConstants.PATH_CHANNEL_RECOMMEND, req -> Responses.ok(OK_BODY)); |
||||
|
||||
ChannelRecommendResult result = adapter.recommend(ctx(), query()); |
||||
|
||||
assertEquals(WarehouseProvider.XINCANG, result.sourceProvider()); |
||||
|
||||
// 最优方案
|
||||
assertNotNull(result.optimalPlan()); |
||||
assertEquals("CA-3790", result.optimalPlan().warehouseCode()); |
||||
assertEquals("GOFO-G", result.optimalPlan().serviceCode()); |
||||
assertEquals(0, result.optimalPlan().total().amount().compareTo(new java.math.BigDecimal("20.87"))); |
||||
assertEquals("USD", result.optimalPlan().total().currencyCode()); |
||||
|
||||
// 所有仓库明细
|
||||
assertEquals(2, result.warehouseQuotes().size()); |
||||
ChannelRecommendResult.WarehouseQuote first = result.warehouseQuotes().get(0); |
||||
assertEquals("CA-3790", first.warehouseCode()); |
||||
assertEquals(Boolean.TRUE, first.inventoryEnough()); |
||||
assertNull(first.insufficientStockError(), "空串应转 null"); |
||||
assertEquals(2, first.services().size()); |
||||
|
||||
ChannelRecommendResult.ServiceQuote gogo = first.services().get(0); |
||||
assertEquals("GOFO-G", gogo.serviceCode()); |
||||
assertEquals(2, gogo.fees().size()); |
||||
assertEquals("快递费", gogo.fees().get(0).bigFeeType()); |
||||
assertEquals("燃油附加费", gogo.fees().get(1).feeType()); |
||||
assertEquals(0, gogo.fees().get(1).fee().amount() |
||||
.compareTo(new java.math.BigDecimal("5.64"))); |
||||
|
||||
ChannelRecommendResult.WarehouseQuote second = result.warehouseQuotes().get(1); |
||||
assertEquals(Boolean.FALSE, second.inventoryEnough()); |
||||
assertEquals("库存不足", second.insufficientStockError()); |
||||
assertTrue(second.services().isEmpty()); |
||||
} |
||||
|
||||
@Test |
||||
void signatureIsSentWhenRequested() { |
||||
transport.route(XincangConstants.PATH_CHANNEL_RECOMMEND, req -> Responses.ok(OK_BODY)); |
||||
ChannelRecommendQuery signed = ChannelRecommendQuery.builder() |
||||
.product("SKU-A", 1).postalCode("10001").signatureRequired(true).build(); |
||||
|
||||
adapter.recommend(ctx(), signed); |
||||
|
||||
assertTrue(transport.lastDataRequest().body().contains("\"is_sign\":\"是\"")); |
||||
} |
||||
|
||||
@Test |
||||
void warehouseCodeIsSentWhenSpecified() { |
||||
transport.route(XincangConstants.PATH_CHANNEL_RECOMMEND, req -> Responses.ok(OK_BODY)); |
||||
ChannelRecommendQuery pinned = ChannelRecommendQuery.builder() |
||||
.product("SKU-A", 1).postalCode("10001").warehouseCode("CA-3790").build(); |
||||
|
||||
adapter.recommend(ctx(), pinned); |
||||
|
||||
assertTrue(transport.lastDataRequest().body().contains("\"warehouse_code\":\"CA-3790\"")); |
||||
} |
||||
|
||||
@Test |
||||
void emptyOptimalPlanIsNullNotThrow() { |
||||
transport.route(XincangConstants.PATH_CHANNEL_RECOMMEND, req -> Responses.ok( |
||||
"{\"rst\":{\"optimalPlan\":null,\"warehouseFeeList\":[]}," |
||||
+ "\"errno\":0,\"err\":\"\",\"trace_id\":\"t-empty\"}")); |
||||
|
||||
ChannelRecommendResult result = adapter.recommend(ctx(), query()); |
||||
|
||||
assertNull(result.optimalPlan(), "无可用渠道时为 null"); |
||||
assertTrue(result.warehouseQuotes().isEmpty()); |
||||
} |
||||
|
||||
@Test |
||||
void missingRstIsNotSilentSuccess() { |
||||
transport.route(XincangConstants.PATH_CHANNEL_RECOMMEND, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":0,\"err\":\"\"}")); |
||||
|
||||
ValidationException e = assertThrows(ValidationException.class, |
||||
() -> adapter.recommend(ctx(), query())); |
||||
assertTrue(e.getMessage().contains("no rst"), e.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void capabilityDeclared() { |
||||
assertTrue(adapter.capabilities().contains(WarehouseCapability.CHANNEL_RECOMMEND)); |
||||
assertTrue(adapter.supports("XC-CA-3790", WarehouseCapability.CHANNEL_RECOMMEND)); |
||||
} |
||||
|
||||
@Test |
||||
void busyFlagAcceptsBothStringForms() { |
||||
assertEquals(Boolean.TRUE, XincangChannelRecommendMapper.parseFlag("1")); |
||||
assertEquals(Boolean.TRUE, XincangChannelRecommendMapper.parseFlag("true")); |
||||
assertEquals(Boolean.FALSE, XincangChannelRecommendMapper.parseFlag("0")); |
||||
assertEquals(Boolean.FALSE, XincangChannelRecommendMapper.parseFlag("false")); |
||||
assertNull(XincangChannelRecommendMapper.parseFlag("")); |
||||
assertNull(XincangChannelRecommendMapper.parseFlag("unknown")); |
||||
} |
||||
} |
||||
@ -0,0 +1,89 @@
@@ -0,0 +1,89 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.error.PlatformBusinessException; |
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||
import common.ecommerce.shared.testkit.MutableClock; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import org.junit.jupiter.api.BeforeEach; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Duration; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.*; |
||||
|
||||
/** |
||||
* 删除转运({@code POST fba.delete_fba})契约测试。 |
||||
*/ |
||||
class XincangDeleteTransferTest { |
||||
|
||||
private static final String BASE = XincangConstants.TEST_BASE_URL; |
||||
private static final String APP_KEY = "ak-1"; |
||||
|
||||
private RecordingTransport transport; |
||||
private XincangAdapter adapter; |
||||
|
||||
@BeforeEach |
||||
void setUp() { |
||||
transport = RecordingTransport.create(); |
||||
MutableClock clock = MutableClock.atUtc("2026-11-10T00:00:00Z"); |
||||
transport.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||
"{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-1}\",\"token_expire_time\":\"" |
||||
+ java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), |
||||
XincangConstants.SYSTEM_ZONE) |
||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) |
||||
+ "\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-login\"}")); |
||||
adapter = new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), |
||||
new InMemoryTokenStore(), new InMemoryLockProvider(), clock); |
||||
} |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("XC-CA-15950", WarehouseProvider.XINCANG, "CA-15950", |
||||
WarehouseConnection.of(BASE, ChannelSecret.builder() |
||||
.appKey(APP_KEY).appSecret("sk").build()), |
||||
"req-1", Clock.systemUTC()); |
||||
} |
||||
|
||||
@Test |
||||
void deletesTransferByOrderNo() { |
||||
transport.route(XincangConstants.PATH_TRANSFER_DELETE, req -> Responses.ok( |
||||
"{\"rst\":true,\"errno\":0,\"err\":\"\",\"trace_id\":\"t-del\"}")); |
||||
|
||||
adapter.deleteTransfer(ctx(), "LTL26101500002"); |
||||
|
||||
common.ecommerce.http.HttpRequest req = transport.lastDataRequest(); |
||||
assertEquals("POST", req.method()); |
||||
assertTrue(req.url().contains("/fba.delete_fba?"), req.url()); |
||||
assertTrue(req.url().contains("order_no=LTL26101500002"), req.url()); |
||||
assertTrue(req.url().contains("token=%7BT-1%7D"), req.url()); |
||||
assertNull(req.body(), "删除转运无请求体"); |
||||
} |
||||
|
||||
@Test |
||||
void nonPendingTransferIsRejectedByWarehouse() { |
||||
transport.route(XincangConstants.PATH_TRANSFER_DELETE, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":-1,\"err\":\"只有待审核状态的订单可以删除\",\"trace_id\":\"t-bad\"}")); |
||||
|
||||
PlatformBusinessException e = assertThrows(PlatformBusinessException.class, |
||||
() -> adapter.deleteTransfer(ctx(), "LTL-1")); |
||||
assertTrue(e.getMessage().contains("待审核"), e.getMessage()); |
||||
assertFalse(e.retryable()); |
||||
} |
||||
|
||||
@Test |
||||
void blankOrderNoIsRejectedBeforeSending() { |
||||
ValidationException e = assertThrows(ValidationException.class, |
||||
() -> adapter.deleteTransfer(ctx(), " ")); |
||||
assertTrue(e.getMessage().contains("providerTransferNo"), e.getMessage()); |
||||
assertFalse(transport.recorded().stream() |
||||
.anyMatch(r -> r.url().contains(XincangConstants.PATH_TRANSFER_DELETE))); |
||||
} |
||||
} |
||||
@ -0,0 +1,200 @@
@@ -0,0 +1,200 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.support.Page; |
||||
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||
import common.ecommerce.shared.testkit.MutableClock; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.enums.InventorySyncStrategy; |
||||
import common.ecommerce.warehouse.enums.WarehouseCapability; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.InventoryAgeQuery; |
||||
import common.ecommerce.warehouse.model.InventoryAgeRecord; |
||||
import common.ecommerce.warehouse.model.InventoryQuery; |
||||
import common.ecommerce.warehouse.model.InventorySnapshot; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import org.junit.jupiter.api.BeforeEach; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Duration; |
||||
import java.time.Instant; |
||||
import java.time.LocalDate; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.*; |
||||
|
||||
/** |
||||
* 实时库存({@code api.stocklist})与库龄列表({@code api.stockagelist})契约测试。 |
||||
*/ |
||||
class XincangInventoryTest { |
||||
|
||||
private static final String BASE = XincangConstants.TEST_BASE_URL; |
||||
private static final String APP_KEY = "ak-1"; |
||||
|
||||
private static final String STOCK_BODY = "{\"rst\":{\"code\":\"0\",\"msg\":\"\",\"data\":[" |
||||
+ "{\"warehouse_code\":\"NJ-2605\",\"product_sku\":\"LSS29ORANGE\"," |
||||
+ "\"real_stock\":\"1500\",\"cansale_sku_count\":\"1499\",\"use_sku_count\":\"1\"," |
||||
+ "\"wait_sku_count\":\"1\",\"ship_sku_count\":\"0\",\"alerm_count\":\"0\"," |
||||
+ "\"chn_name\":\"餐椅\",\"volume_cm\":\"136221.5274\"}" |
||||
+ "],\"count\":\"1\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-stock\"}"; |
||||
|
||||
private static final String AGE_BODY = "{\"rst\":{\"code\":\"0\",\"msg\":\"\",\"data\":[" |
||||
+ "{\"dt\":\"2026-10-14\",\"warehouse_code\":\"NJ-2605\",\"product_sku\":\"LSS29ORANGE\"," |
||||
+ "\"cabinet_no\":\"KKKKK001\",\"sum_fee\":\"0.00\",\"total_volume_cbm\":\"204.3323\"," |
||||
+ "\"sku_count\":\"1500\",\"in_stock_time\":\"2026-10-14 08:00:00\",\"fee_days\":\"1\"," |
||||
+ "\"config_price\":\"0.50\",\"fee_count\":\"1500\"}" |
||||
+ "],\"count\":\"1\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-age\"}"; |
||||
|
||||
private RecordingTransport transport; |
||||
private XincangAdapter adapter; |
||||
|
||||
@BeforeEach |
||||
void setUp() { |
||||
transport = RecordingTransport.create(); |
||||
MutableClock clock = MutableClock.atUtc("2026-11-10T00:00:00Z"); |
||||
transport.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||
"{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-1}\",\"token_expire_time\":\"" |
||||
+ java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), |
||||
XincangConstants.SYSTEM_ZONE) |
||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) |
||||
+ "\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-login\"}")); |
||||
adapter = new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), |
||||
new InMemoryTokenStore(), new InMemoryLockProvider(), clock); |
||||
} |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("XC-NJ-2605", WarehouseProvider.XINCANG, "NJ-2605", |
||||
WarehouseConnection.of(BASE, ChannelSecret.builder() |
||||
.appKey(APP_KEY).appSecret("sk").build()), |
||||
"req-1", Clock.systemUTC()); |
||||
} |
||||
|
||||
@Test |
||||
void stockQuerySendsWarehouseAndMapsSnapshot() { |
||||
transport.route(XincangConstants.PATH_STOCK_LIST, req -> Responses.ok(STOCK_BODY)); |
||||
|
||||
Page<InventorySnapshot> page = adapter.query(ctx(), |
||||
InventoryQuery.builder().warehouseCode("NJ-2605").pageSize(10).build()); |
||||
|
||||
String url = transport.lastDataRequest().url(); |
||||
assertTrue(url.contains("/api.stocklist?"), url); |
||||
assertTrue(url.contains("warehouse_code=NJ-2605"), url); |
||||
assertTrue(url.contains("page=1"), url); |
||||
assertTrue(url.contains("limit=10"), url); |
||||
assertTrue(url.contains("token=%7BT-1%7D"), url); |
||||
|
||||
assertEquals(1, page.size()); |
||||
InventorySnapshot snap = page.items().get(0); |
||||
assertEquals("NJ-2605", snap.warehouseCode()); |
||||
assertEquals("LSS29ORANGE", snap.providerSku()); |
||||
assertEquals(1500, snap.onHand()); |
||||
assertEquals(1499, snap.available()); |
||||
assertEquals(1, snap.reserved()); |
||||
assertEquals(1, snap.pendingOutbound()); |
||||
assertEquals(0, snap.inTransit()); |
||||
assertEquals(0, snap.inventoryType()); |
||||
assertEquals("餐椅", snap.productName()); |
||||
assertEquals(0, snap.volumeCbm().compareTo(new java.math.BigDecimal("136221.5274"))); |
||||
assertNotNull(snap.asOfUtc()); |
||||
} |
||||
|
||||
@Test |
||||
void stockFallsBackToAccountWarehouse() { |
||||
transport.route(XincangConstants.PATH_STOCK_LIST, req -> Responses.ok(STOCK_BODY)); |
||||
|
||||
adapter.query(ctx(), InventoryQuery.builder().build()); |
||||
|
||||
assertTrue(transport.lastDataRequest().url().contains("warehouse_code=NJ-2605")); |
||||
} |
||||
|
||||
@Test |
||||
void multipleWarehousesAreRejectedInsteadOfSilentlyUsingFirst() { |
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, |
||||
() -> adapter.query(ctx(), InventoryQuery.builder() |
||||
.warehouseCode("A").warehouseCode("B").build())); |
||||
assertTrue(e.getMessage().contains("single warehouse_code"), e.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void stockSkuFilterIsSent() { |
||||
transport.route(XincangConstants.PATH_STOCK_LIST, req -> Responses.ok(STOCK_BODY)); |
||||
|
||||
adapter.query(ctx(), InventoryQuery.builder().sku("LSS29ORANGE").build()); |
||||
|
||||
String url = transport.lastDataRequest().url(); |
||||
assertTrue(url.contains("product_no=LSS29ORANGE"), url); |
||||
} |
||||
|
||||
@Test |
||||
void ageQuerySendsBillDateRangeAndMapsRecord() { |
||||
transport.route(XincangConstants.PATH_STOCK_AGE_LIST, req -> Responses.ok(AGE_BODY)); |
||||
|
||||
Page<InventoryAgeRecord> page = adapter.queryAges(ctx(), InventoryAgeQuery.builder() |
||||
.dateRange(LocalDate.parse("2026-10-01"), LocalDate.parse("2026-10-31")) |
||||
.includeFeeRate(true) |
||||
.build()); |
||||
|
||||
String url = transport.lastDataRequest().url(); |
||||
assertTrue(url.contains("/api.stockagelist?"), url); |
||||
// bill_date 是「起 - 止」单值,空格与连字符会被 URL 编码
|
||||
assertTrue(url.contains("bill_date=2026-10-01+-+2026-10-31"), url); |
||||
assertTrue(url.contains("is_need_fee_rate=1"), url); |
||||
assertTrue(url.contains("warehouse_code=NJ-2605"), "未指定仓时用账户配置: " + url); |
||||
|
||||
assertEquals(1, page.size()); |
||||
InventoryAgeRecord rec = page.items().get(0); |
||||
assertEquals("NJ-2605", rec.warehouseCode()); |
||||
assertEquals("LSS29ORANGE", rec.providerSku()); |
||||
// 计费日期按北京时间 0 点 → UTC 前一天 16:00
|
||||
assertEquals(Instant.parse("2026-10-13T16:00:00Z"), rec.billingDate()); |
||||
assertEquals("KKKKK001", rec.cabinetNo()); |
||||
assertEquals(1, rec.ageDays()); |
||||
assertEquals(1500, rec.quantity()); |
||||
assertEquals(1500, rec.billingQuantity()); |
||||
assertEquals(0, rec.feeRate().compareTo(new java.math.BigDecimal("0.50"))); |
||||
assertEquals(0, rec.fee().amount().compareTo(java.math.BigDecimal.ZERO)); |
||||
assertEquals("USD", rec.fee().currencyCode()); |
||||
assertEquals(Instant.parse("2026-10-14T00:00:00Z"), rec.inStockAt()); |
||||
} |
||||
|
||||
@Test |
||||
void ageQueryRejectsMissingDateRange() { |
||||
assertThrows(IllegalArgumentException.class, |
||||
() -> InventoryAgeQuery.builder().build()); |
||||
assertThrows(IllegalArgumentException.class, |
||||
() -> InventoryAgeQuery.builder() |
||||
.dateRange(LocalDate.parse("2026-10-31"), LocalDate.parse("2026-10-01")) |
||||
.build()); |
||||
} |
||||
|
||||
@Test |
||||
void ageQuerySkipsRowsWithoutBillingDate() { |
||||
String noDate = AGE_BODY.replace("\"dt\":\"2026-10-14\",", "\"dt\":\"\","); |
||||
transport.route(XincangConstants.PATH_STOCK_AGE_LIST, req -> Responses.ok(noDate)); |
||||
|
||||
Page<InventoryAgeRecord> page = adapter.queryAges(ctx(), InventoryAgeQuery.builder() |
||||
.dateRange(LocalDate.parse("2026-10-01"), LocalDate.parse("2026-10-31")).build()); |
||||
|
||||
assertTrue(page.items().isEmpty(), "计费日期解析不出时跳过,不猜日期"); |
||||
} |
||||
|
||||
@Test |
||||
void missingRstIsNotSilentEmpty() { |
||||
transport.route(XincangConstants.PATH_STOCK_LIST, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":0,\"err\":\"\"}")); |
||||
|
||||
assertThrows(ValidationException.class, |
||||
() -> adapter.query(ctx(), InventoryQuery.builder().build())); |
||||
} |
||||
|
||||
@Test |
||||
void inventoryCapabilityAndStrategy() { |
||||
assertTrue(adapter.capabilities().contains(WarehouseCapability.INVENTORY_QUERY)); |
||||
assertEquals(InventorySyncStrategy.FULL_PULL_DIFF, adapter.syncStrategy()); |
||||
} |
||||
} |
||||
@ -0,0 +1,207 @@
@@ -0,0 +1,207 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.error.PlatformBusinessException; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||
import common.ecommerce.shared.testkit.MutableClock; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.enums.LabelMode; |
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.OutboundOrder; |
||||
import common.ecommerce.warehouse.model.OutboundRef; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import org.junit.jupiter.api.BeforeEach; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Duration; |
||||
import java.time.Instant; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.*; |
||||
|
||||
/** |
||||
* 订单详情({@code GET api.get_order})契约测试。 |
||||
*/ |
||||
class XincangOrderDetailTest { |
||||
|
||||
private static final String BASE = XincangConstants.TEST_BASE_URL; |
||||
private static final String APP_KEY = "ak-1"; |
||||
|
||||
/** 文档「成功示例」原文。 */ |
||||
private static final String DETAIL = "{" |
||||
+ "\"id\":\"126508095093477568\"," |
||||
+ "\"order_no\":\"DS-BZY01-26101600001\"," |
||||
+ "\"state\":\"0\"," |
||||
+ "\"state_name\":\"待审核\"," |
||||
+ "\"api_error\":\"验证订单操作失败\"," |
||||
+ "\"gzh\":\"\"," |
||||
+ "\"face_url\":\"\"," |
||||
+ "\"ckh\":\"Ref26101601\"," |
||||
+ "\"order_type\":\"common\"," |
||||
+ "\"products\":[{\"product_id\":\"1\",\"sku\":\"LSS29BLACK\",\"qty\":\"1\"," |
||||
+ "\"name_zh_cn\":\"餐椅\"}]," |
||||
+ "\"sku_count\":\"1\"," |
||||
+ "\"dim_length\":\"25.9840\",\"dim_width\":\"18.8976\",\"dim_height\":\"16.9290\"," |
||||
+ "\"dim_divisor\":\"250.00\",\"weight_lbs\":\"23.5000\"," |
||||
+ "\"billing_weight_lbs\":\"34.00\",\"volume_weight_lbs\":\"34\"," |
||||
+ "\"product_sku\":\"LSS29BLACK\",\"product_name\":\"餐椅\",\"source_sku\":\"LSS29BLACK\"," |
||||
+ "\"warehouse_id\":\"84047962479824\",\"warehouse_code\":\"NJ-2605\"," |
||||
+ "\"country\":\"US\",\"province\":\"GA\",\"city\":\"STONE MOUNTAIN\"," |
||||
+ "\"address\":\"5039 LELAND DR\",\"address2\":\"\",\"postcode\":\"30083-6026\"," |
||||
+ "\"receive_user\":\"DARA\",\"phone\":\"+1 480-618-5344\",\"email\":\"\"," |
||||
+ "\"logistics_type\":\"FEDEX-G\",\"is_sign\":\"0\",\"zone\":\"5\"," |
||||
+ "\"total_amount\":\"0\",\"repair_amount\":\"0\"," |
||||
+ "\"approve_time\":\"2026-10-16 16:20:46\",\"delivered_time\":\"\"," |
||||
+ "\"shop_name\":\"BZY01-shop\",\"gmt_create\":\"2026-10-16 10:18:00\"," |
||||
+ "\"gmt_modify\":\"2026-10-16 10:18:00\",\"gmt_cancel\":\"\",\"intercept_time\":\"\"" |
||||
+ "}"; |
||||
|
||||
private static final String OK_BODY = "{\"rst\":" + DETAIL |
||||
+ ",\"errno\":0,\"err\":\"\",\"trace_id\":\"t-1\"}"; |
||||
|
||||
private RecordingTransport transport; |
||||
private XincangAdapter adapter; |
||||
|
||||
@BeforeEach |
||||
void setUp() { |
||||
transport = RecordingTransport.create(); |
||||
MutableClock clock = MutableClock.atUtc("2026-11-10T00:00:00Z"); |
||||
transport.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||
"{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-1}\",\"token_expire_time\":\"" |
||||
+ java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), |
||||
XincangConstants.SYSTEM_ZONE) |
||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) |
||||
+ "\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-login\"}")); |
||||
adapter = new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), |
||||
new InMemoryTokenStore(), new InMemoryLockProvider(), clock); |
||||
} |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("XC-NJ-2605", WarehouseProvider.XINCANG, "NJ-2605", |
||||
WarehouseConnection.of(BASE, ChannelSecret.builder() |
||||
.appKey(APP_KEY).appSecret("sk").build()), |
||||
"req-1", Clock.systemUTC()); |
||||
} |
||||
|
||||
@Test |
||||
void getByProviderOrderIdMapsDetail() { |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok(OK_BODY)); |
||||
|
||||
OutboundOrder order = adapter.get(ctx(), OutboundRef.ofProviderOrderId("DS-BZY01-26101600001")); |
||||
|
||||
// 请求:GET + query token + order_no
|
||||
common.ecommerce.http.HttpRequest req = transport.lastDataRequest(); |
||||
assertEquals("GET", req.method()); |
||||
assertTrue(req.url().contains("/api.get_order?"), req.url()); |
||||
assertTrue(req.url().contains("order_no=DS-BZY01-26101600001"), req.url()); |
||||
assertTrue(req.url().contains("token=%7BT-1%7D"), req.url()); |
||||
assertFalse(req.url().contains("ckh="), "给了 order_no 就不该再传 ckh"); |
||||
|
||||
// 映射
|
||||
assertEquals("NJ-2605", order.warehouseCode()); |
||||
assertEquals("DS-BZY01-26101600001", order.outboundRequestNo()); |
||||
assertEquals("DS-BZY01-26101600001", order.providerOrderId()); |
||||
assertEquals("Ref26101601", order.orderRef()); |
||||
assertEquals(OutboundStatus.PENDING_REVIEW, order.status()); |
||||
assertEquals("0", order.rawStatus()); |
||||
assertEquals(LabelMode.WAREHOUSE_LABEL, order.labelMode()); |
||||
assertEquals("FEDEX-G", order.carrierCode()); |
||||
assertEquals("验证订单操作失败", order.exceptionCode()); |
||||
assertEquals(WarehouseProvider.XINCANG, order.sourceProvider()); |
||||
// 北京时间 2026-10-16 10:18:00 → UTC 02:18:00
|
||||
assertEquals(Instant.parse("2026-10-16T02:18:00Z"), order.requestedAt()); |
||||
assertNull(order.shippedAt(), "空串的发货时间应为 null"); |
||||
|
||||
assertEquals(1, order.lines().size()); |
||||
assertEquals("LSS29BLACK", order.lines().get(0).omsSku()); |
||||
assertEquals(1, order.lines().get(0).quantity()); |
||||
assertEquals("餐椅", order.lines().get(0).declareName()); |
||||
|
||||
assertEquals("US", order.shipTo().countryCode()); |
||||
assertEquals("GA", order.shipTo().stateOrProvince()); |
||||
assertEquals("DARA", order.shipTo().name()); |
||||
assertNull(order.shipTo().addressLine2(), "空串地址2 应为 null"); |
||||
} |
||||
|
||||
@Test |
||||
void getFallsBackToReferenceNumber() { |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok(OK_BODY)); |
||||
|
||||
adapter.get(ctx(), OutboundRef.ofRequestNo("Ref26101601")); |
||||
|
||||
String url = transport.lastDataRequest().url(); |
||||
assertTrue(url.contains("ckh=Ref26101601"), url); |
||||
assertFalse(url.contains("order_no="), "没有仓单号时只传 ckh"); |
||||
} |
||||
|
||||
@Test |
||||
void wayfairOrderMapsToPlatformLabel() { |
||||
String wayfair = OK_BODY.replace("\"order_type\":\"common\"", "\"order_type\":\"wayfair\""); |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok(wayfair)); |
||||
|
||||
OutboundOrder order = adapter.get(ctx(), OutboundRef.ofProviderOrderId("DS-1")); |
||||
|
||||
assertEquals(LabelMode.PLATFORM_LABEL, order.labelMode()); |
||||
} |
||||
|
||||
@Test |
||||
void fallsBackToSingleSkuWhenProductsMissing() { |
||||
String single = OK_BODY.replace( |
||||
"\"products\":[{\"product_id\":\"1\",\"sku\":\"LSS29BLACK\",\"qty\":\"1\",\"name_zh_cn\":\"餐椅\"}]", |
||||
"\"products\":[]").replace("\"sku_count\":\"1\"", "\"sku_count\":\"3\""); |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok(single)); |
||||
|
||||
OutboundOrder order = adapter.get(ctx(), OutboundRef.ofProviderOrderId("DS-1")); |
||||
|
||||
assertEquals(1, order.lines().size()); |
||||
assertEquals("LSS29BLACK", order.lines().get(0).omsSku()); |
||||
assertEquals(3, order.lines().get(0).quantity()); |
||||
} |
||||
|
||||
@Test |
||||
void unknownStateIsNotGuessed() { |
||||
String unknown = OK_BODY.replace("\"state\":\"0\"", "\"state\":\"99\""); |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok(unknown)); |
||||
|
||||
OutboundOrder order = adapter.get(ctx(), OutboundRef.ofProviderOrderId("DS-1")); |
||||
|
||||
assertEquals(OutboundStatus.UNKNOWN, order.status()); |
||||
assertEquals("99", order.rawStatus()); |
||||
} |
||||
|
||||
@Test |
||||
void businessErrorPropagates() { |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":-1,\"err\":\"订单不存在\",\"trace_id\":\"t-err\"}")); |
||||
|
||||
PlatformBusinessException e = assertThrows(PlatformBusinessException.class, |
||||
() -> adapter.get(ctx(), OutboundRef.ofProviderOrderId("DS-NONE"))); |
||||
assertTrue(e.getMessage().contains("订单不存在"), e.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void emptyRstIsNotSilentNull() { |
||||
transport.route(XincangConstants.PATH_ORDER_DETAIL, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":0,\"err\":\"\",\"trace_id\":\"t-empty\"}")); |
||||
|
||||
common.ecommerce.shared.error.ValidationException e = |
||||
assertThrows(common.ecommerce.shared.error.ValidationException.class, |
||||
() -> adapter.get(ctx(), OutboundRef.ofProviderOrderId("DS-1"))); |
||||
assertTrue(e.getMessage().contains("no rst"), e.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void timeParsingIsBeijingToUtc() { |
||||
assertEquals(Instant.parse("2026-10-16T02:18:00Z"), |
||||
XincangOrderDetailMapper.parseTime("2026-10-16 10:18:00")); |
||||
assertNull(XincangOrderDetailMapper.parseTime("")); |
||||
assertNull(XincangOrderDetailMapper.parseTime("not-a-time")); |
||||
assertEquals(Instant.parse("2026-10-15T16:00:00Z"), |
||||
XincangOrderDetailMapper.parseDate("2026-10-16")); |
||||
} |
||||
} |
||||
@ -0,0 +1,178 @@
@@ -0,0 +1,178 @@
|
||||
package common.ecommerce.xincang.adapter; |
||||
|
||||
import common.ecommerce.shared.error.PlatformBusinessException; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||
import common.ecommerce.shared.testkit.MutableClock; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.enums.TransferStatus; |
||||
import common.ecommerce.warehouse.enums.TransferType; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.TransferOrder; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.xincang.XincangConstants; |
||||
import org.junit.jupiter.api.BeforeEach; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Duration; |
||||
import java.time.Instant; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.*; |
||||
|
||||
/** |
||||
* 转运详情({@code GET fba.fba_detail})契约测试。 |
||||
*/ |
||||
class XincangTransferDetailTest { |
||||
|
||||
private static final String BASE = XincangConstants.TEST_BASE_URL; |
||||
private static final String APP_KEY = "ak-1"; |
||||
|
||||
/** 文档「成功示例」原文(截取与映射相关的字段)。 */ |
||||
private static final String DETAIL = "{" |
||||
+ "\"id\":\"128064084674485505\"," |
||||
+ "\"order_no\":\"LTL2610200000271\"," |
||||
+ "\"fba_no\":\"ZYDD20261020001\"," |
||||
+ "\"po\":\"ZYDD20261020001\"," |
||||
+ "\"from_warehouse\":\"84047962307416\"," |
||||
+ "\"from_warehouse_name\":\"CA-15950\"," |
||||
+ "\"dest_warehouse\":\"0\"," |
||||
+ "\"dest_warehouse_name\":\"123\"," |
||||
+ "\"pre_send_time\":\"2026-10-21\"," |
||||
+ "\"state\":\"6\"," |
||||
+ "\"state_name\":\"已发货\"," |
||||
+ "\"remark\":\"\"," |
||||
+ "\"is_pallet\":\"1\"," |
||||
+ "\"delivery_mode\":\"LTL\"," |
||||
+ "\"delivery_way\":\"卡车\"," |
||||
+ "\"label_requirement\":\"产品贴,外箱标签,托盘标签\"," |
||||
+ "\"total_amount\":\"84.25\"," |
||||
+ "\"products\":[" |
||||
+ "{\"product_no\":\"BOOK\",\"sku_count\":\"10\",\"box_count\":\"5\",\"packing_rate\":\"2\"}," |
||||
+ "{\"product_no\":\"FHCP006\",\"sku_count\":\"10\",\"box_count\":\"5\",\"packing_rate\":\"2\"}" |
||||
+ "]" |
||||
+ "}"; |
||||
|
||||
private static final String OK_BODY = "{\"rst\":" + DETAIL |
||||
+ ",\"errno\":0,\"err\":\"\",\"trace_id\":\"t-1\"}"; |
||||
|
||||
private RecordingTransport transport; |
||||
private XincangAdapter adapter; |
||||
|
||||
@BeforeEach |
||||
void setUp() { |
||||
transport = RecordingTransport.create(); |
||||
MutableClock clock = MutableClock.atUtc("2026-11-10T00:00:00Z"); |
||||
transport.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||
"{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-1}\",\"token_expire_time\":\"" |
||||
+ java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), |
||||
XincangConstants.SYSTEM_ZONE) |
||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) |
||||
+ "\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-login\"}")); |
||||
adapter = new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), |
||||
new InMemoryTokenStore(), new InMemoryLockProvider(), clock); |
||||
} |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("XC-CA-15950", WarehouseProvider.XINCANG, "CA-15950", |
||||
WarehouseConnection.of(BASE, ChannelSecret.builder() |
||||
.appKey(APP_KEY).appSecret("sk").build()), |
||||
"req-1", Clock.systemUTC()); |
||||
} |
||||
|
||||
@Test |
||||
void getMapsTransferDetail() { |
||||
transport.route(XincangConstants.PATH_TRANSFER_DETAIL, req -> Responses.ok(OK_BODY)); |
||||
|
||||
TransferOrder order = adapter.getTransfer(ctx(), "LTL2610200000271"); |
||||
|
||||
// 请求
|
||||
common.ecommerce.http.HttpRequest req = transport.lastDataRequest(); |
||||
assertEquals("GET", req.method()); |
||||
assertTrue(req.url().contains("/fba.fba_detail?"), req.url()); |
||||
assertTrue(req.url().contains("order_no=LTL2610200000271"), req.url()); |
||||
assertTrue(req.url().contains("token=%7BT-1%7D"), req.url()); |
||||
|
||||
// 双号:fba_no 是业务单号,order_no 是仓单号
|
||||
assertEquals("ZYDD20261020001", order.transferRequestNo()); |
||||
assertEquals("LTL2610200000271", order.providerTransferNo()); |
||||
assertEquals("CA-15950", order.fromWarehouseCode()); |
||||
assertEquals("123", order.toWarehouseCode()); |
||||
assertEquals(TransferType.OUTBOUND, order.type()); |
||||
assertEquals(TransferStatus.SHIPPED, order.status()); |
||||
assertEquals("6", order.rawStatus()); |
||||
assertEquals(WarehouseProvider.XINCANG, order.sourceProvider()); |
||||
assertEquals(20, order.totalQuantity(), "10 + 10"); |
||||
// pre_send_time 2026-10-21 北京时间 0 点 → UTC 前一天 16:00
|
||||
assertEquals(Instant.parse("2026-10-20T16:00:00Z"), order.estimatedOutboundAt()); |
||||
assertNull(order.remark(), "空串备注应为 null"); |
||||
} |
||||
|
||||
@Test |
||||
void unknownTransferStateIsNotGuessed() { |
||||
String unknown = OK_BODY.replace("\"state\":\"6\"", "\"state\":\"99\""); |
||||
transport.route(XincangConstants.PATH_TRANSFER_DETAIL, req -> Responses.ok(unknown)); |
||||
|
||||
TransferOrder order = adapter.getTransfer(ctx(), "LTL-1"); |
||||
|
||||
assertEquals(TransferStatus.UNKNOWN, order.status()); |
||||
assertEquals("99", order.rawStatus()); |
||||
} |
||||
|
||||
@Test |
||||
void outputStateMapsToShipped() { |
||||
// 信仓 state=6「已发货」→ core SHIPPED,不是 COMPLETED
|
||||
transport.route(XincangConstants.PATH_TRANSFER_DETAIL, req -> Responses.ok(OK_BODY)); |
||||
|
||||
TransferOrder order = adapter.getTransfer(ctx(), "LTL-1"); |
||||
|
||||
assertEquals(TransferStatus.SHIPPED, order.status()); |
||||
assertFalse(order.completed(), "已发货不等于已完成"); |
||||
} |
||||
|
||||
@Test |
||||
void missingProductsMeansUnknownQuantity() { |
||||
String noProducts = OK_BODY.replace( |
||||
",\"products\":[" |
||||
+ "{\"product_no\":\"BOOK\",\"sku_count\":\"10\",\"box_count\":\"5\",\"packing_rate\":\"2\"}," |
||||
+ "{\"product_no\":\"FHCP006\",\"sku_count\":\"10\",\"box_count\":\"5\",\"packing_rate\":\"2\"}" |
||||
+ "]", ""); |
||||
transport.route(XincangConstants.PATH_TRANSFER_DETAIL, req -> Responses.ok(noProducts)); |
||||
|
||||
assertEquals(0, adapter.getTransfer(ctx(), "LTL-1").totalQuantity()); |
||||
} |
||||
|
||||
@Test |
||||
void blankOrderNoIsRejectedBeforeSending() { |
||||
common.ecommerce.shared.error.ValidationException e = |
||||
assertThrows(common.ecommerce.shared.error.ValidationException.class, |
||||
() -> adapter.getTransfer(ctx(), " ")); |
||||
assertTrue(e.getMessage().contains("providerTransferNo"), e.getMessage()); |
||||
assertFalse(transport.recorded().stream() |
||||
.anyMatch(r -> r.url().contains(XincangConstants.PATH_TRANSFER_DETAIL))); |
||||
} |
||||
|
||||
@Test |
||||
void businessErrorPropagates() { |
||||
transport.route(XincangConstants.PATH_TRANSFER_DETAIL, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":-1,\"err\":\"转运单不存在\",\"trace_id\":\"t-err\"}")); |
||||
|
||||
PlatformBusinessException e = assertThrows(PlatformBusinessException.class, |
||||
() -> adapter.getTransfer(ctx(), "LTL-NONE")); |
||||
assertTrue(e.getMessage().contains("转运单不存在"), e.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void emptyRstIsNotSilentNull() { |
||||
transport.route(XincangConstants.PATH_TRANSFER_DETAIL, req -> Responses.ok( |
||||
"{\"rst\":null,\"errno\":0,\"err\":\"\",\"trace_id\":\"t-empty\"}")); |
||||
|
||||
common.ecommerce.shared.error.ValidationException e = |
||||
assertThrows(common.ecommerce.shared.error.ValidationException.class, |
||||
() -> adapter.getTransfer(ctx(), "LTL-1")); |
||||
assertTrue(e.getMessage().contains("no rst"), e.getMessage()); |
||||
} |
||||
} |
||||
@ -0,0 +1,80 @@
@@ -0,0 +1,80 @@
|
||||
package common.ecommerce.xincang.enums; |
||||
|
||||
import common.ecommerce.warehouse.enums.InboundStatus; |
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
import common.ecommerce.warehouse.enums.TransferStatus; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.*; |
||||
|
||||
/** |
||||
* 信仓平台枚举 → core 底层枚举的映射。 |
||||
* |
||||
* <p>码表来自 Apifox「OMS接口文档V2」,1:1 对应;认不出的值一律归 UNKNOWN,不猜。</p> |
||||
*/ |
||||
class XincangEnumsTest { |
||||
|
||||
@Test |
||||
void orderStatusMapsEveryDocumentedCode() { |
||||
assertEquals(OutboundStatus.PENDING_REVIEW, XincangOrderStatus.toCore("0")); |
||||
assertEquals(OutboundStatus.PENDING_SHIPMENT, XincangOrderStatus.toCore("1")); |
||||
assertEquals(OutboundStatus.PICKING, XincangOrderStatus.toCore("2")); |
||||
assertEquals(OutboundStatus.PICKED, XincangOrderStatus.toCore("3")); |
||||
assertEquals(OutboundStatus.LABEL_READY, XincangOrderStatus.toCore("4")); |
||||
assertEquals(OutboundStatus.SHIPPED, XincangOrderStatus.toCore("5")); |
||||
assertEquals(OutboundStatus.INTERCEPTED, XincangOrderStatus.toCore("6")); |
||||
assertEquals(OutboundStatus.OUT_OF_STOCK, XincangOrderStatus.toCore("7")); |
||||
assertEquals(OutboundStatus.CANCELLED, XincangOrderStatus.toCore("8")); |
||||
assertEquals(OutboundStatus.DELETED, XincangOrderStatus.toCore("10")); |
||||
assertEquals(OutboundStatus.REVIEWING, XincangOrderStatus.toCore("11")); |
||||
assertEquals(OutboundStatus.REVIEW_FAILED, XincangOrderStatus.toCore("12")); |
||||
} |
||||
|
||||
@Test |
||||
void unknownOrderStatusIsNotGuessed() { |
||||
assertEquals(OutboundStatus.UNKNOWN, XincangOrderStatus.toCore("99")); |
||||
assertEquals(OutboundStatus.UNKNOWN, XincangOrderStatus.toCore("")); |
||||
assertEquals(OutboundStatus.UNKNOWN, XincangOrderStatus.toCore(null)); |
||||
} |
||||
|
||||
@Test |
||||
void transferStateMapsEveryDocumentedCode() { |
||||
assertEquals(TransferStatus.PENDING_REVIEW, XincangTransferState.toCore("0")); |
||||
assertEquals(TransferStatus.PENDING_PROCESSING, XincangTransferState.toCore("1")); |
||||
assertEquals(TransferStatus.PENDING_PICK, XincangTransferState.toCore("2")); |
||||
assertEquals(TransferStatus.PENDING_LABELING, XincangTransferState.toCore("3")); |
||||
assertEquals(TransferStatus.PENDING_PALLETIZING, XincangTransferState.toCore("4")); |
||||
assertEquals(TransferStatus.PENDING_OUTBOUND, XincangTransferState.toCore("5")); |
||||
assertEquals(TransferStatus.SHIPPED, XincangTransferState.toCore("6")); |
||||
assertEquals(TransferStatus.CANCELLED, XincangTransferState.toCore("7")); |
||||
} |
||||
|
||||
@Test |
||||
void unknownTransferStateIsNotGuessed() { |
||||
assertEquals(TransferStatus.UNKNOWN, XincangTransferState.toCore("9")); |
||||
assertEquals(TransferStatus.UNKNOWN, XincangTransferState.toCore(null)); |
||||
} |
||||
|
||||
@Test |
||||
void forecastStatusMapsToInboundStatus() { |
||||
assertEquals(InboundStatus.DRAFT, XincangForecastStatus.toCore("0")); |
||||
assertEquals(InboundStatus.IN_TRANSIT, XincangForecastStatus.toCore("1")); |
||||
assertEquals(InboundStatus.PENDING_SHIPMENT, XincangForecastStatus.toCore("2")); |
||||
assertEquals(InboundStatus.IN_TRANSIT, XincangForecastStatus.toCore("3")); |
||||
assertEquals(InboundStatus.RECEIVING, XincangForecastStatus.toCore("6")); |
||||
assertEquals(InboundStatus.STORING, XincangForecastStatus.toCore("7")); |
||||
assertEquals(InboundStatus.COMPLETED, XincangForecastStatus.toCore("8")); |
||||
assertEquals(InboundStatus.REJECTED, XincangForecastStatus.toCore("9")); |
||||
assertEquals(InboundStatus.UNKNOWN, XincangForecastStatus.toCore("99")); |
||||
} |
||||
|
||||
@Test |
||||
void orderTypeDrivesSelfLabelRequirement() { |
||||
assertEquals("common", XincangOrderType.COMMON.rawCode()); |
||||
assertEquals("wayfair", XincangOrderType.WAYFAIR.rawCode()); |
||||
assertFalse(XincangOrderType.COMMON.requiresSelfLabel()); |
||||
assertTrue(XincangOrderType.WAYFAIR.requiresSelfLabel()); |
||||
assertEquals(XincangOrderType.WAYFAIR, XincangOrderType.of("wayfair")); |
||||
assertNull(XincangOrderType.of("unknown")); |
||||
} |
||||
} |
||||
Loading…
Reference in new issue