Browse Source
通道 ChannelProvider.DIRECT + Platform.WALMART_SC,新增模块 channel-sdk-walmart。
一期只做只读:鉴权、订单、商品、售后。标发、退款、商品写入不在本期,
对应能力位也不声明——门面调用会显式抛 UnsupportedCapabilityException。
【core 模型增量】全部是可选字段,不影响领星现有行为:
- 新增 ShipToAddress(收件信息;toString 只输出城市/州/邮编,不输出街道与姓名)
- SalesOrder 增加 buyerEmail / shipToAddress
- OrderLine 增加 status(行状态原值)与 lineAmount(行金额,金额权威来源)
- OrderLine.unitPrice 明确为「单价」:行金额除以数量,除不尽时留 null
而不是四舍五入倒推,否则 unitPrice × quantity 与原金额会差出分差
【适配器】
- POST /v3/token(Basic Auth + client_credentials),按 clientId 缓存,
提前 120s 续期;401/403 时 forceRefresh 后重发一次
- GET /v3/orders、/v3/orders/{id}:updatedAfter/Before 映射到创建时间窗
(沃尔玛没有更新时间过滤),跨度超 180 天本地拒绝
- GET /v3/items、/v3/items/{sku}:limit 上限 200;syncStrategy=FULL_PULL_DIFF,
传更新时间窗直接报错而不是静默忽略
- GET /v3/returns:一个退货单按商品行展开成多个 AfterSale,
nextCursor 是整段查询串,翻页时整串拼到路径后
- 扩展查询:getReturn(退货详情)、getShipping(发货信息),沙箱均 404
增量语义拆成两条车道:pull 走创建时间窗语义可预测,老单状态变化由
pullOpenOrders 按行状态对账,不混在一个方法里。
脏数据处理:缺订单号/下单时间/退货单号的记录跳过并 WARN,不崩整页,
也不用假值兜底写脏主键。运费不冒充商品单价,行金额除不尽时 unitPrice 留 null。
【测试】108 个:订单 22、商品 18、售后 13、脏数据 10、扩展查询 12、
状态映射 16、错误 11、门面 5、沙箱探针 1(默认跳过)。
【文档】仅新增 docs/walmart/README.md,以及 README / 操作手册.md 里
沃尔玛相关的两处能力表条目。
Co-Authored-By: Claude Code <noreply@anthropic.com>
46 changed files with 6976 additions and 10 deletions
@ -0,0 +1,231 @@ |
|||||||
|
package common.ecommerce.channel.model.order; |
||||||
|
|
||||||
|
import java.util.Objects; |
||||||
|
|
||||||
|
/** |
||||||
|
* 订单收货地址。 |
||||||
|
* |
||||||
|
* <p>各平台字段名不同、语义一致:沃尔玛 {@code shippingInfo.postalAddress}、 |
||||||
|
* 亚马逊 {@code ShippingAddress}、领星 {@code address_*}。统一收在这里, |
||||||
|
* 平台原始值不再重复存放于 {@code SalesOrder}。</p> |
||||||
|
* |
||||||
|
* <p>本类只承载<b>收件信息</b>,不含发货仓、物流方式等履约配置; |
||||||
|
* 那些属于出库/面单域,由 {@code OutboundOrder} 等模型表达。</p> |
||||||
|
* |
||||||
|
* <p><b>地址类型不做成枚举</b>:沃尔玛给 {@code RESIDENTIAL} / {@code OFFICE}, |
||||||
|
* 其它平台可能给别的值,做成枚举后平台加值就会编译不过。原值放在 |
||||||
|
* {@link #addressType()},由宿主自行解释。</p> |
||||||
|
*/ |
||||||
|
public final class ShipToAddress { |
||||||
|
|
||||||
|
/** 收件人姓名;平台不提供时为 null。 */ |
||||||
|
private final String name; |
||||||
|
|
||||||
|
/** 地址行 1(街道、门牌号);平台不提供时为 null。 */ |
||||||
|
private final String address1; |
||||||
|
|
||||||
|
/** 地址行 2(单元、楼层等);多数订单为 null。 */ |
||||||
|
private final String address2; |
||||||
|
|
||||||
|
/** 城市;平台不提供时为 null。 */ |
||||||
|
private final String city; |
||||||
|
|
||||||
|
/** 州 / 省;平台原始编码(如沃尔玛的 {@code CO}),不做大小写归一。 */ |
||||||
|
private final String state; |
||||||
|
|
||||||
|
/** 邮编;保留平台原值,不补零、不去零。 */ |
||||||
|
private final String postalCode; |
||||||
|
|
||||||
|
/** 国家代码;ISO 3166-1 alpha-2({@code US})或平台原值(沃尔玛给 {@code USA}),可空。 */ |
||||||
|
private final String countryCode; |
||||||
|
|
||||||
|
/** 地址类型原值,如 {@code RESIDENTIAL} / {@code OFFICE};平台不给时为 null。 */ |
||||||
|
private final String addressType; |
||||||
|
|
||||||
|
/** 收件人电话;平台以中转号或虚拟号给出时保留原值。 */ |
||||||
|
private final String phone; |
||||||
|
|
||||||
|
private ShipToAddress(Builder b) { |
||||||
|
this.name = b.name; |
||||||
|
this.address1 = b.address1; |
||||||
|
this.address2 = b.address2; |
||||||
|
this.city = b.city; |
||||||
|
this.state = b.state; |
||||||
|
this.postalCode = b.postalCode; |
||||||
|
this.countryCode = b.countryCode; |
||||||
|
this.addressType = b.addressType; |
||||||
|
this.phone = b.phone; |
||||||
|
} |
||||||
|
|
||||||
|
/** 创建构建器。 */ |
||||||
|
public static Builder builder() { |
||||||
|
return new Builder(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 收件人姓名。 */ |
||||||
|
public String name() { |
||||||
|
return name; |
||||||
|
} |
||||||
|
|
||||||
|
/** 地址行 1。 */ |
||||||
|
public String address1() { |
||||||
|
return address1; |
||||||
|
} |
||||||
|
|
||||||
|
/** 地址行 2。 */ |
||||||
|
public String address2() { |
||||||
|
return address2; |
||||||
|
} |
||||||
|
|
||||||
|
/** 城市。 */ |
||||||
|
public String city() { |
||||||
|
return city; |
||||||
|
} |
||||||
|
|
||||||
|
/** 州 / 省。 */ |
||||||
|
public String state() { |
||||||
|
return state; |
||||||
|
} |
||||||
|
|
||||||
|
/** 邮编。 */ |
||||||
|
public String postalCode() { |
||||||
|
return postalCode; |
||||||
|
} |
||||||
|
|
||||||
|
/** 国家代码原值。 */ |
||||||
|
public String countryCode() { |
||||||
|
return countryCode; |
||||||
|
} |
||||||
|
|
||||||
|
/** 地址类型原值。 */ |
||||||
|
public String addressType() { |
||||||
|
return addressType; |
||||||
|
} |
||||||
|
|
||||||
|
/** 收件人电话。 */ |
||||||
|
public String phone() { |
||||||
|
return phone; |
||||||
|
} |
||||||
|
|
||||||
|
/** 地址是否为空(全字段为 null);适配器可据此决定要不要挂到订单上。 */ |
||||||
|
public boolean isEmpty() { |
||||||
|
return name == null && address1 == null && address2 == null && city == null |
||||||
|
&& state == null && postalCode == null && countryCode == null |
||||||
|
&& addressType == null && phone == null; |
||||||
|
} |
||||||
|
|
||||||
|
/** 各字段都相同才相等。 */ |
||||||
|
@Override |
||||||
|
public boolean equals(Object o) { |
||||||
|
if (this == o) { |
||||||
|
return true; |
||||||
|
} |
||||||
|
if (!(o instanceof ShipToAddress)) { |
||||||
|
return false; |
||||||
|
} |
||||||
|
ShipToAddress that = (ShipToAddress) o; |
||||||
|
return Objects.equals(name, that.name) |
||||||
|
&& Objects.equals(address1, that.address1) |
||||||
|
&& Objects.equals(address2, that.address2) |
||||||
|
&& Objects.equals(city, that.city) |
||||||
|
&& Objects.equals(state, that.state) |
||||||
|
&& Objects.equals(postalCode, that.postalCode) |
||||||
|
&& Objects.equals(countryCode, that.countryCode) |
||||||
|
&& Objects.equals(addressType, that.addressType) |
||||||
|
&& Objects.equals(phone, that.phone); |
||||||
|
} |
||||||
|
|
||||||
|
/** 与 {@link #equals(Object)} 一致。 */ |
||||||
|
@Override |
||||||
|
public int hashCode() { |
||||||
|
return Objects.hash(name, address1, address2, city, state, postalCode, countryCode, addressType, phone); |
||||||
|
} |
||||||
|
|
||||||
|
/** 调试输出;地址属于个人信息,这里只输出城市与州,不输出街道与收件人。 */ |
||||||
|
@Override |
||||||
|
public String toString() { |
||||||
|
return "ShipToAddress{" + city + ", " + state + " " + postalCode + " " + countryCode + '}'; |
||||||
|
} |
||||||
|
|
||||||
|
/** 收货地址构建器;所有字段可选。 */ |
||||||
|
public static final class Builder { |
||||||
|
|
||||||
|
/** 收件人姓名。 */ |
||||||
|
private String name; |
||||||
|
/** 地址行 1。 */ |
||||||
|
private String address1; |
||||||
|
/** 地址行 2。 */ |
||||||
|
private String address2; |
||||||
|
/** 城市。 */ |
||||||
|
private String city; |
||||||
|
/** 州 / 省。 */ |
||||||
|
private String state; |
||||||
|
/** 邮编。 */ |
||||||
|
private String postalCode; |
||||||
|
/** 国家代码原值。 */ |
||||||
|
private String countryCode; |
||||||
|
/** 地址类型原值。 */ |
||||||
|
private String addressType; |
||||||
|
/** 收件人电话。 */ |
||||||
|
private String phone; |
||||||
|
|
||||||
|
/** 设置收件人姓名。 */ |
||||||
|
public Builder name(String name) { |
||||||
|
this.name = name; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置地址行 1。 */ |
||||||
|
public Builder address1(String address1) { |
||||||
|
this.address1 = address1; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置地址行 2。 */ |
||||||
|
public Builder address2(String address2) { |
||||||
|
this.address2 = address2; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置城市。 */ |
||||||
|
public Builder city(String city) { |
||||||
|
this.city = city; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置州 / 省。 */ |
||||||
|
public Builder state(String state) { |
||||||
|
this.state = state; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置邮编。 */ |
||||||
|
public Builder postalCode(String postalCode) { |
||||||
|
this.postalCode = postalCode; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置国家代码原值。 */ |
||||||
|
public Builder countryCode(String countryCode) { |
||||||
|
this.countryCode = countryCode; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置地址类型原值。 */ |
||||||
|
public Builder addressType(String addressType) { |
||||||
|
this.addressType = addressType; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 设置收件人电话。 */ |
||||||
|
public Builder phone(String phone) { |
||||||
|
this.phone = phone; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
/** 构建地址对象;不做必填校验,缺字段就是 null。 */ |
||||||
|
public ShipToAddress build() { |
||||||
|
return new ShipToAddress(this); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,113 @@ |
|||||||
|
package common.ecommerce.channel.model.order; |
||||||
|
|
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.support.Money; |
||||||
|
import common.ecommerce.shared.support.PlatformTime; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 订单模型的增量字段必须全是可选的:老适配器(领星)不传时行为不能变。 |
||||||
|
*/ |
||||||
|
class SalesOrderOptionalFieldsTest { |
||||||
|
|
||||||
|
private static SalesOrder minimalOrder() { |
||||||
|
return SalesOrder.builder() |
||||||
|
.omsStoreId("oms-wm-001") |
||||||
|
.channelOrderId("PO-1") |
||||||
|
.occurredAt(PlatformTime.of(Instant.parse("2026-11-18T00:00:00Z"), "America/Chicago")) |
||||||
|
.sourceProvider(ChannelProvider.LINGXING) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void addressAndEmailDefaultToNull() { |
||||||
|
SalesOrder order = minimalOrder(); |
||||||
|
assertNull(order.buyerEmail()); |
||||||
|
assertNull(order.shipToAddress()); |
||||||
|
assertNull(order.buyerName()); |
||||||
|
assertNull(order.shipToCountryCode()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void lineStatusDefaultsToNull() { |
||||||
|
OrderLine line = OrderLine.builder().platformSku("SKU-1").quantity(1).build(); |
||||||
|
assertNull(line.status()); |
||||||
|
assertNull(line.lineId()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void walmartStyleOrderKeepsAllNewFields() { |
||||||
|
SalesOrder order = SalesOrder.builder() |
||||||
|
.omsStoreId("oms-wm-001") |
||||||
|
.channelOrderId("108816631915371") |
||||||
|
.status("Created") |
||||||
|
.buyerName("Astro Test") |
||||||
|
.buyerEmail("buyer@relay.walmart.com") |
||||||
|
.shipToCountryCode("USA") |
||||||
|
.shipToAddress(ShipToAddress.builder() |
||||||
|
.name("Astro Test") |
||||||
|
.address1("5809 W 44th Ave") |
||||||
|
.city("Lakeside") |
||||||
|
.state("CO") |
||||||
|
.postalCode("80212") |
||||||
|
.countryCode("USA") |
||||||
|
.addressType("OFFICE") |
||||||
|
.phone("555-0100") |
||||||
|
.build()) |
||||||
|
.lines(java.util.Collections.singletonList(OrderLine.builder() |
||||||
|
.lineId("1") |
||||||
|
.platformSku("SKU-1") |
||||||
|
.quantity(1) |
||||||
|
.unitPrice(Money.of("499.99", "USD")) |
||||||
|
.status("Created") |
||||||
|
.build())) |
||||||
|
.occurredAt(PlatformTime.of(Instant.ofEpochMilli(1686736267000L), "America/Chicago")) |
||||||
|
.sourceProvider(ChannelProvider.DIRECT) |
||||||
|
.build(); |
||||||
|
|
||||||
|
assertEquals("buyer@relay.walmart.com", order.buyerEmail()); |
||||||
|
assertEquals("Lakeside", order.shipToAddress().city()); |
||||||
|
assertEquals("Created", order.lines().get(0).status()); |
||||||
|
assertEquals("499.99", order.lines().get(0).unitPrice().amount().toPlainString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void addressIsEmptyOnlyWhenEveryFieldIsNull() { |
||||||
|
assertTrue(ShipToAddress.builder().build().isEmpty()); |
||||||
|
assertFalse(ShipToAddress.builder().city("Lakeside").build().isEmpty()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void addressEqualityCoversEveryField() { |
||||||
|
ShipToAddress a = ShipToAddress.builder().address1("1 Main St").city("Dallas").build(); |
||||||
|
ShipToAddress b = ShipToAddress.builder().address1("1 Main St").city("Dallas").build(); |
||||||
|
ShipToAddress c = ShipToAddress.builder().address1("1 Main St").city("Austin").build(); |
||||||
|
|
||||||
|
assertEquals(a, b); |
||||||
|
assertEquals(a.hashCode(), b.hashCode()); |
||||||
|
assertFalse(a.equals(c)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void addressToStringHidesPersonalFields() { |
||||||
|
ShipToAddress address = ShipToAddress.builder() |
||||||
|
.name("Jane Doe") |
||||||
|
.address1("1 Main St") |
||||||
|
.city("Dallas") |
||||||
|
.state("TX") |
||||||
|
.postalCode("75201") |
||||||
|
.countryCode("USA") |
||||||
|
.build(); |
||||||
|
String text = address.toString(); |
||||||
|
assertFalse(text.contains("Jane Doe"), text); |
||||||
|
assertFalse(text.contains("1 Main St"), text); |
||||||
|
assertTrue(text.contains("Dallas"), text); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,49 @@ |
|||||||
|
<?xml version="1.0" encoding="UTF-8"?> |
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" |
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
||||||
|
<modelVersion>4.0.0</modelVersion> |
||||||
|
|
||||||
|
<parent> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>channel-sdk-parent</artifactId> |
||||||
|
<version>1.0.0-SNAPSHOT</version> |
||||||
|
</parent> |
||||||
|
|
||||||
|
<artifactId>channel-sdk-walmart</artifactId> |
||||||
|
<description>沃尔玛 Marketplace 直连适配器(订单 / 商品 / 售后)</description> |
||||||
|
|
||||||
|
<dependencies> |
||||||
|
<dependency> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>sdk-common</artifactId> |
||||||
|
</dependency> |
||||||
|
<dependency> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>channel-sdk-core</artifactId> |
||||||
|
</dependency> |
||||||
|
<dependency> |
||||||
|
<groupId>com.fasterxml.jackson.core</groupId> |
||||||
|
<artifactId>jackson-databind</artifactId> |
||||||
|
</dependency> |
||||||
|
<dependency> |
||||||
|
<groupId>com.squareup.okhttp3</groupId> |
||||||
|
<artifactId>okhttp</artifactId> |
||||||
|
</dependency> |
||||||
|
<dependency> |
||||||
|
<groupId>org.slf4j</groupId> |
||||||
|
<artifactId>slf4j-api</artifactId> |
||||||
|
</dependency> |
||||||
|
|
||||||
|
<dependency> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>sdk-testkit</artifactId> |
||||||
|
<scope>test</scope> |
||||||
|
</dependency> |
||||||
|
<dependency> |
||||||
|
<groupId>org.junit.jupiter</groupId> |
||||||
|
<artifactId>junit-jupiter</artifactId> |
||||||
|
<scope>test</scope> |
||||||
|
</dependency> |
||||||
|
</dependencies> |
||||||
|
</project> |
||||||
@ -0,0 +1,115 @@ |
|||||||
|
package common.ecommerce.walmart; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛 Marketplace 协议常量。 |
||||||
|
* |
||||||
|
* <p>端点与路径属于<b>协议的一部分</b>,写在代码里,不做成配置表。 |
||||||
|
* 运行时不使用 {@link #PRODUCTION_BASE_URL} / {@link #SANDBOX_BASE_URL}: |
||||||
|
* 端点由调用方每次经 {@code ChannelConnection} 传入(沙箱还是生产由宿主决定, |
||||||
|
* 账户上的 {@code ChannelAccount.sandbox()} 只是元数据)。</p> |
||||||
|
* |
||||||
|
* <p>来源:《沃尔玛沙箱接口说明》v1.0(2026-11-16),沙箱 |
||||||
|
* {@code https://sandbox.walmartapis.com} 实测。</p>
|
||||||
|
*/ |
||||||
|
public final class WalmartConstants { |
||||||
|
|
||||||
|
/** 适配器标识;注册表与日志用。 */ |
||||||
|
public static final String ADAPTER_ID = "walmart-direct"; |
||||||
|
|
||||||
|
/** 生产端点。 */ |
||||||
|
public static final String PRODUCTION_BASE_URL = "https://marketplace.walmartapis.com"; |
||||||
|
|
||||||
|
/** 沙箱端点。 */ |
||||||
|
public static final String SANDBOX_BASE_URL = "https://sandbox.walmartapis.com"; |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 路径
|
||||||
|
|
||||||
|
/** 换取访问令牌;form-urlencoded + Basic Auth。 */ |
||||||
|
public static final String PATH_TOKEN = "/v3/token"; |
||||||
|
|
||||||
|
/** 商品列表;游标分页。 */ |
||||||
|
public static final String PATH_ITEMS = "/v3/items"; |
||||||
|
|
||||||
|
/** 商品详情;路径参数为 URL 编码后的 SKU。 */ |
||||||
|
public static final String PATH_ITEM_BY_SKU = "/v3/items/"; |
||||||
|
|
||||||
|
/** 订单列表;按创建时间窗 + 游标分页。 */ |
||||||
|
public static final String PATH_ORDERS = "/v3/orders"; |
||||||
|
|
||||||
|
/** 订单详情;路径参数为 purchaseOrderId。响应多包一层 {@code {"order": ...}}。 */ |
||||||
|
public static final String PATH_ORDER_BY_ID = "/v3/orders/"; |
||||||
|
|
||||||
|
/** 退货单列表;{@code meta.nextCursor} 本身是一段查询串,翻页时整串拼到路径后面。 */ |
||||||
|
public static final String PATH_RETURNS = "/v3/returns"; |
||||||
|
|
||||||
|
/** 退货单详情;路径参数为 returnOrderId。⚠ 沙箱实测 404。 */ |
||||||
|
public static final String PATH_RETURN_BY_ID = "/v3/returns/"; |
||||||
|
|
||||||
|
/** 查询发货信息:{@code GET /v3/orders/{purchaseOrderId}/shipping}。⚠ 沙箱实测 404。 */ |
||||||
|
public static final String PATH_ORDER_SHIPPING = "/shipping"; |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 请求头
|
||||||
|
|
||||||
|
/** 服务名,固定值。 */ |
||||||
|
public static final String HEADER_SVC_NAME = "WM_SVC.NAME"; |
||||||
|
|
||||||
|
/** 服务名的固定取值。 */ |
||||||
|
public static final String SVC_NAME_VALUE = "Walmart Marketplace"; |
||||||
|
|
||||||
|
/** 调用链追踪 ID,每次请求生成一个新的;SDK 用 {@code ChannelContext.requestId()}。 */ |
||||||
|
public static final String HEADER_CORRELATION_ID = "WM_QOS.CORRELATION_ID"; |
||||||
|
|
||||||
|
/** 访问令牌;<b>业务接口用它,不用 Authorization</b>。 */ |
||||||
|
public static final String HEADER_ACCESS_TOKEN = "WM_SEC.ACCESS_TOKEN"; |
||||||
|
|
||||||
|
/** 表单类型,仅令牌接口使用。 */ |
||||||
|
public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"; |
||||||
|
|
||||||
|
/** JSON 类型,业务接口使用。 */ |
||||||
|
public static final String CONTENT_TYPE_JSON = "application/json"; |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 限制
|
||||||
|
|
||||||
|
/** |
||||||
|
* 商品列表单页上限(官方值,超了本地截断)。 |
||||||
|
* |
||||||
|
* <p>与领星不同,这里是<b>平台硬上限</b>:静默截断是安全的,因为调用方本来 |
||||||
|
* 就只能拿到这么多,且用 {@code nextCursor} 翻页。</p> |
||||||
|
*/ |
||||||
|
public static final int MAX_ITEM_PAGE_SIZE = 200; |
||||||
|
|
||||||
|
/** 订单列表在沙箱的默认单页条数;未显式指定时用它。 */ |
||||||
|
public static final int DEFAULT_ORDER_PAGE_SIZE = 20; |
||||||
|
|
||||||
|
/** |
||||||
|
* 订单列表单页上限(📖 官方常见取值 200,与商品一致)。 |
||||||
|
* |
||||||
|
* <p>文档没给订单的 {@code limit} 上限;这里与商品保持同一策略:超了本地截断, |
||||||
|
* 而不是把大值原样发给平台(沙箱 mock 不校验,生产会被拒)。</p> |
||||||
|
*/ |
||||||
|
public static final int MAX_ORDER_PAGE_SIZE = 200; |
||||||
|
|
||||||
|
/** 退货列表默认单页条数;沃尔玛默认 10。 */ |
||||||
|
public static final int DEFAULT_RETURN_PAGE_SIZE = 10; |
||||||
|
|
||||||
|
/** |
||||||
|
* 订单创建时间窗的最大回溯天数(📖 官方常见取值,待 Developer Portal 核实)。 |
||||||
|
* |
||||||
|
* <p>超过这个跨度在本地直接拒绝,不做静默截断——静默截断会让宿主以为拉全了。</p> |
||||||
|
*/ |
||||||
|
public static final int MAX_ORDER_WINDOW_DAYS = 180; |
||||||
|
|
||||||
|
/** |
||||||
|
* 令牌提前续期秒数。 |
||||||
|
* |
||||||
|
* <p>{@code expires_in} 只有 900 秒,且沙箱响应头 {@code x-current-token-count} |
||||||
|
* 已达 99(平台对并发有效 token 有上限),必须缓存复用、提前续期。</p> |
||||||
|
*/ |
||||||
|
public static final long TOKEN_EARLY_REFRESH_SECONDS = 120L; |
||||||
|
|
||||||
|
/** 异常里保留的原始响应最大长度;避免整页报文塞进日志。 */ |
||||||
|
public static final int RAW_RESPONSE_LIMIT = 1024; |
||||||
|
|
||||||
|
private WalmartConstants() { |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,642 @@ |
|||||||
|
package common.ecommerce.walmart.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.channel.capability.AfterSaleCapable; |
||||||
|
import common.ecommerce.channel.capability.PlatformAdapter; |
||||||
|
import common.ecommerce.channel.capability.ProductCapable; |
||||||
|
import common.ecommerce.channel.capability.SalesOrderCapable; |
||||||
|
import common.ecommerce.channel.model.account.ChannelAccount; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSale; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleQuery; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrder; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrderQuery; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrderRef; |
||||||
|
import common.ecommerce.channel.model.product.ProductListing; |
||||||
|
import common.ecommerce.channel.model.product.ProductQuery; |
||||||
|
import common.ecommerce.channel.model.product.ProductRef; |
||||||
|
import common.ecommerce.channel.model.product.ProductSyncStrategy; |
||||||
|
import common.ecommerce.channel.sdk.ChannelContext; |
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.http.HttpResponse; |
||||||
|
import common.ecommerce.http.HttpTransport; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.shared.error.ChannelException; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.model.Capability; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.model.Platform; |
||||||
|
import common.ecommerce.shared.spi.AccessToken; |
||||||
|
import common.ecommerce.shared.spi.ChannelSecret; |
||||||
|
import common.ecommerce.shared.spi.LockProvider; |
||||||
|
import common.ecommerce.shared.spi.TokenStore; |
||||||
|
import common.ecommerce.shared.support.Page; |
||||||
|
import common.ecommerce.http.TokenManager; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import common.ecommerce.walmart.auth.WalmartTokenClient; |
||||||
|
import common.ecommerce.walmart.dto.WalmartItemDtos; |
||||||
|
import common.ecommerce.walmart.dto.WalmartOrderDtos; |
||||||
|
import common.ecommerce.walmart.dto.WalmartReturnDtos; |
||||||
|
import common.ecommerce.walmart.dto.WalmartShipmentDtos; |
||||||
|
import common.ecommerce.walmart.http.WalmartErrors; |
||||||
|
import common.ecommerce.walmart.http.WalmartRequestFactory; |
||||||
|
import common.ecommerce.walmart.mapper.WalmartOrderMapper; |
||||||
|
import common.ecommerce.walmart.mapper.WalmartProductMapper; |
||||||
|
import common.ecommerce.walmart.mapper.WalmartReturnMapper; |
||||||
|
import common.ecommerce.walmart.mapper.WalmartShipmentMapper; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Duration; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneId; |
||||||
|
import java.time.format.DateTimeFormatter; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.EnumSet; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Map; |
||||||
|
|
||||||
|
import org.slf4j.Logger; |
||||||
|
import org.slf4j.LoggerFactory; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛 Marketplace 直连适配器(只读)。 |
||||||
|
* |
||||||
|
* <p>实现三个能力接口:</p> |
||||||
|
* <ul> |
||||||
|
* <li>{@link SalesOrderCapable}:{@code GET /v3/orders}、{@code GET /v3/orders/{id}}</li> |
||||||
|
* <li>{@link ProductCapable}:{@code GET /v3/items}、{@code GET /v3/items/{sku}}</li> |
||||||
|
* <li>{@link AfterSaleCapable}:{@code GET /v3/returns}</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p>写操作(标发 / 退款 / 商品写入)本期不实现,对应能力位也不声明—— |
||||||
|
* 门面调用会显式抛 {@code UnsupportedCapabilityException},不会静默成功。</p> |
||||||
|
* |
||||||
|
* <h2>增量语义</h2> |
||||||
|
* <p>沃尔玛订单接口只有<b>创建时间</b>过滤({@code createdStartDate/createdEndDate}), |
||||||
|
* 没有更新时间。因此 {@link SalesOrderQuery#updatedAfter()} 被解释为创建时间窗; |
||||||
|
* 「老单状态变化」需要宿主用 {@link #pullOpenOrders} 单独对账,两者不混在一起, |
||||||
|
* 免得 {@code pull} 的语义变得不可预测。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartAdapter implements SalesOrderCapable, ProductCapable, AfterSaleCapable { |
||||||
|
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(WalmartAdapter.class); |
||||||
|
|
||||||
|
/** 沃尔玛日期时间格式:ISO-8601,毫秒精度,UTC。 */ |
||||||
|
private static final DateTimeFormatter WALMART_TIME_FORMAT = |
||||||
|
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(java.time.ZoneOffset.UTC); |
||||||
|
|
||||||
|
private final HttpTransport transport; |
||||||
|
private final JacksonJsonCodec json; |
||||||
|
private final WalmartRequestFactory requestFactory; |
||||||
|
private final WalmartErrors errors; |
||||||
|
private final TokenManager tokenManager; |
||||||
|
|
||||||
|
public WalmartAdapter(HttpTransport transport, JacksonJsonCodec json, |
||||||
|
TokenStore tokenStore, LockProvider lockProvider, Clock clock) { |
||||||
|
this.transport = transport; |
||||||
|
this.json = json; |
||||||
|
this.requestFactory = new WalmartRequestFactory(); |
||||||
|
this.errors = new WalmartErrors(json); |
||||||
|
final WalmartTokenClient tokenClient = new WalmartTokenClient(transport, json, clock); |
||||||
|
// 令牌有效期 900s,提前 120s 续期;沙箱有效令牌数接近上限,必须缓存复用
|
||||||
|
this.tokenManager = new TokenManager(tokenStore, lockProvider, clock, |
||||||
|
WalmartConstants.TOKEN_EARLY_REFRESH_SECONDS) { |
||||||
|
@Override |
||||||
|
protected AccessToken refresh(ChannelSecret secret, AccessToken previous) { |
||||||
|
return tokenClient.fetch(secret.endpointBaseUrl(), secret.clientId(), secret.clientSecret()); |
||||||
|
} |
||||||
|
}; |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- PlatformAdapter
|
||||||
|
|
||||||
|
@Override |
||||||
|
public String adapterId() { |
||||||
|
return WalmartConstants.ADAPTER_ID; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public ChannelProvider provider() { |
||||||
|
return ChannelProvider.DIRECT; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public java.util.Set<Platform> platforms() { |
||||||
|
return EnumSet.of(Platform.WALMART_SC); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public EnumSet<Capability> capabilities() { |
||||||
|
return EnumSet.of(Capability.SALES_ORDER, Capability.PRODUCT, Capability.RETURNS); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- SalesOrderCapable
|
||||||
|
|
||||||
|
/** |
||||||
|
* 按<b>创建时间窗</b>拉订单(沃尔玛没有更新时间过滤)。 |
||||||
|
* |
||||||
|
* <p>时间窗超过 {@link WalmartConstants#MAX_ORDER_WINDOW_DAYS} 天时本地拒绝, |
||||||
|
* 不做静默截断——静默截断会让宿主以为拉全了。</p> |
||||||
|
*/ |
||||||
|
@Override |
||||||
|
public Page<SalesOrder> pull(ChannelContext ctx, SalesOrderQuery query) { |
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
Instant from = query.updatedAfter(); |
||||||
|
Instant to = query.updatedBefore() != null ? query.updatedBefore() : Instant.now(ctx.clock()); |
||||||
|
validateWindow(from, to); |
||||||
|
|
||||||
|
Map<String, Object> queryParams = WalmartRequestFactory.query(); |
||||||
|
queryParams.put("createdStartDate", WALMART_TIME_FORMAT.format(from)); |
||||||
|
queryParams.put("createdEndDate", WALMART_TIME_FORMAT.format(to)); |
||||||
|
queryParams.put("limit", orderPageSize(query.pageSize())); |
||||||
|
queryParams.put("nextCursor", query.cursor()); |
||||||
|
|
||||||
|
HttpResponse response = execute(ctx, "salesOrders.pull", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), WalmartConstants.PATH_ORDERS, |
||||||
|
queryParams, t, c, "salesOrders.pull"); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
WalmartOrderDtos.OrderListResponse dto = |
||||||
|
json.fromJson(response.body(), WalmartOrderDtos.OrderListResponse.class); |
||||||
|
List<SalesOrder> orders = new ArrayList<SalesOrder>(); |
||||||
|
String nextCursor = null; |
||||||
|
if (dto != null && dto.list != null) { |
||||||
|
if (dto.list.elements != null && dto.list.elements.order != null) { |
||||||
|
for (WalmartOrderDtos.Order order : dto.list.elements.order) { |
||||||
|
SalesOrder mapped = WalmartOrderMapper.toSalesOrder(order, |
||||||
|
account.omsStoreId(), zoneOf(ctx)); |
||||||
|
if (mapped != null) { |
||||||
|
orders.add(mapped); |
||||||
|
} else { |
||||||
|
warnSkipped(ctx, "order", order == null ? null : order.purchaseOrderId); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
if (dto.list.meta != null) { |
||||||
|
nextCursor = dto.list.meta.nextCursor; |
||||||
|
} |
||||||
|
} |
||||||
|
return Page.of(orders, nextCursor); |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单详情;响应比列表多一层 {@code {"order": ...}}。 */ |
||||||
|
@Override |
||||||
|
public SalesOrder get(ChannelContext ctx, SalesOrderRef ref) { |
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
String path = WalmartConstants.PATH_ORDER_BY_ID |
||||||
|
+ WalmartRequestFactory.pathSegment(ref.channelOrderId()); |
||||||
|
HttpResponse response = execute(ctx, "salesOrders.get", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), path, null, t, c, "salesOrders.get"); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
WalmartOrderDtos.OrderDetailResponse dto = |
||||||
|
json.fromJson(response.body(), WalmartOrderDtos.OrderDetailResponse.class); |
||||||
|
SalesOrder order = dto == null ? null |
||||||
|
: WalmartOrderMapper.toSalesOrder(dto.order, account.omsStoreId(), zoneOf(ctx)); |
||||||
|
if (order == null) { |
||||||
|
throw new ValidationException(ChannelException.builder() |
||||||
|
.message("walmart order not found or empty: " + ref.channelOrderId()) |
||||||
|
.operation("salesOrders.get") |
||||||
|
.provider(provider().name()) |
||||||
|
.omsStoreId(ctx.omsStoreId()) |
||||||
|
.platform(ctx.platform()) |
||||||
|
.requestId(ctx.requestId()) |
||||||
|
.platformCode(ref.channelOrderId()) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
return order; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 开放单对账:按行状态拉 {@code Created} / {@code Acknowledged} 的订单。 |
||||||
|
* |
||||||
|
* <p>沃尔玛订单接口只能按创建时间过滤,{@code pull} 拿不到「老单今天发货」这种变化。 |
||||||
|
* 宿主在同步任务里追加一次本方法即可补齐,无需改统一模型。</p> |
||||||
|
* |
||||||
|
* @param statuses 行状态列表,如 {@code ["Created","Acknowledged"]};空则用这两个 |
||||||
|
* @param createdAfter 创建时间下界;null 表示不限制(平台默认行为) |
||||||
|
* @param cursor 游标;首页传 null |
||||||
|
*/ |
||||||
|
public Page<SalesOrder> pullOpenOrders(ChannelContext ctx, List<String> statuses, |
||||||
|
Instant createdAfter, String cursor) { |
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
Map<String, Object> queryParams = WalmartRequestFactory.query(); |
||||||
|
List<String> effective = statuses == null || statuses.isEmpty() |
||||||
|
? java.util.Arrays.asList("Created", "Acknowledged") : statuses; |
||||||
|
queryParams.put("status", joinComma(effective)); |
||||||
|
if (createdAfter != null) { |
||||||
|
queryParams.put("createdStartDate", WALMART_TIME_FORMAT.format(createdAfter)); |
||||||
|
} |
||||||
|
queryParams.put("limit", WalmartConstants.DEFAULT_ORDER_PAGE_SIZE); |
||||||
|
queryParams.put("nextCursor", cursor); |
||||||
|
|
||||||
|
HttpResponse response = execute(ctx, "salesOrders.pullOpen", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), WalmartConstants.PATH_ORDERS, |
||||||
|
queryParams, t, c, "salesOrders.pullOpen"); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
WalmartOrderDtos.OrderListResponse dto = |
||||||
|
json.fromJson(response.body(), WalmartOrderDtos.OrderListResponse.class); |
||||||
|
List<SalesOrder> orders = new ArrayList<SalesOrder>(); |
||||||
|
String nextCursor = null; |
||||||
|
if (dto != null && dto.list != null) { |
||||||
|
if (dto.list.elements != null && dto.list.elements.order != null) { |
||||||
|
for (WalmartOrderDtos.Order order : dto.list.elements.order) { |
||||||
|
SalesOrder mapped = WalmartOrderMapper.toSalesOrder(order, |
||||||
|
account.omsStoreId(), zoneOf(ctx)); |
||||||
|
if (mapped != null) { |
||||||
|
orders.add(mapped); |
||||||
|
} else { |
||||||
|
warnSkipped(ctx, "order", order == null ? null : order.purchaseOrderId); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
if (dto.list.meta != null) { |
||||||
|
nextCursor = dto.list.meta.nextCursor; |
||||||
|
} |
||||||
|
} |
||||||
|
return Page.of(orders, nextCursor); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- ProductCapable
|
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛 items 接口<b>没有更新时间过滤</b>,只能全量拉 + 差分。 |
||||||
|
* |
||||||
|
* @see ProductSyncStrategy#FULL_PULL_DIFF |
||||||
|
*/ |
||||||
|
@Override |
||||||
|
public ProductSyncStrategy syncStrategy() { |
||||||
|
return ProductSyncStrategy.FULL_PULL_DIFF; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 拉商品。 |
||||||
|
* |
||||||
|
* <p>时间窗在此适配器里<b>不支持</b>:传了 {@code updatedAfter/updatedBefore} 直接抛 |
||||||
|
* {@link ValidationException},而不是静默忽略——静默忽略会让宿主以为做了增量。</p> |
||||||
|
*/ |
||||||
|
@Override |
||||||
|
public Page<ProductListing> pull(ChannelContext ctx, ProductQuery query) { |
||||||
|
if (query.updatedAfter() != null || query.updatedBefore() != null) { |
||||||
|
throw unsupportedFilter("walmart /v3/items does not support update-time filtering; " |
||||||
|
+ "use syncStrategy FULL_PULL_DIFF or search by SKU"); |
||||||
|
} |
||||||
|
if (query.searchField() != null && !query.searchValues().isEmpty()) { |
||||||
|
throw unsupportedFilter("walmart /v3/items supports one sku at a time, not multi-value search"); |
||||||
|
} |
||||||
|
if (query.searchField() == common.ecommerce.channel.model.product.ProductSearchField.LOCAL_SKU) { |
||||||
|
throw unsupportedFilter("walmart has no local-sku concept; search by PLATFORM_SKU"); |
||||||
|
} |
||||||
|
|
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
Map<String, Object> queryParams = WalmartRequestFactory.query(); |
||||||
|
queryParams.put("limit", Math.min( |
||||||
|
query.pageSize() <= 0 ? WalmartConstants.MAX_ITEM_PAGE_SIZE : query.pageSize(), |
||||||
|
WalmartConstants.MAX_ITEM_PAGE_SIZE)); |
||||||
|
queryParams.put("nextCursor", query.cursor()); |
||||||
|
if (query.searchValue() != null) { |
||||||
|
queryParams.put("sku", query.searchValue()); |
||||||
|
} |
||||||
|
|
||||||
|
HttpResponse response = execute(ctx, "products.pull", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), WalmartConstants.PATH_ITEMS, |
||||||
|
queryParams, t, c, "products.pull"); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
WalmartItemDtos.ItemListResponse dto = |
||||||
|
json.fromJson(response.body(), WalmartItemDtos.ItemListResponse.class); |
||||||
|
List<ProductListing> products = new ArrayList<ProductListing>(); |
||||||
|
String nextCursor = null; |
||||||
|
if (dto != null) { |
||||||
|
if (dto.itemResponse != null) { |
||||||
|
for (WalmartItemDtos.ItemResponse item : dto.itemResponse) { |
||||||
|
ProductListing mapped = WalmartProductMapper.toProductListing(item, account.omsStoreId()); |
||||||
|
if (mapped != null) { |
||||||
|
products.add(mapped); |
||||||
|
} else { |
||||||
|
warnSkipped(ctx, "item", item == null ? null : item.sku); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
nextCursor = dto.nextCursor; |
||||||
|
} |
||||||
|
return Page.of(products, nextCursor); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 按 SKU 取单品。 |
||||||
|
* |
||||||
|
* <p>⚠ 沙箱实测该路由 404(mock 未实现),只能在生产环境验证。</p> |
||||||
|
*/ |
||||||
|
@Override |
||||||
|
public ProductListing get(ChannelContext ctx, ProductRef ref) { |
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
String path = WalmartConstants.PATH_ITEM_BY_SKU |
||||||
|
+ WalmartRequestFactory.pathSegment(ref.platformSku()); |
||||||
|
HttpResponse response = execute(ctx, "products.get", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), path, null, t, c, "products.get"); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
WalmartItemDtos.ItemResponse dto = |
||||||
|
json.fromJson(response.body(), WalmartItemDtos.ItemResponse.class); |
||||||
|
return WalmartProductMapper.toProductListing(dto, account.omsStoreId()); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- AfterSaleCapable
|
||||||
|
|
||||||
|
/** |
||||||
|
* 拉退货单,<b>按商品行展开</b>。 |
||||||
|
* |
||||||
|
* <p>分页特殊:{@code meta.nextCursor} 本身是一段查询串 |
||||||
|
* (如 {@code "?sellerId=151&limit=10&offset=10"}),翻页时整串拼到 URL 后面。</p> |
||||||
|
* |
||||||
|
* <p>时间窗只支持按退货单创建时间;{@code PURCHASE_TIME} / {@code UPDATE_TIME} |
||||||
|
* 显式报错,不做「拿售后时间顶替」的静默降级。</p> |
||||||
|
*/ |
||||||
|
@Override |
||||||
|
public Page<AfterSale> pull(ChannelContext ctx, AfterSaleQuery query) { |
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
if (query.dateType() != AfterSaleQuery.DateType.AFTER_SALE_TIME) { |
||||||
|
throw unsupportedFilter("walmart /v3/returns only filters by return-created date, got " |
||||||
|
+ query.dateType()); |
||||||
|
} |
||||||
|
if (!query.channelOrderIds().isEmpty()) { |
||||||
|
throw unsupportedFilter("walmart /v3/returns filters one customerOrderId at a time, not a list"); |
||||||
|
} |
||||||
|
|
||||||
|
String cursor = query.cursor(); |
||||||
|
if (cursor != null && !cursor.trim().isEmpty()) { |
||||||
|
// 平台给的游标本身就是完整查询串,直接拼,不再追加参数
|
||||||
|
return executeReturns(ctx, account, "afterSales.pull", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.getWithRawQuery(c.endpointBaseUrl(), |
||||||
|
WalmartConstants.PATH_RETURNS, cursor.trim(), t, c, "afterSales.pull"); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
Map<String, Object> queryParams = WalmartRequestFactory.query(); |
||||||
|
queryParams.put("createdStartDate", WALMART_TIME_FORMAT.format( |
||||||
|
query.startDate().atStartOfDay(ZoneId.of("UTC")).toInstant())); |
||||||
|
queryParams.put("createdEndDate", WALMART_TIME_FORMAT.format( |
||||||
|
query.endDate().atStartOfDay(ZoneId.of("UTC")).toInstant())); |
||||||
|
queryParams.put("limit", query.pageSize() <= 0 |
||||||
|
? WalmartConstants.DEFAULT_RETURN_PAGE_SIZE : query.pageSize()); |
||||||
|
queryParams.put("offset", 0); |
||||||
|
|
||||||
|
return executeReturns(ctx, account, "afterSales.pull", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), WalmartConstants.PATH_RETURNS, |
||||||
|
queryParams, t, c, "afterSales.pull"); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
private Page<AfterSale> executeReturns(ChannelContext ctx, ChannelAccount account, |
||||||
|
String operation, GetPlan plan) { |
||||||
|
HttpResponse response = execute(ctx, operation, plan); |
||||||
|
|
||||||
|
WalmartReturnDtos.ReturnListResponse dto = |
||||||
|
json.fromJson(response.body(), WalmartReturnDtos.ReturnListResponse.class); |
||||||
|
List<AfterSale> afterSales = new ArrayList<AfterSale>(); |
||||||
|
String nextCursor = null; |
||||||
|
if (dto != null) { |
||||||
|
if (dto.returnOrders != null) { |
||||||
|
for (WalmartReturnDtos.ReturnOrder order : dto.returnOrders) { |
||||||
|
List<AfterSale> lines = WalmartReturnMapper.toAfterSales(order, |
||||||
|
account.omsStoreId(), zoneOf(ctx)); |
||||||
|
if (lines.isEmpty()) { |
||||||
|
warnSkipped(ctx, "return", order == null ? null : order.returnOrderId); |
||||||
|
} |
||||||
|
afterSales.addAll(lines); |
||||||
|
} |
||||||
|
} |
||||||
|
if (dto.meta != null) { |
||||||
|
nextCursor = dto.meta.nextCursor; |
||||||
|
} |
||||||
|
} |
||||||
|
return Page.of(afterSales, nextCursor); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 退货单详情:{@code GET /v3/returns/{returnOrderId}}。 |
||||||
|
* |
||||||
|
* <p>与列表一样<b>按商品行展开</b>:一个退货单可能含多个退货行, |
||||||
|
* 返回的 {@link AfterSale#afterSaleId()} 与列表里的完全一致({@code returnOrderId:行号}), |
||||||
|
* 可以直接拿去 upsert。</p> |
||||||
|
* |
||||||
|
* <p>{@link AfterSaleCapable} 没有「取详情」方法——售后以拉取为主, |
||||||
|
* 需要单条时用列表的时间窗过滤即可。这里提供它是因为沃尔玛有真实路由, |
||||||
|
* 且列表接口的过滤参数在沙箱不生效,生产上按单号回查更快。</p> |
||||||
|
* |
||||||
|
* <p>⚠ 沙箱实测该路由 404(mock 未实现),只能在生产环境验证。</p> |
||||||
|
* |
||||||
|
* @param returnOrderId 退货单号 |
||||||
|
* @return 该退货单展开出的售后行;退货单没有行时返回空列表 |
||||||
|
* @throws ChannelException 平台 404 / 其它错误,由 {@link WalmartErrors} 分类 |
||||||
|
*/ |
||||||
|
public List<AfterSale> getReturn(ChannelContext ctx, String returnOrderId) { |
||||||
|
if (returnOrderId == null || returnOrderId.trim().isEmpty()) { |
||||||
|
throw unsupportedFilter("walmart return detail requires returnOrderId"); |
||||||
|
} |
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
String path = WalmartConstants.PATH_RETURN_BY_ID |
||||||
|
+ WalmartRequestFactory.pathSegment(returnOrderId.trim()); |
||||||
|
|
||||||
|
HttpResponse response = execute(ctx, "afterSales.get", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), path, null, t, c, "afterSales.get"); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
WalmartReturnDtos.ReturnOrder dto = |
||||||
|
json.fromJson(response.body(), WalmartReturnDtos.ReturnOrder.class); |
||||||
|
return WalmartReturnMapper.toAfterSales(dto, account.omsStoreId(), zoneOf(ctx)); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 发货信息(非能力接口)
|
||||||
|
|
||||||
|
/** |
||||||
|
* 查询发货信息:{@code GET /v3/orders/{purchaseOrderId}/shipping}。 |
||||||
|
* |
||||||
|
* <p>返回<b>行级</b>发货记录(行号 / 承运商 / 运输方式 / 跟踪号 / 发货时间)。 |
||||||
|
* 统一模型没有独立的发货实体——从订单详情的行状态里也能读到同样的 |
||||||
|
* {@code trackingInfo},两种方式数据一致;本方法用于只想知道「发了哪些行」的场景。</p> |
||||||
|
* |
||||||
|
* <p>⚠ 沙箱实测该路由 404(mock 未实现)。生产上若也不可用,改用 |
||||||
|
* {@link #get(ChannelContext, SalesOrderRef)} 读订单详情。</p> |
||||||
|
* |
||||||
|
* @param purchaseOrderId 沃尔玛订单号 |
||||||
|
* @return 已发货行的记录;未发货时返回空列表 |
||||||
|
*/ |
||||||
|
public List<WalmartShipmentMapper.ShipmentLine> getShipping(ChannelContext ctx, |
||||||
|
String purchaseOrderId) { |
||||||
|
if (purchaseOrderId == null || purchaseOrderId.trim().isEmpty()) { |
||||||
|
throw unsupportedFilter("walmart shipping query requires purchaseOrderId"); |
||||||
|
} |
||||||
|
String path = WalmartConstants.PATH_ORDER_BY_ID |
||||||
|
+ WalmartRequestFactory.pathSegment(purchaseOrderId.trim()) |
||||||
|
+ WalmartConstants.PATH_ORDER_SHIPPING; |
||||||
|
|
||||||
|
HttpResponse response = execute(ctx, "salesOrders.shipping", new GetPlan() { |
||||||
|
@Override |
||||||
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
||||||
|
return requestFactory.get(c.endpointBaseUrl(), path, null, t, c, "salesOrders.shipping"); |
||||||
|
} |
||||||
|
}); |
||||||
|
|
||||||
|
WalmartShipmentDtos.ShipmentResponse dto = |
||||||
|
json.fromJson(response.body(), WalmartShipmentDtos.ShipmentResponse.class); |
||||||
|
return WalmartShipmentMapper.toShipmentLines(dto); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- internals
|
||||||
|
|
||||||
|
/** |
||||||
|
* 执行一次业务请求,401/403 时强制换 token 重试一次。 |
||||||
|
* |
||||||
|
* <p>为什么要重试:沃尔玛 token 的 {@code expires_in} 是 900 秒,但平台可以提前作废 |
||||||
|
* (后台重置 secret、并发令牌超限被踢)。缓存里的坏 token 在自然过期前会一直命中, |
||||||
|
* 期间所有请求都 401。{@code TokenManager} 有 {@code forceRefresh},但门面层没有 |
||||||
|
* 自动重试——重试策略属于适配器,这里只在本模块内实现一次「换 token + 重发」。</p> |
||||||
|
* |
||||||
|
* <p>重试只做一次,第二次失败原样抛出,交由宿主决定是否停用账户。</p> |
||||||
|
*/ |
||||||
|
private HttpResponse execute(ChannelContext ctx, String operation, GetPlan plan) { |
||||||
|
AccessToken token = token(ctx); |
||||||
|
HttpResponse response = transport.execute(plan.request(ctx, token)); |
||||||
|
if (!isAuthFailure(response)) { |
||||||
|
errors.throwIfError(response, ctx, operation); |
||||||
|
return response; |
||||||
|
} |
||||||
|
|
||||||
|
// 缓存里的 token 已失效:强制换新后重发一次
|
||||||
|
ChannelSecret secret = ctx.secret(); |
||||||
|
AccessToken refreshed = tokenManager.forceRefresh(tokenKey(secret), secret); |
||||||
|
HttpResponse retried = transport.execute(plan.request(ctx, refreshed)); |
||||||
|
errors.throwIfError(retried, ctx, operation); |
||||||
|
return retried; |
||||||
|
} |
||||||
|
|
||||||
|
/** 401/403 才值得换 token 重试;其它错误交给 {@link WalmartErrors}。 */ |
||||||
|
private static boolean isAuthFailure(HttpResponse response) { |
||||||
|
return response.statusCode() == 401 || response.statusCode() == 403; |
||||||
|
} |
||||||
|
|
||||||
|
/** 用「当前 token」拼请求;重试时会用新 token 再调一次。 */ |
||||||
|
private interface GetPlan { |
||||||
|
HttpRequest request(ChannelContext ctx, AccessToken token); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 取令牌并返回请求要用的 token。 |
||||||
|
* |
||||||
|
* <p>缓存维度是 {@code clientId}:一个 clientId 对应一个 seller, |
||||||
|
* 同 seller 的多个店铺共用一个令牌,避免触碰平台并发令牌上限。</p> |
||||||
|
*/ |
||||||
|
private AccessToken token(ChannelContext ctx) { |
||||||
|
ChannelSecret secret = ctx.secret(); |
||||||
|
if (isBlank(secret.clientId()) || isBlank(secret.clientSecret())) { |
||||||
|
throw new ValidationException(ChannelException.builder() |
||||||
|
.message("walmart requires ChannelSecret.clientId and clientSecret") |
||||||
|
.operation("token") |
||||||
|
.provider(provider().name()) |
||||||
|
.omsStoreId(ctx.omsStoreId()) |
||||||
|
.platform(ctx.platform()) |
||||||
|
.requestId(ctx.requestId()) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
return tokenManager.getOrRefresh(tokenKey(secret), secret); |
||||||
|
} |
||||||
|
|
||||||
|
/** 令牌缓存键;按 clientId 聚合,同一 seller 的店铺共用。 */ |
||||||
|
static String tokenKey(ChannelSecret secret) { |
||||||
|
return "walmart:" + secret.clientId(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 市场时区:账户没配时按沃尔玛总部所在时区兜底(美国中部)。 */ |
||||||
|
private static ZoneId zoneOf(ChannelContext ctx) { |
||||||
|
ChannelAccount account = ctx.account(); |
||||||
|
String zone = account == null ? null : account.marketplaceZone(); |
||||||
|
return zone == null || zone.trim().isEmpty() ? ZoneId.of("America/Chicago") : ZoneId.of(zone); |
||||||
|
} |
||||||
|
|
||||||
|
/** 时间窗校验:起点必填、终点必须晚于起点、跨度不超过平台上限。 */ |
||||||
|
private static void validateWindow(Instant from, Instant to) { |
||||||
|
if (from == null) { |
||||||
|
throw unsupportedFilter("walmart /v3/orders requires updatedAfter (mapped to createdStartDate)"); |
||||||
|
} |
||||||
|
if (!to.isAfter(from)) { |
||||||
|
throw unsupportedFilter("walmart /v3/orders requires updatedBefore after updatedAfter"); |
||||||
|
} |
||||||
|
long days = Duration.between(from, to).toDays(); |
||||||
|
if (days > WalmartConstants.MAX_ORDER_WINDOW_DAYS) { |
||||||
|
throw unsupportedFilter("walmart /v3/orders window is " + days + " days, max " |
||||||
|
+ WalmartConstants.MAX_ORDER_WINDOW_DAYS + "; split the window instead of truncating"); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单单页条数:0 或负数用默认值,超出上限本地截断(与商品同一策略)。 */ |
||||||
|
private static int orderPageSize(int requested) { |
||||||
|
if (requested <= 0) { |
||||||
|
return WalmartConstants.DEFAULT_ORDER_PAGE_SIZE; |
||||||
|
} |
||||||
|
return Math.min(requested, WalmartConstants.MAX_ORDER_PAGE_SIZE); |
||||||
|
} |
||||||
|
|
||||||
|
private static String joinComma(List<String> values) { |
||||||
|
StringBuilder sb = new StringBuilder(); |
||||||
|
for (String v : values) { |
||||||
|
if (v == null || v.trim().isEmpty()) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
if (sb.length() > 0) { |
||||||
|
sb.append(','); |
||||||
|
} |
||||||
|
sb.append(v.trim()); |
||||||
|
} |
||||||
|
return sb.toString(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 平台给了一条缺必填字段的记录,映射层丢弃时留痕。 |
||||||
|
* |
||||||
|
* <p>不抛异常:一条脏数据不该卡住整页同步;但也不能完全静默——宿主需要知道 |
||||||
|
* 「这次少了一条」以及少的是哪个单号。</p> |
||||||
|
*/ |
||||||
|
private static void warnSkipped(ChannelContext ctx, String kind, String id) { |
||||||
|
LOG.warn("walmart {} skipped: missing required field, id={} store={} requestId={}", |
||||||
|
kind, id, ctx.omsStoreId(), ctx.requestId()); |
||||||
|
} |
||||||
|
|
||||||
|
private static boolean isBlank(String v) { |
||||||
|
return v == null || v.trim().isEmpty(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 适配器不支持某过滤条件时的统一异常。 */ |
||||||
|
private static ValidationException unsupportedFilter(String message) { |
||||||
|
return new ValidationException(ChannelException.builder() |
||||||
|
.message(message) |
||||||
|
.operation("walmart.filter") |
||||||
|
.provider(ChannelProvider.DIRECT.name()) |
||||||
|
.platform(Platform.WALMART_SC) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,63 @@ |
|||||||
|
package common.ecommerce.walmart.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.channel.capability.PlatformAdapter; |
||||||
|
import common.ecommerce.channel.sdk.AdapterFactory; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.http.OkHttpTransport; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.model.Platform; |
||||||
|
import common.ecommerce.shared.spi.LockProvider; |
||||||
|
import common.ecommerce.shared.spi.TokenStore; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.util.EnumSet; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛直连适配器工厂。 |
||||||
|
* |
||||||
|
* <p>与领星、三方仓使用同一套注册机制:工厂只装配基础设施, |
||||||
|
* <b>不持有端点与凭据</b>——两者由调用方每次经 {@code ChannelConnection} 传入。</p> |
||||||
|
* |
||||||
|
* <pre> |
||||||
|
* ChannelSdk.builder() |
||||||
|
* .accountRepository(repo) |
||||||
|
* .register(new WalmartAdapterFactory(tokenStore, lockProvider, Clock.systemUTC())) |
||||||
|
* .build(); |
||||||
|
* </pre> |
||||||
|
*/ |
||||||
|
public final class WalmartAdapterFactory implements AdapterFactory { |
||||||
|
|
||||||
|
private final TokenStore tokenStore; |
||||||
|
private final LockProvider lockProvider; |
||||||
|
private final Clock clock; |
||||||
|
|
||||||
|
public WalmartAdapterFactory(TokenStore tokenStore, LockProvider lockProvider, Clock clock) { |
||||||
|
this.tokenStore = tokenStore; |
||||||
|
this.lockProvider = lockProvider; |
||||||
|
this.clock = clock; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String adapterId() { |
||||||
|
return WalmartConstants.ADAPTER_ID; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public ChannelProvider provider() { |
||||||
|
return ChannelProvider.DIRECT; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public EnumSet<Platform> platforms() { |
||||||
|
return EnumSet.of(Platform.WALMART_SC); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public PlatformAdapter create(AdapterConfig config) { |
||||||
|
return new WalmartAdapter( |
||||||
|
new OkHttpTransport("common-ecommerce/1.0.0 (walmart)"), |
||||||
|
new JacksonJsonCodec(), |
||||||
|
tokenStore, lockProvider, clock); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,127 @@ |
|||||||
|
package common.ecommerce.walmart.auth; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.http.HttpResponse; |
||||||
|
import common.ecommerce.http.HttpTransport; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.http.Responses; |
||||||
|
import common.ecommerce.shared.error.AuthException; |
||||||
|
import common.ecommerce.shared.error.ChannelException; |
||||||
|
import common.ecommerce.shared.spi.AccessToken; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import common.ecommerce.walmart.dto.WalmartTokenDtos; |
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets; |
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.util.Base64; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛令牌接口:{@code POST /v3/token}。 |
||||||
|
* |
||||||
|
* <p>请求:Basic Auth({@code clientId:clientSecret})+ form 体 |
||||||
|
* {@code grant_type=client_credentials}。</p> |
||||||
|
* |
||||||
|
* <p>响应:{@code access_token} / {@code token_type=Bearer} / {@code expires_in=900}。 |
||||||
|
* 业务接口带 {@code WM_SEC.ACCESS_TOKEN} 头,<b>不再</b>带 Basic Auth(沙箱实测)。</p> |
||||||
|
* |
||||||
|
* <p>令牌按 {@code clientId} 维度缓存:一个 clientId 对应一个 seller, |
||||||
|
* 多店铺共用同一令牌,避免触碰平台的并发有效令牌上限 |
||||||
|
* (沙箱 {@code x-current-token-count} 已接近上限)。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartTokenClient { |
||||||
|
|
||||||
|
private static final String OP_FETCH = "token.fetch"; |
||||||
|
|
||||||
|
/** 平台未返回 expires_in 时的兜底有效期(秒):官方值为 900。 */ |
||||||
|
static final long DEFAULT_EXPIRES_IN_SECONDS = 900L; |
||||||
|
|
||||||
|
private final HttpTransport transport; |
||||||
|
private final JacksonJsonCodec json; |
||||||
|
private final Clock clock; |
||||||
|
|
||||||
|
public WalmartTokenClient(HttpTransport transport, JacksonJsonCodec json, Clock clock) { |
||||||
|
this.transport = transport; |
||||||
|
this.json = json; |
||||||
|
this.clock = clock; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 用 clientId + clientSecret 换新令牌。 |
||||||
|
* |
||||||
|
* @param baseUrl 端点基址(沙箱或生产),由调用方每次传入 |
||||||
|
* @param clientId 沃尔玛 Client ID |
||||||
|
* @param clientSecret 沃尔玛 Client Secret |
||||||
|
* @throws AuthException clientId / clientSecret 为空,或平台返回 401 / 403 |
||||||
|
*/ |
||||||
|
public AccessToken fetch(String baseUrl, String clientId, String clientSecret) { |
||||||
|
if (isBlank(clientId) || isBlank(clientSecret)) { |
||||||
|
throw new AuthException(ChannelException.builder() |
||||||
|
.message("walmart token requires clientId and clientSecret") |
||||||
|
.operation(OP_FETCH) |
||||||
|
.provider(WalmartConstants.ADAPTER_ID) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
|
||||||
|
HttpRequest request = HttpRequest.builder() |
||||||
|
.method("POST") |
||||||
|
.url(baseUrl + WalmartConstants.PATH_TOKEN) |
||||||
|
.contentType(WalmartConstants.CONTENT_TYPE_FORM) |
||||||
|
.header("Authorization", basicAuth(clientId, clientSecret)) |
||||||
|
.header(WalmartConstants.HEADER_SVC_NAME, WalmartConstants.SVC_NAME_VALUE) |
||||||
|
.header("Accept", WalmartConstants.CONTENT_TYPE_JSON) |
||||||
|
.body("grant_type=client_credentials") |
||||||
|
.operation(OP_FETCH) |
||||||
|
.build(); |
||||||
|
|
||||||
|
HttpResponse response = transport.execute(request); |
||||||
|
Responses.throwIfNotSuccess(response, OP_FETCH); |
||||||
|
|
||||||
|
WalmartTokenDtos.TokenResponse dto; |
||||||
|
try { |
||||||
|
dto = json.fromJson(response.body(), WalmartTokenDtos.TokenResponse.class); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
throw new AuthException(ChannelException.builder() |
||||||
|
.message("walmart token response is not valid json") |
||||||
|
.operation(OP_FETCH) |
||||||
|
.provider(WalmartConstants.ADAPTER_ID) |
||||||
|
.retryable(false) |
||||||
|
.rawResponse(truncate(response.body())), |
||||||
|
e); |
||||||
|
} |
||||||
|
if (dto == null || isBlank(dto.accessToken)) { |
||||||
|
throw new AuthException(ChannelException.builder() |
||||||
|
.message("walmart token response has no access_token") |
||||||
|
.operation(OP_FETCH) |
||||||
|
.provider(WalmartConstants.ADAPTER_ID) |
||||||
|
.retryable(false) |
||||||
|
.rawResponse(truncate(response.body()))); |
||||||
|
} |
||||||
|
|
||||||
|
long expiresIn = dto.expiresIn == null || dto.expiresIn <= 0 |
||||||
|
? DEFAULT_EXPIRES_IN_SECONDS : dto.expiresIn.longValue(); |
||||||
|
return AccessToken.builder() |
||||||
|
.value(dto.accessToken) |
||||||
|
.tokenType(isBlank(dto.tokenType) ? "Bearer" : dto.tokenType) |
||||||
|
.expiresAt(Instant.now(clock).plusSeconds(expiresIn)) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** Base64(clientId:clientSecret),UTF-8。 */ |
||||||
|
static String basicAuth(String clientId, String clientSecret) { |
||||||
|
String raw = clientId + ":" + clientSecret; |
||||||
|
return "Basic " + Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); |
||||||
|
} |
||||||
|
|
||||||
|
private static boolean isBlank(String v) { |
||||||
|
return v == null || v.trim().isEmpty(); |
||||||
|
} |
||||||
|
|
||||||
|
private static String truncate(String body) { |
||||||
|
if (body == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
return body.length() <= WalmartConstants.RAW_RESPONSE_LIMIT |
||||||
|
? body : body.substring(0, WalmartConstants.RAW_RESPONSE_LIMIT); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,113 @@ |
|||||||
|
package common.ecommerce.walmart.dto; |
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||||
|
|
||||||
|
import java.math.BigDecimal; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛报文结构:商品 Listing({@code GET /v3/items}、{@code GET /v3/items/{sku}})。 |
||||||
|
* |
||||||
|
* <p>列表字段名是单数 {@code ItemResponse},没有外层包装对象,直接是数组。</p> |
||||||
|
* |
||||||
|
* <p>{@code shelf} 是<b>JSON 字符串数组</b>(例如 {@code "[\"Home Page\",\"Clothing\"]"}), |
||||||
|
* 需要二次解析;{@code UNNAV} 表示未分配到可浏览类目。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartItemDtos { |
||||||
|
|
||||||
|
private WalmartItemDtos() { |
||||||
|
} |
||||||
|
|
||||||
|
/** 商品列表响应。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ItemListResponse { |
||||||
|
|
||||||
|
/** 商品数组;字段名就是单数 {@code ItemResponse}。 */ |
||||||
|
@JsonProperty("ItemResponse") |
||||||
|
public List<ItemResponse> itemResponse; |
||||||
|
|
||||||
|
/** 商品总数。 */ |
||||||
|
@JsonProperty("totalItems") |
||||||
|
public Integer totalItems; |
||||||
|
|
||||||
|
/** 下一页游标;无更多时为 null。 */ |
||||||
|
@JsonProperty("nextCursor") |
||||||
|
public String nextCursor; |
||||||
|
} |
||||||
|
|
||||||
|
/** 商品。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ItemResponse { |
||||||
|
|
||||||
|
/** 站点:{@code WALMART_US} / {@code WALMART_CA} / {@code WALMART_MX}。 */ |
||||||
|
@JsonProperty("mart") |
||||||
|
public String mart; |
||||||
|
|
||||||
|
/** 卖家 SKU。 */ |
||||||
|
@JsonProperty("sku") |
||||||
|
public String sku; |
||||||
|
|
||||||
|
/** 沃尔玛商品 ID(Walmart Product ID)。 */ |
||||||
|
@JsonProperty("wpid") |
||||||
|
public String wpid; |
||||||
|
|
||||||
|
/** UPC 编码。 */ |
||||||
|
@JsonProperty("upc") |
||||||
|
public String upc; |
||||||
|
|
||||||
|
/** GTIN 编码(14 位,含前导 0)。 */ |
||||||
|
@JsonProperty("gtin") |
||||||
|
public String gtin; |
||||||
|
|
||||||
|
/** 商品名称。 */ |
||||||
|
@JsonProperty("productName") |
||||||
|
public String productName; |
||||||
|
|
||||||
|
/** 前台类目:JSON 字符串数组,如 {@code "[\"Home Page\",\"Clothing\"]"}。 */ |
||||||
|
@JsonProperty("shelf") |
||||||
|
public String shelf; |
||||||
|
|
||||||
|
/** 商品类型 / 类目模板名,如 {@code T-Shirts};{@code default} 表示默认模板。 */ |
||||||
|
@JsonProperty("productType") |
||||||
|
public String productType; |
||||||
|
|
||||||
|
/** 价格。 */ |
||||||
|
@JsonProperty("price") |
||||||
|
public Price price; |
||||||
|
|
||||||
|
/** 发布状态:{@code PUBLISHED} / {@code UNPUBLISHED} / {@code SYSTEM_PROBLEM} 等。 */ |
||||||
|
@JsonProperty("publishedStatus") |
||||||
|
public String publishedStatus; |
||||||
|
|
||||||
|
/** 未发布原因。 */ |
||||||
|
@JsonProperty("unpublishedReasons") |
||||||
|
public UnpublishedReasons unpublishedReasons; |
||||||
|
|
||||||
|
/** 生命周期状态:{@code ACTIVE} / {@code ARCHIVED} / {@code RETIRED}。 */ |
||||||
|
@JsonProperty("lifecycleStatus") |
||||||
|
public String lifecycleStatus; |
||||||
|
} |
||||||
|
|
||||||
|
/** 价格。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Price { |
||||||
|
|
||||||
|
/** 币种:{@code USD} / {@code CAD} / {@code MXN}。 */ |
||||||
|
@JsonProperty("currency") |
||||||
|
public String currency; |
||||||
|
|
||||||
|
/** 售价;用 BigDecimal 接。 */ |
||||||
|
@JsonProperty("amount") |
||||||
|
public BigDecimal amount; |
||||||
|
} |
||||||
|
|
||||||
|
/** 未发布原因容器。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class UnpublishedReasons { |
||||||
|
|
||||||
|
/** 原因列表(英文描述)。 */ |
||||||
|
@JsonProperty("reason") |
||||||
|
public List<String> reason; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,377 @@ |
|||||||
|
package common.ecommerce.walmart.dto; |
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||||
|
|
||||||
|
import java.math.BigDecimal; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛报文结构:订单({@code GET /v3/orders}、{@code GET /v3/orders/{id}})。 |
||||||
|
* |
||||||
|
* <p><b>层次陷阱</b>:沃尔玛的 JSON 由旧版 XML Schema 转换而来,数组外层带单数包装对象: |
||||||
|
* {@code orderLines.orderLine[]}、{@code orderLineStatuses.orderLineStatus[]}、 |
||||||
|
* {@code charges.charge[]}。字段名照抄,不要「优化」成复数。</p> |
||||||
|
* |
||||||
|
* <p><b>类型陷阱</b>:金额是 {@code {"currency","amount"}} 且 amount 是数字; |
||||||
|
* 数量是 {@code {"unitOfMeasurement","amount"}} 且 amount 是<b>字符串</b>; |
||||||
|
* 时间是 epoch 毫秒。三者在退货接口里又都不一样。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartOrderDtos { |
||||||
|
|
||||||
|
private WalmartOrderDtos() { |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单列表响应:{@code list.meta} + {@code list.elements.order[]}。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderListResponse { |
||||||
|
|
||||||
|
/** 列表容器;平台未返回时为 null。 */ |
||||||
|
@JsonProperty("list") |
||||||
|
public ListWrapper list; |
||||||
|
} |
||||||
|
|
||||||
|
/** 列表容器。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ListWrapper { |
||||||
|
|
||||||
|
/** 分页元信息。 */ |
||||||
|
@JsonProperty("meta") |
||||||
|
public Meta meta; |
||||||
|
|
||||||
|
/** 订单数组容器。 */ |
||||||
|
@JsonProperty("elements") |
||||||
|
public Elements elements; |
||||||
|
} |
||||||
|
|
||||||
|
/** 分页元信息。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Meta { |
||||||
|
|
||||||
|
/** 总订单数。 */ |
||||||
|
@JsonProperty("totalCount") |
||||||
|
public Integer totalCount; |
||||||
|
|
||||||
|
/** 当前每页条数。 */ |
||||||
|
@JsonProperty("limit") |
||||||
|
public Integer limit; |
||||||
|
|
||||||
|
/** 下一页游标;无更多为 null。 */ |
||||||
|
@JsonProperty("nextCursor") |
||||||
|
public String nextCursor; |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单数组的包装层。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Elements { |
||||||
|
|
||||||
|
/** 订单数组;字段名就是单数 {@code order}。 */ |
||||||
|
@JsonProperty("order") |
||||||
|
public List<Order> order; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 订单详情响应:{@code {"order": {...}}}。 |
||||||
|
* |
||||||
|
* <p>比列表多包一层,映射时两者共用 {@link Order}。</p> |
||||||
|
*/ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderDetailResponse { |
||||||
|
|
||||||
|
/** 订单本体。 */ |
||||||
|
@JsonProperty("order") |
||||||
|
public Order order; |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单本体。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Order { |
||||||
|
|
||||||
|
/** 沃尔玛订单号;标发接口的路径参数。 */ |
||||||
|
@JsonProperty("purchaseOrderId") |
||||||
|
public String purchaseOrderId; |
||||||
|
|
||||||
|
/** 平台客户订单号;买家侧看到的是它。 */ |
||||||
|
@JsonProperty("customerOrderId") |
||||||
|
public String customerOrderId; |
||||||
|
|
||||||
|
/** 客户邮箱;通常是沃尔玛中转地址({@code @relay.walmart.com})。 */ |
||||||
|
@JsonProperty("customerEmailId") |
||||||
|
public String customerEmailId; |
||||||
|
|
||||||
|
/** 下单时间,<b>epoch 毫秒</b>。 */ |
||||||
|
@JsonProperty("orderDate") |
||||||
|
public Long orderDate; |
||||||
|
|
||||||
|
/** 配送与收货信息。 */ |
||||||
|
@JsonProperty("shippingInfo") |
||||||
|
public ShippingInfo shippingInfo; |
||||||
|
|
||||||
|
/** 订单行容器。 */ |
||||||
|
@JsonProperty("orderLines") |
||||||
|
public OrderLines orderLines; |
||||||
|
|
||||||
|
/** 发货节点类型({@code SellerFulfilled} / {@code WalmartFulfilled})。 */ |
||||||
|
@JsonProperty("shipNode") |
||||||
|
public ShipNode shipNode; |
||||||
|
} |
||||||
|
|
||||||
|
/** 配送与收货信息。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ShippingInfo { |
||||||
|
|
||||||
|
/** 收件人电话。 */ |
||||||
|
@JsonProperty("phone") |
||||||
|
public String phone; |
||||||
|
|
||||||
|
/** 预计发货时间,epoch 毫秒。 */ |
||||||
|
@JsonProperty("estimatedShipDate") |
||||||
|
public Long estimatedShipDate; |
||||||
|
|
||||||
|
/** 预计送达时间,epoch 毫秒。 */ |
||||||
|
@JsonProperty("estimatedDeliveryDate") |
||||||
|
public Long estimatedDeliveryDate; |
||||||
|
|
||||||
|
/** 订单配送方式({@code Value} / {@code Standard} / {@code TwoDay} 等)。 */ |
||||||
|
@JsonProperty("methodCode") |
||||||
|
public String methodCode; |
||||||
|
|
||||||
|
/** 收货地址。 */ |
||||||
|
@JsonProperty("postalAddress") |
||||||
|
public PostalAddress postalAddress; |
||||||
|
} |
||||||
|
|
||||||
|
/** 收货地址。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class PostalAddress { |
||||||
|
|
||||||
|
/** 收件人姓名。 */ |
||||||
|
@JsonProperty("name") |
||||||
|
public String name; |
||||||
|
|
||||||
|
/** 地址行 1。 */ |
||||||
|
@JsonProperty("address1") |
||||||
|
public String address1; |
||||||
|
|
||||||
|
/** 地址行 2;可为 null。 */ |
||||||
|
@JsonProperty("address2") |
||||||
|
public String address2; |
||||||
|
|
||||||
|
/** 城市。 */ |
||||||
|
@JsonProperty("city") |
||||||
|
public String city; |
||||||
|
|
||||||
|
/** 州。 */ |
||||||
|
@JsonProperty("state") |
||||||
|
public String state; |
||||||
|
|
||||||
|
/** 邮编。 */ |
||||||
|
@JsonProperty("postalCode") |
||||||
|
public String postalCode; |
||||||
|
|
||||||
|
/** 国家,如 {@code USA}。 */ |
||||||
|
@JsonProperty("country") |
||||||
|
public String country; |
||||||
|
|
||||||
|
/** 地址类型:{@code RESIDENTIAL} / {@code OFFICE}。 */ |
||||||
|
@JsonProperty("addressType") |
||||||
|
public String addressType; |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单行容器。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLines { |
||||||
|
|
||||||
|
/** 订单行数组。 */ |
||||||
|
@JsonProperty("orderLine") |
||||||
|
public List<OrderLine> orderLine; |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单行。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLine { |
||||||
|
|
||||||
|
/** 行号;标发报文里对应 {@code orderLine.lineNumber}。 */ |
||||||
|
@JsonProperty("lineNumber") |
||||||
|
public String lineNumber; |
||||||
|
|
||||||
|
/** 商品信息。 */ |
||||||
|
@JsonProperty("item") |
||||||
|
public Item item; |
||||||
|
|
||||||
|
/** 费用明细容器。 */ |
||||||
|
@JsonProperty("charges") |
||||||
|
public Charges charges; |
||||||
|
|
||||||
|
/** 数量,amount 是<b>字符串</b>。 */ |
||||||
|
@JsonProperty("orderLineQuantity") |
||||||
|
public Quantity orderLineQuantity; |
||||||
|
|
||||||
|
/** 行状态容器。 */ |
||||||
|
@JsonProperty("orderLineStatuses") |
||||||
|
public OrderLineStatuses orderLineStatuses; |
||||||
|
|
||||||
|
/** 状态时间,epoch 毫秒。 */ |
||||||
|
@JsonProperty("statusDate") |
||||||
|
public Long statusDate; |
||||||
|
|
||||||
|
/** 履约信息;结构未在沙箱覆盖,保留原始节点不映射。 */ |
||||||
|
@JsonProperty("fulfillment") |
||||||
|
public Object fulfillment; |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单行商品。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Item { |
||||||
|
|
||||||
|
/** 商品名称。 */ |
||||||
|
@JsonProperty("productName") |
||||||
|
public String productName; |
||||||
|
|
||||||
|
/** 卖家 SKU。 */ |
||||||
|
@JsonProperty("sku") |
||||||
|
public String sku; |
||||||
|
} |
||||||
|
|
||||||
|
/** 费用明细容器。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Charges { |
||||||
|
|
||||||
|
/** 费用数组。 */ |
||||||
|
@JsonProperty("charge") |
||||||
|
public List<Charge> charge; |
||||||
|
} |
||||||
|
|
||||||
|
/** 单条费用。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Charge { |
||||||
|
|
||||||
|
/** 费用类型:{@code PRODUCT} / {@code FEE} / {@code SHIPPING}。 */ |
||||||
|
@JsonProperty("chargeType") |
||||||
|
public String chargeType; |
||||||
|
|
||||||
|
/** 费用名称,如 {@code ItemPrice}、{@code Shipping}。 */ |
||||||
|
@JsonProperty("chargeName") |
||||||
|
public String chargeName; |
||||||
|
|
||||||
|
/** 费用金额。 */ |
||||||
|
@JsonProperty("chargeAmount") |
||||||
|
public Amount chargeAmount; |
||||||
|
|
||||||
|
/** 税。 */ |
||||||
|
@JsonProperty("tax") |
||||||
|
public Tax tax; |
||||||
|
} |
||||||
|
|
||||||
|
/** 金额:{@code {"currency","amount"}},amount 是数字。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Amount { |
||||||
|
|
||||||
|
/** 币种,如 {@code USD}。 */ |
||||||
|
@JsonProperty("currency") |
||||||
|
public String currency; |
||||||
|
|
||||||
|
/** 金额;用 BigDecimal 接,避免 double 精度问题。 */ |
||||||
|
@JsonProperty("amount") |
||||||
|
public BigDecimal amount; |
||||||
|
} |
||||||
|
|
||||||
|
/** 税。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Tax { |
||||||
|
|
||||||
|
/** 税名。 */ |
||||||
|
@JsonProperty("taxName") |
||||||
|
public String taxName; |
||||||
|
|
||||||
|
/** 税额。 */ |
||||||
|
@JsonProperty("taxAmount") |
||||||
|
public Amount taxAmount; |
||||||
|
} |
||||||
|
|
||||||
|
/** 数量:{@code {"unitOfMeasurement","amount"}},amount 是<b>字符串</b>。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Quantity { |
||||||
|
|
||||||
|
/** 计量单位,如 {@code EACH}。 */ |
||||||
|
@JsonProperty("unitOfMeasurement") |
||||||
|
public String unitOfMeasurement; |
||||||
|
|
||||||
|
/** 数量,字符串(沙箱样例 {@code "1"})。 */ |
||||||
|
@JsonProperty("amount") |
||||||
|
public String amount; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行状态容器。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLineStatuses { |
||||||
|
|
||||||
|
/** 行状态数组。 */ |
||||||
|
@JsonProperty("orderLineStatus") |
||||||
|
public List<OrderLineStatus> orderLineStatus; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行状态。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLineStatus { |
||||||
|
|
||||||
|
/** 状态:{@code Created} / {@code Acknowledged} / {@code Shipped} / {@code Delivered} / {@code Cancelled}。 */ |
||||||
|
@JsonProperty("status") |
||||||
|
public String status; |
||||||
|
|
||||||
|
/** 该状态对应的数量。 */ |
||||||
|
@JsonProperty("statusQuantity") |
||||||
|
public Quantity statusQuantity; |
||||||
|
|
||||||
|
/** 取消原因,仅取消时有值。 */ |
||||||
|
@JsonProperty("cancellationReason") |
||||||
|
public String cancellationReason; |
||||||
|
|
||||||
|
/** 物流跟踪信息;未发货时为 null。 */ |
||||||
|
@JsonProperty("trackingInfo") |
||||||
|
public TrackingInfo trackingInfo; |
||||||
|
} |
||||||
|
|
||||||
|
/** 物流跟踪信息。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class TrackingInfo { |
||||||
|
|
||||||
|
/** 发货时间,ISO-8601 字符串(与订单其它时间是 epoch 毫秒不同)。 */ |
||||||
|
@JsonProperty("shipDateTime") |
||||||
|
public String shipDateTime; |
||||||
|
|
||||||
|
/** 承运商。 */ |
||||||
|
@JsonProperty("carrierName") |
||||||
|
public CarrierName carrierName; |
||||||
|
|
||||||
|
/** 运输方式编码。 */ |
||||||
|
@JsonProperty("methodCode") |
||||||
|
public String methodCode; |
||||||
|
|
||||||
|
/** 跟踪号。 */ |
||||||
|
@JsonProperty("trackingNumber") |
||||||
|
public String trackingNumber; |
||||||
|
} |
||||||
|
|
||||||
|
/** 承运商:标准承运商用 {@code carrier},非标准用 {@code otherCarrier},二选一。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class CarrierName { |
||||||
|
|
||||||
|
/** 承运商编码,如 {@code UPS}、{@code FedEx}。 */ |
||||||
|
@JsonProperty("carrier") |
||||||
|
public String carrier; |
||||||
|
|
||||||
|
/** 非标准承运商名称。 */ |
||||||
|
@JsonProperty("otherCarrier") |
||||||
|
public String otherCarrier; |
||||||
|
} |
||||||
|
|
||||||
|
/** 发货节点。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ShipNode { |
||||||
|
|
||||||
|
/** 发货节点类型:{@code SellerFulfilled} / {@code WalmartFulfilled}。 */ |
||||||
|
@JsonProperty("type") |
||||||
|
public String type; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,396 @@ |
|||||||
|
package common.ecommerce.walmart.dto; |
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||||
|
|
||||||
|
import java.math.BigDecimal; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛报文结构:售后退货({@code GET /v3/returns}、{@code GET /v3/returns/{id}})。 |
||||||
|
* |
||||||
|
* <p><b>与订单接口的差异(同一个字段三种写法)</b>:</p> |
||||||
|
* <ul> |
||||||
|
* <li>金额:订单是 {@code {"currency","amount"}},退货是 {@code {"currencyAmount","currencyUnit"}}</li> |
||||||
|
* <li>数量:订单是 {@code {"unitOfMeasurement","amount"(字符串)}}, |
||||||
|
* 退货是 {@code {"unitOfMeasure","measurementValue"(数字)}}</li> |
||||||
|
* <li>时间:订单是 epoch 毫秒,退货是 ISO-8601 字符串</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p><b>分页陷阱</b>:{@code meta.nextCursor} 的值本身是一段查询串 |
||||||
|
* ({@code "?sellerId=151&limit=10&offset=10"}),翻页时整串拼到 URL 后面, |
||||||
|
* 不是普通游标。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartReturnDtos { |
||||||
|
|
||||||
|
private WalmartReturnDtos() { |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货单列表响应。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ReturnListResponse { |
||||||
|
|
||||||
|
/** 分页元信息。 */ |
||||||
|
@JsonProperty("meta") |
||||||
|
public Meta meta; |
||||||
|
|
||||||
|
/** 退货单数组。 */ |
||||||
|
@JsonProperty("returnOrders") |
||||||
|
public List<ReturnOrder> returnOrders; |
||||||
|
} |
||||||
|
|
||||||
|
/** 分页元信息。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Meta { |
||||||
|
|
||||||
|
/** 退货单总数。 */ |
||||||
|
@JsonProperty("totalCount") |
||||||
|
public Integer totalCount; |
||||||
|
|
||||||
|
/** 当前每页条数。 */ |
||||||
|
@JsonProperty("limit") |
||||||
|
public Integer limit; |
||||||
|
|
||||||
|
/** 下一页查询串;无更多时为 null。 */ |
||||||
|
@JsonProperty("nextCursor") |
||||||
|
public String nextCursor; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货单(一个退货单可含多个退货行)。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ReturnOrder { |
||||||
|
|
||||||
|
/** 退货单号。 */ |
||||||
|
@JsonProperty("returnOrderId") |
||||||
|
public String returnOrderId; |
||||||
|
|
||||||
|
/** 客户邮箱(沃尔玛中转邮箱)。 */ |
||||||
|
@JsonProperty("customerEmailId") |
||||||
|
public String customerEmailId; |
||||||
|
|
||||||
|
/** 客户姓名。 */ |
||||||
|
@JsonProperty("customerName") |
||||||
|
public CustomerName customerName; |
||||||
|
|
||||||
|
/** 平台客户订单号。 */ |
||||||
|
@JsonProperty("customerOrderId") |
||||||
|
public String customerOrderId; |
||||||
|
|
||||||
|
/** 退款模式:{@code PRE_DELIVERY} / {@code POST_DELIVERY}。 */ |
||||||
|
@JsonProperty("refundMode") |
||||||
|
public String refundMode; |
||||||
|
|
||||||
|
/** 退货单创建时间,ISO-8601 字符串。 */ |
||||||
|
@JsonProperty("returnOrderDate") |
||||||
|
public String returnOrderDate; |
||||||
|
|
||||||
|
/** 退货类型:{@code RETURN} / {@code REPLACEMENT}。 */ |
||||||
|
@JsonProperty("returnType") |
||||||
|
public String returnType; |
||||||
|
|
||||||
|
/** 换货生成的客户订单号;换货时有值。 */ |
||||||
|
@JsonProperty("replacementCustomerOrderId") |
||||||
|
public String replacementCustomerOrderId; |
||||||
|
|
||||||
|
/** 最晚退货时间,ISO-8601。 */ |
||||||
|
@JsonProperty("returnByDate") |
||||||
|
public String returnByDate; |
||||||
|
|
||||||
|
/** 应退总金额。 */ |
||||||
|
@JsonProperty("totalRefundAmount") |
||||||
|
public CurrencyAmount totalRefundAmount; |
||||||
|
|
||||||
|
/** 退货渠道。 */ |
||||||
|
@JsonProperty("returnChannel") |
||||||
|
public ReturnChannel returnChannel; |
||||||
|
|
||||||
|
/** 退货包裹 / 面单分组。 */ |
||||||
|
@JsonProperty("returnLineGroups") |
||||||
|
public List<ReturnLineGroup> returnLineGroups; |
||||||
|
|
||||||
|
/** 退货行数组。 */ |
||||||
|
@JsonProperty("returnOrderLines") |
||||||
|
public List<ReturnOrderLine> returnOrderLines; |
||||||
|
} |
||||||
|
|
||||||
|
/** 客户姓名。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class CustomerName { |
||||||
|
|
||||||
|
/** 名。 */ |
||||||
|
@JsonProperty("firstName") |
||||||
|
public String firstName; |
||||||
|
|
||||||
|
/** 姓。 */ |
||||||
|
@JsonProperty("lastName") |
||||||
|
public String lastName; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货金额:{@code {"currencyAmount","currencyUnit"}};currencyAmount 是数字。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class CurrencyAmount { |
||||||
|
|
||||||
|
/** 金额;用 BigDecimal 接。 */ |
||||||
|
@JsonProperty("currencyAmount") |
||||||
|
public BigDecimal currencyAmount; |
||||||
|
|
||||||
|
/** 币种,如 {@code USD}。 */ |
||||||
|
@JsonProperty("currencyUnit") |
||||||
|
public String currencyUnit; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货渠道。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ReturnChannel { |
||||||
|
|
||||||
|
/** 渠道名:{@code IN_STORE}(到店) / {@code ONLINE}(线上)。 */ |
||||||
|
@JsonProperty("channelName") |
||||||
|
public String channelName; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货包裹 / 面单分组。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ReturnLineGroup { |
||||||
|
|
||||||
|
/** 分组号。 */ |
||||||
|
@JsonProperty("groupNo") |
||||||
|
public Integer groupNo; |
||||||
|
|
||||||
|
/** 组内退货行。 */ |
||||||
|
@JsonProperty("returnLines") |
||||||
|
public List<GroupReturnLine> returnLines; |
||||||
|
|
||||||
|
/** 面单列表。 */ |
||||||
|
@JsonProperty("labels") |
||||||
|
public List<Label> labels; |
||||||
|
|
||||||
|
/** 是否预期退回商品。 */ |
||||||
|
@JsonProperty("returnExpectedFlag") |
||||||
|
public Boolean returnExpectedFlag; |
||||||
|
} |
||||||
|
|
||||||
|
/** 组内退货行:这里只有行号,明细在 {@code returnOrderLines}。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class GroupReturnLine { |
||||||
|
|
||||||
|
/** 退货行号。 */ |
||||||
|
@JsonProperty("returnOrderLineNumber") |
||||||
|
public Integer returnOrderLineNumber; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货面单。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Label { |
||||||
|
|
||||||
|
/** 面单图片 URL。 */ |
||||||
|
@JsonProperty("labelImageURL") |
||||||
|
public String labelImageURL; |
||||||
|
|
||||||
|
/** 承运商信息列表。 */ |
||||||
|
@JsonProperty("carrierInfoList") |
||||||
|
public List<CarrierInfo> carrierInfoList; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货承运商信息。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class CarrierInfo { |
||||||
|
|
||||||
|
/** 承运商 ID。 */ |
||||||
|
@JsonProperty("carrierId") |
||||||
|
public String carrierId; |
||||||
|
|
||||||
|
/** 承运商名称,如 {@code FEDEX}。 */ |
||||||
|
@JsonProperty("carrierName") |
||||||
|
public String carrierName; |
||||||
|
|
||||||
|
/** 服务类型,如 {@code FedEx Ground}。 */ |
||||||
|
@JsonProperty("serviceType") |
||||||
|
public String serviceType; |
||||||
|
|
||||||
|
/** 退货物流跟踪号。 */ |
||||||
|
@JsonProperty("trackingNo") |
||||||
|
public String trackingNo; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货行。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ReturnOrderLine { |
||||||
|
|
||||||
|
/** 退货行号;售后单拆分的唯一锚点。 */ |
||||||
|
@JsonProperty("returnOrderLineNumber") |
||||||
|
public Integer returnOrderLineNumber; |
||||||
|
|
||||||
|
/** 原销售订单行号。 */ |
||||||
|
@JsonProperty("salesOrderLineNumber") |
||||||
|
public Integer salesOrderLineNumber; |
||||||
|
|
||||||
|
/** 退货原因,如 {@code ARRIVED_LATE}。 */ |
||||||
|
@JsonProperty("returnReason") |
||||||
|
public String returnReason; |
||||||
|
|
||||||
|
/** 原沃尔玛订单号。 */ |
||||||
|
@JsonProperty("purchaseOrderId") |
||||||
|
public String purchaseOrderId; |
||||||
|
|
||||||
|
/** 卖家订单号。 */ |
||||||
|
@JsonProperty("sellerOrderId") |
||||||
|
public String sellerOrderId; |
||||||
|
|
||||||
|
/** 原订单行号。 */ |
||||||
|
@JsonProperty("purchaseOrderLineNumber") |
||||||
|
public Integer purchaseOrderLineNumber; |
||||||
|
|
||||||
|
/** 商品。 */ |
||||||
|
@JsonProperty("item") |
||||||
|
public Item item; |
||||||
|
|
||||||
|
/** 退货数量;{@code measurementValue} 是数字。 */ |
||||||
|
@JsonProperty("quantity") |
||||||
|
public Measure quantity; |
||||||
|
|
||||||
|
/** 单价。 */ |
||||||
|
@JsonProperty("unitPrice") |
||||||
|
public CurrencyAmount unitPrice; |
||||||
|
|
||||||
|
/** 费用明细。 */ |
||||||
|
@JsonProperty("charges") |
||||||
|
public List<Charge> charges; |
||||||
|
|
||||||
|
/** 行金额汇总({@code name} + {@code value})。 */ |
||||||
|
@JsonProperty("chargeTotals") |
||||||
|
public List<ChargeTotal> chargeTotals; |
||||||
|
|
||||||
|
/** 当前物流状态。 */ |
||||||
|
@JsonProperty("currentDeliveryStatus") |
||||||
|
public String currentDeliveryStatus; |
||||||
|
|
||||||
|
/** 当前退款状态。 */ |
||||||
|
@JsonProperty("currentRefundStatus") |
||||||
|
public String currentRefundStatus; |
||||||
|
|
||||||
|
/** 退款渠道。 */ |
||||||
|
@JsonProperty("refundChannel") |
||||||
|
public String refundChannel; |
||||||
|
|
||||||
|
/** 退款渠道明细。 */ |
||||||
|
@JsonProperty("refundChannels") |
||||||
|
public List<RefundChannel> refundChannels; |
||||||
|
|
||||||
|
/** 已退数量。 */ |
||||||
|
@JsonProperty("refundedQty") |
||||||
|
public BigDecimal refundedQty; |
||||||
|
|
||||||
|
/** 可取消数量。 */ |
||||||
|
@JsonProperty("cancellableQty") |
||||||
|
public BigDecimal cancellableQty; |
||||||
|
|
||||||
|
/** 可再次扣费数量。 */ |
||||||
|
@JsonProperty("rechargeableQty") |
||||||
|
public BigDecimal rechargeableQty; |
||||||
|
|
||||||
|
/** 是否预期退回。 */ |
||||||
|
@JsonProperty("returnExpectedFlag") |
||||||
|
public Boolean returnExpectedFlag; |
||||||
|
|
||||||
|
/** 是否「keep it」售后(客户留货、无需寄回)。 */ |
||||||
|
@JsonProperty("isKeepIt") |
||||||
|
public Boolean isKeepIt; |
||||||
|
|
||||||
|
/** 是否快速换货。 */ |
||||||
|
@JsonProperty("isFastReplacement") |
||||||
|
public Boolean isFastReplacement; |
||||||
|
|
||||||
|
/** 是否该订单最后一个商品。 */ |
||||||
|
@JsonProperty("lastItem") |
||||||
|
public Boolean lastItem; |
||||||
|
|
||||||
|
/** 退货行状态:{@code COMPLETED} / {@code INITIATED} 等。 */ |
||||||
|
@JsonProperty("status") |
||||||
|
public String status; |
||||||
|
|
||||||
|
/** 状态时间,ISO-8601。 */ |
||||||
|
@JsonProperty("statusTime") |
||||||
|
public String statusTime; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货行商品。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Item { |
||||||
|
|
||||||
|
/** 卖家 SKU。 */ |
||||||
|
@JsonProperty("sku") |
||||||
|
public String sku; |
||||||
|
|
||||||
|
/** 商品名称。 */ |
||||||
|
@JsonProperty("productName") |
||||||
|
public String productName; |
||||||
|
|
||||||
|
/** 商品重量;{@code unitOfMeasure} + {@code measurementValue}。 */ |
||||||
|
@JsonProperty("itemWeight") |
||||||
|
public Measure itemWeight; |
||||||
|
} |
||||||
|
|
||||||
|
/** 数量 / 重量:{@code {"unitOfMeasure","measurementValue"}};值与订单接口不同。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Measure { |
||||||
|
|
||||||
|
/** 计量单位,如 {@code EACH}、{@code POUND}。 */ |
||||||
|
@JsonProperty("unitOfMeasure") |
||||||
|
public String unitOfMeasure; |
||||||
|
|
||||||
|
/** 数值;退货接口是数字,不是字符串。 */ |
||||||
|
@JsonProperty("measurementValue") |
||||||
|
public BigDecimal measurementValue; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退货行费用明细。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Charge { |
||||||
|
|
||||||
|
/** 费用类别,如 {@code PRODUCT}。 */ |
||||||
|
@JsonProperty("chargeCategory") |
||||||
|
public String chargeCategory; |
||||||
|
|
||||||
|
/** 费用名称,如 {@code ItemPrice}。 */ |
||||||
|
@JsonProperty("chargeName") |
||||||
|
public String chargeName; |
||||||
|
|
||||||
|
/** 单价金额。 */ |
||||||
|
@JsonProperty("chargePerUnit") |
||||||
|
public CurrencyAmount chargePerUnit; |
||||||
|
|
||||||
|
/** 是否折扣。 */ |
||||||
|
@JsonProperty("isDiscount") |
||||||
|
public Boolean isDiscount; |
||||||
|
|
||||||
|
/** 是否计费。 */ |
||||||
|
@JsonProperty("isBillable") |
||||||
|
public Boolean isBillable; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行金额汇总项;{@code name} 如 {@code lineTotal}、{@code lineProductTaxes}。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ChargeTotal { |
||||||
|
|
||||||
|
/** 汇总项名称。 */ |
||||||
|
@JsonProperty("name") |
||||||
|
public String name; |
||||||
|
|
||||||
|
/** 金额;结构随接口版本变化,按数字接,解析失败由映射层兜底。 */ |
||||||
|
@JsonProperty("value") |
||||||
|
public BigDecimal value; |
||||||
|
} |
||||||
|
|
||||||
|
/** 退款渠道明细。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class RefundChannel { |
||||||
|
|
||||||
|
/** 退款渠道名,如 {@code SELLER_MANUAL_REFUND}、{@code InstantRefund}。 */ |
||||||
|
@JsonProperty("refundChannelName") |
||||||
|
public String refundChannelName; |
||||||
|
|
||||||
|
/** 数量。 */ |
||||||
|
@JsonProperty("quantity") |
||||||
|
public BigDecimal quantity; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,134 @@ |
|||||||
|
package common.ecommerce.walmart.dto; |
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||||
|
|
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛报文结构:查询发货信息({@code GET /v3/orders/{purchaseOrderId}/shipping})。 |
||||||
|
* |
||||||
|
* <p>响应结构与标发请求体同形:{@code orderShipment.orderLines.orderLine[]}, |
||||||
|
* 每个行状态里带 {@code trackingInfo}。</p> |
||||||
|
* |
||||||
|
* <p>⚠ 沙箱实测该路由 404(mock 未实现)。若生产环境也不可用,可直接读订单详情 |
||||||
|
* {@code orderLines[].orderLineStatuses[].trackingInfo}——两种方式数据一致。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartShipmentDtos { |
||||||
|
|
||||||
|
private WalmartShipmentDtos() { |
||||||
|
} |
||||||
|
|
||||||
|
/** 发货信息响应。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class ShipmentResponse { |
||||||
|
|
||||||
|
/** 发货单容器。 */ |
||||||
|
@JsonProperty("orderShipment") |
||||||
|
public OrderShipment orderShipment; |
||||||
|
} |
||||||
|
|
||||||
|
/** 发货单:行数组。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderShipment { |
||||||
|
|
||||||
|
/** 行容器。 */ |
||||||
|
@JsonProperty("orderLines") |
||||||
|
public OrderLines orderLines; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行容器。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLines { |
||||||
|
|
||||||
|
/** 发货行数组。 */ |
||||||
|
@JsonProperty("orderLine") |
||||||
|
public List<OrderLine> orderLine; |
||||||
|
} |
||||||
|
|
||||||
|
/** 发货行。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLine { |
||||||
|
|
||||||
|
/** 订单行号。 */ |
||||||
|
@JsonProperty("lineNumber") |
||||||
|
public String lineNumber; |
||||||
|
|
||||||
|
/** 行状态容器(发货记录在 {@code status=Shipped} 的那条里)。 */ |
||||||
|
@JsonProperty("orderLineStatuses") |
||||||
|
public OrderLineStatuses orderLineStatuses; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行状态容器。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLineStatuses { |
||||||
|
|
||||||
|
/** 行状态数组。 */ |
||||||
|
@JsonProperty("orderLineStatus") |
||||||
|
public List<OrderLineStatus> orderLineStatus; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行状态:发货记录就挂在这里。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class OrderLineStatus { |
||||||
|
|
||||||
|
/** 状态:{@code Shipped} / {@code Delivered} 等。 */ |
||||||
|
@JsonProperty("status") |
||||||
|
public String status; |
||||||
|
|
||||||
|
/** 该状态对应数量。 */ |
||||||
|
@JsonProperty("statusQuantity") |
||||||
|
public Quantity statusQuantity; |
||||||
|
|
||||||
|
/** 物流信息。 */ |
||||||
|
@JsonProperty("trackingInfo") |
||||||
|
public TrackingInfo trackingInfo; |
||||||
|
} |
||||||
|
|
||||||
|
/** 数量:与订单接口同形,{@code amount} 是字符串。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class Quantity { |
||||||
|
|
||||||
|
/** 计量单位。 */ |
||||||
|
@JsonProperty("unitOfMeasurement") |
||||||
|
public String unitOfMeasurement; |
||||||
|
|
||||||
|
/** 数量(字符串)。 */ |
||||||
|
@JsonProperty("amount") |
||||||
|
public String amount; |
||||||
|
} |
||||||
|
|
||||||
|
/** 物流信息。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class TrackingInfo { |
||||||
|
|
||||||
|
/** 发货时间,ISO-8601。 */ |
||||||
|
@JsonProperty("shipDateTime") |
||||||
|
public String shipDateTime; |
||||||
|
|
||||||
|
/** 承运商。 */ |
||||||
|
@JsonProperty("carrierName") |
||||||
|
public CarrierName carrierName; |
||||||
|
|
||||||
|
/** 运输方式编码。 */ |
||||||
|
@JsonProperty("methodCode") |
||||||
|
public String methodCode; |
||||||
|
|
||||||
|
/** 跟踪号。 */ |
||||||
|
@JsonProperty("trackingNumber") |
||||||
|
public String trackingNumber; |
||||||
|
} |
||||||
|
|
||||||
|
/** 承运商:{@code carrier} 与 {@code otherCarrier} 二选一。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class CarrierName { |
||||||
|
|
||||||
|
/** 标准承运商编码,如 {@code UPS}、{@code FedEx}。 */ |
||||||
|
@JsonProperty("carrier") |
||||||
|
public String carrier; |
||||||
|
|
||||||
|
/** 非标准承运商名称。 */ |
||||||
|
@JsonProperty("otherCarrier") |
||||||
|
public String otherCarrier; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,33 @@ |
|||||||
|
package common.ecommerce.walmart.dto; |
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛报文结构:获取令牌({@code POST /v3/token})。 |
||||||
|
* |
||||||
|
* <p>请求体是 form-urlencoded(只有 {@code grant_type}),不需要在这里建模; |
||||||
|
* 这里只描述响应。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartTokenDtos { |
||||||
|
|
||||||
|
private WalmartTokenDtos() { |
||||||
|
} |
||||||
|
|
||||||
|
/** 令牌响应;{@code access_token} 是 JWT,实测约 841 字符。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class TokenResponse { |
||||||
|
|
||||||
|
/** 访问令牌。 */ |
||||||
|
@JsonProperty("access_token") |
||||||
|
public String accessToken; |
||||||
|
|
||||||
|
/** 令牌类型,固定 {@code Bearer}。 */ |
||||||
|
@JsonProperty("token_type") |
||||||
|
public String tokenType; |
||||||
|
|
||||||
|
/** 有效期,单位秒,实测固定 900(15 分钟)。 */ |
||||||
|
@JsonProperty("expires_in") |
||||||
|
public Integer expiresIn; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,138 @@ |
|||||||
|
package common.ecommerce.walmart.enums; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛订单 / 订单行状态。 |
||||||
|
* |
||||||
|
* <p>沃尔玛<b>没有订单级状态字段</b>:文档 §4.1 的 {@code status} 只出现在 |
||||||
|
* {@code orderLineStatuses.orderLineStatus[]} 上。适配器必须自己聚合出订单级状态, |
||||||
|
* 见 {@link #aggregate(Iterable)}。</p> |
||||||
|
* |
||||||
|
* <p>聚合规则(写死,不猜):</p> |
||||||
|
* <ul> |
||||||
|
* <li>所有行都 {@code Cancelled} → {@link #CANCELLED}</li> |
||||||
|
* <li>所有行都 {@code Delivered} → {@link #DELIVERED}</li> |
||||||
|
* <li>所有行都已终结({@code Shipped} / {@code Delivered} / {@code Cancelled} 混合) |
||||||
|
* 且至少有一行发过货 → {@link #SHIPPED}</li> |
||||||
|
* <li>还有 {@code Created} 行(部分发货时也会命中这一条)→ {@link #CREATED}: |
||||||
|
* 仍有未发货的行,调用方要发货;逐行差异看 {@code OrderLine.status()}</li> |
||||||
|
* <li>有 {@code Acknowledged} 且无 {@code Created} → {@link #ACKNOWLEDGED}</li> |
||||||
|
* <li>识别不了 → {@link #UNKNOWN},原值保留在行上</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p>「部分发货」不单独表达:统一模型的状态是字符串原值,没有 PARTIALLY_SHIPPED 这个平台值, |
||||||
|
* 凭空造一个会让下游按平台原值匹配的地方全部失效。需要精确判断时逐行读状态。</p> |
||||||
|
*/ |
||||||
|
public enum WalmartOrderStatus { |
||||||
|
|
||||||
|
/** 新订单,待处理 / 待发货。 */ |
||||||
|
CREATED("Created"), |
||||||
|
/** 已确认,待发货。 */ |
||||||
|
ACKNOWLEDGED("Acknowledged"), |
||||||
|
/** 已发货。 */ |
||||||
|
SHIPPED("Shipped"), |
||||||
|
/** 已送达。 */ |
||||||
|
DELIVERED("Delivered"), |
||||||
|
/** 已取消。 */ |
||||||
|
CANCELLED("Cancelled"), |
||||||
|
/** 无法识别。 */ |
||||||
|
UNKNOWN(null); |
||||||
|
|
||||||
|
/** 平台原始值;{@link #UNKNOWN} 为 null。 */ |
||||||
|
private final String raw; |
||||||
|
|
||||||
|
WalmartOrderStatus(String raw) { |
||||||
|
this.raw = raw; |
||||||
|
} |
||||||
|
|
||||||
|
/** 平台原始状态值;{@link #UNKNOWN} 返回 null。 */ |
||||||
|
public String raw() { |
||||||
|
return raw; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 精确匹配平台原值;不做 {@code contains} 或大小写模糊匹配 |
||||||
|
* ({@code Cancelled} 里含 {@code Cancel},模糊匹配容易把取消的单判成别的)。 |
||||||
|
* |
||||||
|
* @param raw 平台原值,可空 |
||||||
|
* @return 对应枚举;无法识别或空返回 {@link #UNKNOWN} |
||||||
|
*/ |
||||||
|
public static WalmartOrderStatus fromRaw(String raw) { |
||||||
|
if (raw == null) { |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
for (WalmartOrderStatus s : values()) { |
||||||
|
if (s.raw != null && s.raw.equals(raw)) { |
||||||
|
return s; |
||||||
|
} |
||||||
|
} |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 按订单行状态聚合出订单级状态。 |
||||||
|
* |
||||||
|
* @param lineStatuses 各行状态原值(可含 null) |
||||||
|
* @return 聚合后的订单状态;没有任何可识别状态时返回 {@link #UNKNOWN} |
||||||
|
*/ |
||||||
|
public static WalmartOrderStatus aggregate(Iterable<String> lineStatuses) { |
||||||
|
if (lineStatuses == null) { |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
int total = 0; |
||||||
|
int created = 0; |
||||||
|
int acknowledged = 0; |
||||||
|
int shipped = 0; |
||||||
|
int delivered = 0; |
||||||
|
int cancelled = 0; |
||||||
|
int recognized = 0; |
||||||
|
for (String raw : lineStatuses) { |
||||||
|
total++; |
||||||
|
WalmartOrderStatus s = fromRaw(raw); |
||||||
|
switch (s) { |
||||||
|
case CREATED: |
||||||
|
created++; |
||||||
|
recognized++; |
||||||
|
break; |
||||||
|
case ACKNOWLEDGED: |
||||||
|
acknowledged++; |
||||||
|
recognized++; |
||||||
|
break; |
||||||
|
case SHIPPED: |
||||||
|
shipped++; |
||||||
|
recognized++; |
||||||
|
break; |
||||||
|
case DELIVERED: |
||||||
|
delivered++; |
||||||
|
recognized++; |
||||||
|
break; |
||||||
|
case CANCELLED: |
||||||
|
cancelled++; |
||||||
|
recognized++; |
||||||
|
break; |
||||||
|
default: |
||||||
|
break; |
||||||
|
} |
||||||
|
} |
||||||
|
if (total == 0 || recognized == 0) { |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
if (cancelled == total) { |
||||||
|
return CANCELLED; |
||||||
|
} |
||||||
|
if (delivered == total) { |
||||||
|
return DELIVERED; |
||||||
|
} |
||||||
|
if (shipped + delivered + cancelled == total && shipped + delivered > 0) { |
||||||
|
// 全部行都已终结:已发货 / 已送达 / 已取消混合时以「已发货」表达,
|
||||||
|
// 逐行差异看 OrderLine.status(),不做进一步细分以免猜错
|
||||||
|
return SHIPPED; |
||||||
|
} |
||||||
|
if (created > 0) { |
||||||
|
return CREATED; |
||||||
|
} |
||||||
|
if (acknowledged > 0) { |
||||||
|
return ACKNOWLEDGED; |
||||||
|
} |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,103 @@ |
|||||||
|
package common.ecommerce.walmart.enums; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.product.ProductStatus; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛商品状态:{@code publishedStatus} + {@code lifecycleStatus} 的组合。 |
||||||
|
* |
||||||
|
* <p>沃尔玛没有单一的「商品状态」字段,要两个维度一起看:</p> |
||||||
|
* <ul> |
||||||
|
* <li>{@code publishedStatus}:是否发布了,未发布时原因在 {@code unpublishedReasons}</li> |
||||||
|
* <li>{@code lifecycleStatus}:是否还在生命周期内(归档 / 停售后不再销售)</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p>映射到统一 {@link ProductStatus} 的规则:</p> |
||||||
|
* <table> |
||||||
|
* <tr><th>published</th><th>lifecycle</th><th>ProductStatus</th></tr> |
||||||
|
* <tr><td>PUBLISHED</td><td>ACTIVE</td><td>ACTIVE</td></tr> |
||||||
|
* <tr><td>PUBLISHED</td><td>ARCHIVED / RETIRED</td><td>INACTIVE</td></tr> |
||||||
|
* <tr><td>UNPUBLISHED / STAGE / IN_PROGRESS / SYSTEM_PROBLEM</td><td>任意</td><td>INACTIVE</td></tr> |
||||||
|
* <tr><td>其它</td><td>任意</td><td>UNKNOWN</td></tr> |
||||||
|
* </table> |
||||||
|
* |
||||||
|
* <p>统一模型没有「已删除」语义:沃尔玛也不提供删除接口,归档沿用 {@code INACTIVE}。</p> |
||||||
|
*/ |
||||||
|
public enum WalmartPublishedStatus { |
||||||
|
|
||||||
|
/** 已发布,前台可售。 */ |
||||||
|
PUBLISHED("PUBLISHED"), |
||||||
|
/** 未发布,具体原因见 {@code unpublishedReasons}。 */ |
||||||
|
UNPUBLISHED("UNPUBLISHED"), |
||||||
|
/** 沃尔玛系统侧异常导致未能正常发布。 */ |
||||||
|
SYSTEM_PROBLEM("SYSTEM_PROBLEM"), |
||||||
|
/** 发布处理中。 */ |
||||||
|
IN_PROGRESS("IN_PROGRESS"), |
||||||
|
/** 暂存 / 待发布。 */ |
||||||
|
STAGE("STAGE"), |
||||||
|
/** 无法识别。 */ |
||||||
|
UNKNOWN(null); |
||||||
|
|
||||||
|
/** 平台原始值;{@link #UNKNOWN} 为 null。 */ |
||||||
|
private final String raw; |
||||||
|
|
||||||
|
WalmartPublishedStatus(String raw) { |
||||||
|
this.raw = raw; |
||||||
|
} |
||||||
|
|
||||||
|
/** 平台原始值;{@link #UNKNOWN} 返回 null。 */ |
||||||
|
public String raw() { |
||||||
|
return raw; |
||||||
|
} |
||||||
|
|
||||||
|
/** 精确匹配平台原值。 */ |
||||||
|
public static WalmartPublishedStatus fromRaw(String raw) { |
||||||
|
if (raw == null) { |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
for (WalmartPublishedStatus s : values()) { |
||||||
|
if (s.raw != null && s.raw.equals(raw)) { |
||||||
|
return s; |
||||||
|
} |
||||||
|
} |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
|
||||||
|
/** 生命周期是否表示「不再销售」。 */ |
||||||
|
static boolean isRetiredLifecycle(String lifecycleStatus) { |
||||||
|
return "ARCHIVED".equals(lifecycleStatus) || "RETIRED".equals(lifecycleStatus); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 把两个维度归一成统一状态。 |
||||||
|
* |
||||||
|
* @param publishedStatus 平台 {@code publishedStatus} |
||||||
|
* @param lifecycleStatus 平台 {@code lifecycleStatus} |
||||||
|
* @return 统一商品状态,不会为 null |
||||||
|
*/ |
||||||
|
public static ProductStatus toProductStatus(String publishedStatus, String lifecycleStatus) { |
||||||
|
WalmartPublishedStatus published = fromRaw(publishedStatus); |
||||||
|
switch (published) { |
||||||
|
case PUBLISHED: |
||||||
|
return isRetiredLifecycle(lifecycleStatus) ? ProductStatus.INACTIVE : ProductStatus.ACTIVE; |
||||||
|
case UNPUBLISHED: |
||||||
|
case STAGE: |
||||||
|
case IN_PROGRESS: |
||||||
|
case SYSTEM_PROBLEM: |
||||||
|
return ProductStatus.INACTIVE; |
||||||
|
default: |
||||||
|
return ProductStatus.UNKNOWN; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 拼一个稳定的原始状态串,供 {@code ProductListing.rawStatus()} 使用, |
||||||
|
* 例如 {@code "UNPUBLISHED/ACTIVE"}。 |
||||||
|
* |
||||||
|
* @param publishedStatus 平台 {@code publishedStatus} |
||||||
|
* @param lifecycleStatus 平台 {@code lifecycleStatus} |
||||||
|
*/ |
||||||
|
public static String rawStatus(String publishedStatus, String lifecycleStatus) { |
||||||
|
return (publishedStatus == null ? "UNKNOWN" : publishedStatus) |
||||||
|
+ "/" + (lifecycleStatus == null ? "UNKNOWN" : lifecycleStatus); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,60 @@ |
|||||||
|
package common.ecommerce.walmart.enums; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleType; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛退货类型 {@code returnType} → 统一 {@link AfterSaleType}。 |
||||||
|
* |
||||||
|
* <p>沃尔玛只有两种:{@link #RETURN}(退货退款)和 {@link #REPLACEMENT}(换货)。 |
||||||
|
* 换货在统一模型里叫 {@link AfterSaleType#EXCHANGE}。</p> |
||||||
|
* |
||||||
|
* <p>注意 {@code REPLACEMENT} 也会出现在 {@code refundMode} 等其它字段的枚举里, |
||||||
|
* 这里只用于 {@code returnType}。</p> |
||||||
|
*/ |
||||||
|
public enum WalmartReturnType { |
||||||
|
|
||||||
|
/** 退货(退款)。 */ |
||||||
|
RETURN("RETURN", AfterSaleType.RETURN), |
||||||
|
/** 换货 / 补发。 */ |
||||||
|
REPLACEMENT("REPLACEMENT", AfterSaleType.EXCHANGE), |
||||||
|
/** 无法识别。 */ |
||||||
|
UNKNOWN(null, AfterSaleType.UNKNOWN); |
||||||
|
|
||||||
|
/** 平台原始值。 */ |
||||||
|
private final String raw; |
||||||
|
/** 统一类型。 */ |
||||||
|
private final AfterSaleType core; |
||||||
|
|
||||||
|
WalmartReturnType(String raw, AfterSaleType core) { |
||||||
|
this.raw = raw; |
||||||
|
this.core = core; |
||||||
|
} |
||||||
|
|
||||||
|
/** 平台原始值;{@link #UNKNOWN} 返回 null。 */ |
||||||
|
public String raw() { |
||||||
|
return raw; |
||||||
|
} |
||||||
|
|
||||||
|
/** 统一售后类型。 */ |
||||||
|
public AfterSaleType toCore() { |
||||||
|
return core; |
||||||
|
} |
||||||
|
|
||||||
|
/** 精确匹配平台原值;空或无法识别返回 {@link #UNKNOWN}。 */ |
||||||
|
public static WalmartReturnType fromRaw(String raw) { |
||||||
|
if (raw == null) { |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
for (WalmartReturnType t : values()) { |
||||||
|
if (t.raw != null && t.raw.equals(raw)) { |
||||||
|
return t; |
||||||
|
} |
||||||
|
} |
||||||
|
return UNKNOWN; |
||||||
|
} |
||||||
|
|
||||||
|
/** 便捷方法:直接取统一类型。 */ |
||||||
|
public static AfterSaleType toCore(String raw) { |
||||||
|
return fromRaw(raw).toCore(); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,165 @@ |
|||||||
|
package common.ecommerce.walmart.http; |
||||||
|
|
||||||
|
import common.ecommerce.channel.sdk.ChannelContext; |
||||||
|
import common.ecommerce.http.HttpResponse; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.shared.error.AuthException; |
||||||
|
import common.ecommerce.shared.error.ChannelException; |
||||||
|
import common.ecommerce.shared.error.RateLimitException; |
||||||
|
import common.ecommerce.shared.error.TransientException; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛错误解析。 |
||||||
|
* |
||||||
|
* <p>沙箱观察到两种错误格式,必须都认:</p> |
||||||
|
* <ol> |
||||||
|
* <li><b>业务网关错误</b>:{@code {"error":[{"code":"CONTENT_NOT_FOUND.GMP_GATEWAY_API", |
||||||
|
* "description":"...","info":"...","severity":"INFO","category":"APPLICATION"}]}}</li> |
||||||
|
* <li><b>路由级错误</b>:{@code {"timestamp":"...","status":404,"error":"Request Not Found...","path":"..."}}</li> |
||||||
|
* </ol> |
||||||
|
* |
||||||
|
* <p>不用 {@code Responses.throwIfNotSuccess}:它只看状态码,拿不到 body 里的 |
||||||
|
* {@code code} / {@code description},排障时只能看到 {@code http 400 on xxx}。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartErrors { |
||||||
|
|
||||||
|
private final JacksonJsonCodec json; |
||||||
|
|
||||||
|
public WalmartErrors(JacksonJsonCodec json) { |
||||||
|
this.json = json; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 非 2xx 时抛对应异常,2xx 直接返回。 |
||||||
|
* |
||||||
|
* <p>分类:</p> |
||||||
|
* <ul> |
||||||
|
* <li>401 / 403 → {@link AuthException}(调用方刷新后重试一次)</li> |
||||||
|
* <li>429 → {@link RateLimitException},遵守 {@code Retry-After}</li> |
||||||
|
* <li>5xx → {@link TransientException},{@code retryable=true}</li> |
||||||
|
* <li>其它 4xx → {@link ValidationException},不重试</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p>沃尔玛业务错误码里的 {@code SYSTEM_ERROR.GMP_*} 也按可重试处理, |
||||||
|
* 即便 HTTP 是 4xx——这类是平台侧数据状态问题,原样重跑常能成功。</p> |
||||||
|
*/ |
||||||
|
public void throwIfError(HttpResponse response, ChannelContext ctx, String operation) { |
||||||
|
if (response.isSuccess()) { |
||||||
|
return; |
||||||
|
} |
||||||
|
|
||||||
|
String code = null; |
||||||
|
String description = null; |
||||||
|
String severity = null; |
||||||
|
JsonNode root = parse(response.body()); |
||||||
|
if (root != null) { |
||||||
|
JsonNode errors = root.get("error"); |
||||||
|
if (errors != null && errors.isArray() && errors.size() > 0) { |
||||||
|
JsonNode first = errors.get(0); |
||||||
|
code = text(first, "code"); |
||||||
|
description = text(first, "description"); |
||||||
|
severity = text(first, "severity"); |
||||||
|
String info = text(first, "info"); |
||||||
|
if (description == null) { |
||||||
|
description = info; |
||||||
|
} |
||||||
|
} else { |
||||||
|
// 格式二:路由级错误,没有 error 数组
|
||||||
|
description = text(root, "error"); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
ChannelException.Builder b = ChannelException.builder() |
||||||
|
.message(buildMessage(response, operation, code, description, severity)) |
||||||
|
.operation(operation) |
||||||
|
.platform(ctx.platform()) |
||||||
|
.provider(ctx.providerName()) |
||||||
|
.omsStoreId(ctx.omsStoreId()) |
||||||
|
.requestId(ctx.requestId()) |
||||||
|
.platformCode(code != null ? code : String.valueOf(response.statusCode())) |
||||||
|
.rawResponse(truncate(response.body())); |
||||||
|
|
||||||
|
int status = response.statusCode(); |
||||||
|
if (response.isAuthFailure()) { |
||||||
|
throw new AuthException(b); |
||||||
|
} |
||||||
|
if (response.isRateLimited()) { |
||||||
|
throw new RateLimitException(b, parseRetryAfterMillis(response.header("Retry-After"))); |
||||||
|
} |
||||||
|
if (response.isServerError()) { |
||||||
|
throw new TransientException(b.retryable(true), null); |
||||||
|
} |
||||||
|
if (isSystemError(code)) { |
||||||
|
throw new TransientException(b.retryable(true), null); |
||||||
|
} |
||||||
|
// 其余 4xx 一律按「数据/参数错误,重跑也不会成功」处理。
|
||||||
|
// 不猜 {@code INVALID_STATE} / {@code CONFLICT} 这类前缀:文档实测只给了
|
||||||
|
// CONTENT_NOT_FOUND.* 与 SYSTEM_ERROR.*,凭前缀分类会把可重试错误判成终态。
|
||||||
|
throw new ValidationException(b); |
||||||
|
} |
||||||
|
|
||||||
|
/** 沃尔玛的 {@code SYSTEM_ERROR.*} 是平台侧问题,可重试。 */ |
||||||
|
static boolean isSystemError(String code) { |
||||||
|
return code != null && code.startsWith("SYSTEM_ERROR"); |
||||||
|
} |
||||||
|
|
||||||
|
/** 拼接一条既能定位又能看懂的异常消息。 */ |
||||||
|
private static String buildMessage(HttpResponse response, String operation, |
||||||
|
String code, String description, String severity) { |
||||||
|
StringBuilder sb = new StringBuilder("walmart http ").append(response.statusCode()) |
||||||
|
.append(" on ").append(operation); |
||||||
|
if (code != null) { |
||||||
|
sb.append(" [").append(code).append(']'); |
||||||
|
} |
||||||
|
if (description != null) { |
||||||
|
sb.append(": ").append(description); |
||||||
|
} |
||||||
|
if (severity != null && !"ERROR".equalsIgnoreCase(severity)) { |
||||||
|
sb.append(" (severity=").append(severity).append(')'); |
||||||
|
} |
||||||
|
return sb.toString(); |
||||||
|
} |
||||||
|
|
||||||
|
/** Retry-After 只支持秒数;解析失败给 1s 默认值,避免 0 导致无退避重试。 */ |
||||||
|
static long parseRetryAfterMillis(String raw) { |
||||||
|
if (raw == null || raw.trim().isEmpty()) { |
||||||
|
return 1_000L; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Math.max(0L, Long.parseLong(raw.trim()) * 1000L); |
||||||
|
} catch (NumberFormatException e) { |
||||||
|
return 1_000L; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** 原始报文截断,避免整页 JSON 进日志/异常。 */ |
||||||
|
static String truncate(String body) { |
||||||
|
if (body == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
return body.length() <= WalmartConstants.RAW_RESPONSE_LIMIT |
||||||
|
? body : body.substring(0, WalmartConstants.RAW_RESPONSE_LIMIT); |
||||||
|
} |
||||||
|
|
||||||
|
private JsonNode parse(String body) { |
||||||
|
if (body == null || body.trim().isEmpty()) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return json.mapper().readTree(body); |
||||||
|
} catch (Exception e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private static String text(JsonNode node, String field) { |
||||||
|
if (node == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
JsonNode value = node.get(field); |
||||||
|
return value == null || value.isNull() ? null : value.asText(); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,130 @@ |
|||||||
|
package common.ecommerce.walmart.http; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.channel.sdk.ChannelContext; |
||||||
|
import common.ecommerce.shared.spi.AccessToken; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
|
||||||
|
import java.io.UnsupportedEncodingException; |
||||||
|
import java.net.URLEncoder; |
||||||
|
import java.util.LinkedHashMap; |
||||||
|
import java.util.Map; |
||||||
|
|
||||||
|
/** |
||||||
|
* 构造沃尔玛请求:公共头 + 令牌头 + 链路 ID。 |
||||||
|
* |
||||||
|
* <p>沃尔玛不需要签名,鉴权只靠 {@code WM_SEC.ACCESS_TOKEN} 头; |
||||||
|
* 业务接口<b>不再</b>带 Basic Auth(沙箱实测确认)。</p> |
||||||
|
* |
||||||
|
* <p>query 参数按插入顺序拼接,null 值跳过;游标类参数由调用方决定是否编码, |
||||||
|
* 因为退货接口的 {@code nextCursor} 本身就是一段带 {@code ?} 的查询串。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartRequestFactory { |
||||||
|
|
||||||
|
/** 无状态;请求体序列化由各 DTO 与 JacksonJsonCodec 承担,本类只管 URL 与请求头。 */ |
||||||
|
public WalmartRequestFactory() { |
||||||
|
} |
||||||
|
|
||||||
|
/** GET 业务请求;{@code query} 为 null 或空时不拼 {@code ?}。 */ |
||||||
|
public HttpRequest get(String baseUrl, String path, Map<String, Object> query, |
||||||
|
AccessToken token, ChannelContext ctx, String operation) { |
||||||
|
return HttpRequest.builder() |
||||||
|
.method("GET") |
||||||
|
.url(baseUrl + path + queryString(query)) |
||||||
|
.header(WalmartConstants.HEADER_SVC_NAME, WalmartConstants.SVC_NAME_VALUE) |
||||||
|
.header(WalmartConstants.HEADER_CORRELATION_ID, ctx.requestId()) |
||||||
|
.header(WalmartConstants.HEADER_ACCESS_TOKEN, token.value()) |
||||||
|
.header("Accept", WalmartConstants.CONTENT_TYPE_JSON) |
||||||
|
.operation(operation) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 用一段<b>已拼好的查询串</b>发 GET。 |
||||||
|
* |
||||||
|
* <p>退货列表的 {@code meta.nextCursor} 形如 {@code ?sellerId=151&limit=10&offset=10}, |
||||||
|
* 翻页时整串拼到路径后面,不能再做 URL 编码,也不能重复加 {@code ?}。</p> |
||||||
|
* |
||||||
|
* @param rawQuery 查询串,可带或不带开头的 {@code ?};null / 空表示无。 |
||||||
|
* 以 {@code &} 开头的串会被归一成 {@code ?} + 余下部分—— |
||||||
|
* 直接拼 {@code path + "&k=v"} 会生成没有 {@code ?} 的非法 URL。 |
||||||
|
*/ |
||||||
|
public HttpRequest getWithRawQuery(String baseUrl, String path, String rawQuery, |
||||||
|
AccessToken token, ChannelContext ctx, String operation) { |
||||||
|
String query = normalizeRawQuery(rawQuery); |
||||||
|
return HttpRequest.builder() |
||||||
|
.method("GET") |
||||||
|
.url(baseUrl + path + (query == null ? "" : query)) |
||||||
|
.header(WalmartConstants.HEADER_SVC_NAME, WalmartConstants.SVC_NAME_VALUE) |
||||||
|
.header(WalmartConstants.HEADER_CORRELATION_ID, ctx.requestId()) |
||||||
|
.header(WalmartConstants.HEADER_ACCESS_TOKEN, token.value()) |
||||||
|
.header("Accept", WalmartConstants.CONTENT_TYPE_JSON) |
||||||
|
.operation(operation) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 归一原始查询串:空串 → null;不以 {@code ?} 开头时补上;开头的 {@code &} 去掉。 |
||||||
|
* |
||||||
|
* @param rawQuery 平台的 {@code nextCursor} 或调用方拼的查询串 |
||||||
|
*/ |
||||||
|
static String normalizeRawQuery(String rawQuery) { |
||||||
|
if (rawQuery == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
String query = rawQuery.trim(); |
||||||
|
if (query.isEmpty()) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
if (query.charAt(0) == '&') { |
||||||
|
// "&a=1&b=2" → "?a=1&b=2"
|
||||||
|
return "?" + query.substring(1); |
||||||
|
} |
||||||
|
return query.charAt(0) == '?' ? query : "?" + query; |
||||||
|
} |
||||||
|
|
||||||
|
/** 把查询参数拼成 {@code ?k=v&k2=v2};空 Map 返回空串。 */ |
||||||
|
public static String queryString(Map<String, Object> query) { |
||||||
|
if (query == null || query.isEmpty()) { |
||||||
|
return ""; |
||||||
|
} |
||||||
|
StringBuilder sb = new StringBuilder(); |
||||||
|
for (Map.Entry<String, Object> e : query.entrySet()) { |
||||||
|
if (e.getValue() == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
sb.append(sb.length() == 0 ? '?' : '&') |
||||||
|
.append(urlEncode(e.getKey())) |
||||||
|
.append('=') |
||||||
|
.append(urlEncode(String.valueOf(e.getValue()))); |
||||||
|
} |
||||||
|
return sb.toString(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 新建有序 query 容器;便于测试断言参数顺序。 */ |
||||||
|
public static Map<String, Object> query() { |
||||||
|
return new LinkedHashMap<String, Object>(); |
||||||
|
} |
||||||
|
|
||||||
|
/** UTF-8 URL 编码;{@link URLEncoder} 把空格编成 {@code +},对 query 而言是合法的。 */ |
||||||
|
public static String urlEncode(String value) { |
||||||
|
if (value == null) { |
||||||
|
return ""; |
||||||
|
} |
||||||
|
try { |
||||||
|
return URLEncoder.encode(value, "UTF-8"); |
||||||
|
} catch (UnsupportedEncodingException e) { |
||||||
|
// UTF-8 一定存在
|
||||||
|
throw new IllegalStateException("UTF-8 not supported", e); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** 路径段编码:{@link #urlEncode(String)} 但把 {@code +} 还原成 {@code %20}。 |
||||||
|
* |
||||||
|
* <p>路径里的 {@code +} 是字面量加号,不是空格;SKU / 订单号里带空格时 |
||||||
|
* 用 query 编码会拼出错误的路径。</p> |
||||||
|
*/ |
||||||
|
public static String pathSegment(String value) { |
||||||
|
return urlEncode(value).replace("+", "%20"); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,422 @@ |
|||||||
|
package common.ecommerce.walmart.mapper; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.order.OrderLine; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrder; |
||||||
|
import common.ecommerce.channel.model.order.ShipToAddress; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.support.Money; |
||||||
|
import common.ecommerce.shared.support.PlatformTime; |
||||||
|
import common.ecommerce.walmart.dto.WalmartOrderDtos; |
||||||
|
|
||||||
|
import java.math.BigDecimal; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneId; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.Collections; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛订单 → 统一 {@link SalesOrder}。 |
||||||
|
* |
||||||
|
* <p>只做字段搬运与必要的单位/格式转换,不做业务判断:</p> |
||||||
|
* <ul> |
||||||
|
* <li>时间:订单接口是 epoch 毫秒,统一转 {@link PlatformTime}</li> |
||||||
|
* <li>数量:{@code orderLineQuantity.amount} 是字符串,解析失败记 0 而不是抛异常, |
||||||
|
* 避免一行脏数据卡住整页同步</li> |
||||||
|
* <li>单价:沃尔玛的 {@code ItemPrice.chargeAmount} 是<b>整行金额</b>, |
||||||
|
* 必须除以行数量才是 {@link OrderLine#unitPrice()};数量为 0 时无法拆分, |
||||||
|
* 保留整行金额(此时它等于单价,因为只有 1 件)</li> |
||||||
|
* <li>行税额:取该行所有 charge 上 {@code tax.taxAmount} 的合计</li> |
||||||
|
* <li>订单总额:按行合计(商品金额 + 税),币种取第一个非空币种</li> |
||||||
|
* </ul> |
||||||
|
*/ |
||||||
|
public final class WalmartOrderMapper { |
||||||
|
|
||||||
|
private WalmartOrderMapper() { |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 映射一个订单。 |
||||||
|
* |
||||||
|
* <p><b>不完整的订单返回 null</b>,由调用方跳过并记一条 WARN: |
||||||
|
* {@code purchaseOrderId} 与 {@code orderDate} 在统一模型里是必填 |
||||||
|
* (前者进 canonicalKey,后者进 {@code occurredAt}),平台漏给时硬造一个值 |
||||||
|
* 会把脏数据写进主键。宁可少一条,也不能写错一条。</p> |
||||||
|
* |
||||||
|
* @param dto 平台订单 |
||||||
|
* @param omsStoreId 宿主店铺 ID |
||||||
|
* @param marketplaceZone 市场时区,用于 {@link PlatformTime} |
||||||
|
* @return 统一订单;{@code dto} 为 null、缺订单号或缺下单时间时返回 null |
||||||
|
*/ |
||||||
|
public static SalesOrder toSalesOrder(WalmartOrderDtos.Order dto, String omsStoreId, |
||||||
|
ZoneId marketplaceZone) { |
||||||
|
if (dto == null || isBlank(dto.purchaseOrderId) || dto.orderDate == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
List<OrderLine> lines = toOrderLines(dto); |
||||||
|
return SalesOrder.builder() |
||||||
|
.omsStoreId(omsStoreId) |
||||||
|
.channelOrderId(dto.purchaseOrderId) |
||||||
|
.status(statusOf(dto)) |
||||||
|
.buyerName(dto.shippingInfo == null || dto.shippingInfo.postalAddress == null |
||||||
|
? null : dto.shippingInfo.postalAddress.name) |
||||||
|
.buyerEmail(dto.customerEmailId) |
||||||
|
.shipToCountryCode(countryCodeOf(dto)) |
||||||
|
.shipToAddress(toShipToAddress(dto)) |
||||||
|
.lines(lines) |
||||||
|
.totalAmount(totalOf(dto)) |
||||||
|
.occurredAt(toPlatformTime(dto.orderDate, marketplaceZone)) |
||||||
|
.sourceProvider(ChannelProvider.DIRECT) |
||||||
|
.sourceAccountId(null) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 平台必填字段缺失时的判定;只 trim,不做其它归一。 */ |
||||||
|
private static boolean isBlank(String value) { |
||||||
|
return value == null || value.trim().isEmpty(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 订单级状态:沃尔玛没有这个字段,按行状态聚合。 |
||||||
|
* |
||||||
|
* <p>一行的 {@code orderLineStatus[]} 不是纯历史:部分发货时 |
||||||
|
* {@code Created(3)} 与 {@code Shipped(1)} 会同时存在,数量各不相同。所以先按数量 |
||||||
|
* 把每行<b>归一</b>成一个当前状态(见 {@link #resolveLineStatus}),再交给 |
||||||
|
* {@link common.ecommerce.walmart.enums.WalmartOrderStatus#aggregate}。</p> |
||||||
|
* |
||||||
|
* @see common.ecommerce.walmart.enums.WalmartOrderStatus#aggregate(Iterable) |
||||||
|
*/ |
||||||
|
static String statusOf(WalmartOrderDtos.Order dto) { |
||||||
|
if (dto.orderLines == null || dto.orderLines.orderLine == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
List<String> statuses = new ArrayList<String>(); |
||||||
|
for (WalmartOrderDtos.OrderLine line : dto.orderLines.orderLine) { |
||||||
|
if (line == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
String resolved = resolveLineStatus(line); |
||||||
|
if (resolved != null) { |
||||||
|
statuses.add(resolved); |
||||||
|
} |
||||||
|
} |
||||||
|
return common.ecommerce.walmart.enums.WalmartOrderStatus.aggregate(statuses).raw(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 按订单行数量把行状态归一成一个「当前」状态。 |
||||||
|
* |
||||||
|
* <p>规则(数量缺失时退化为「取状态列表最后一条」):</p> |
||||||
|
* <ol> |
||||||
|
* <li>取消数量 ≥ 订量 → {@code Cancelled}</li> |
||||||
|
* <li>发货数量({@code Shipped} + {@code Delivered})≥ 订量 - 取消数量: |
||||||
|
* 全部 {@code Delivered} 时给 {@code Delivered},否则 {@code Shipped}</li> |
||||||
|
* <li>还有没发的余量 → {@code Created}(订单层面仍需发货动作)</li> |
||||||
|
* <li>什么都不匹配 → 状态列表最后一条的原值</li> |
||||||
|
* </ol> |
||||||
|
* |
||||||
|
* <p>{@code OrderLine.status()} 保留的是<b>平台原值</b>(状态列表最后一条), |
||||||
|
* 需要判断「这一行还差多少没发」时以 {@link #resolveLineStatus} 的结果为准。</p> |
||||||
|
*/ |
||||||
|
static String resolveLineStatus(WalmartOrderDtos.OrderLine line) { |
||||||
|
int ordered = parseQuantity(line.orderLineQuantity); |
||||||
|
if (ordered <= 0 || line.orderLineStatuses == null |
||||||
|
|| line.orderLineStatuses.orderLineStatus == null) { |
||||||
|
return currentLineStatus(line); |
||||||
|
} |
||||||
|
int shipped = 0; |
||||||
|
int delivered = 0; |
||||||
|
int cancelled = 0; |
||||||
|
boolean anyQuantity = false; |
||||||
|
for (WalmartOrderDtos.OrderLineStatus s : line.orderLineStatuses.orderLineStatus) { |
||||||
|
if (s == null || s.status == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
int qty = parseQuantity(s.statusQuantity); |
||||||
|
if (qty > 0) { |
||||||
|
anyQuantity = true; |
||||||
|
} |
||||||
|
if ("Shipped".equals(s.status)) { |
||||||
|
shipped += qty; |
||||||
|
} else if ("Delivered".equals(s.status)) { |
||||||
|
delivered += qty; |
||||||
|
} else if ("Cancelled".equals(s.status)) { |
||||||
|
cancelled += qty; |
||||||
|
} |
||||||
|
} |
||||||
|
if (!anyQuantity) { |
||||||
|
return currentLineStatus(line); |
||||||
|
} |
||||||
|
if (cancelled >= ordered) { |
||||||
|
return "Cancelled"; |
||||||
|
} |
||||||
|
int fulfilled = shipped + delivered; |
||||||
|
int expected = ordered - cancelled; |
||||||
|
if (fulfilled >= expected) { |
||||||
|
return delivered >= expected ? "Delivered" : "Shipped"; |
||||||
|
} |
||||||
|
return "Created"; |
||||||
|
} |
||||||
|
|
||||||
|
/** 收货地址;平台未返回地址时返回 null(全空对象不挂到订单上)。 */ |
||||||
|
static ShipToAddress toShipToAddress(WalmartOrderDtos.Order dto) { |
||||||
|
if (dto.shippingInfo == null || dto.shippingInfo.postalAddress == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
WalmartOrderDtos.PostalAddress a = dto.shippingInfo.postalAddress; |
||||||
|
ShipToAddress address = ShipToAddress.builder() |
||||||
|
.name(a.name) |
||||||
|
.address1(a.address1) |
||||||
|
.address2(a.address2) |
||||||
|
.city(a.city) |
||||||
|
.state(a.state) |
||||||
|
.postalCode(a.postalCode) |
||||||
|
.countryCode(a.country) |
||||||
|
.addressType(a.addressType) |
||||||
|
.phone(dto.shippingInfo.phone) |
||||||
|
.build(); |
||||||
|
return address.isEmpty() ? null : address; |
||||||
|
} |
||||||
|
|
||||||
|
/** 收货国家:优先地址里的国家;没有地址时返回 null。 */ |
||||||
|
static String countryCodeOf(WalmartOrderDtos.Order dto) { |
||||||
|
return dto.shippingInfo == null || dto.shippingInfo.postalAddress == null |
||||||
|
? null : dto.shippingInfo.postalAddress.country; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 订单总额:逐行商品金额 + 税合计;一行都算不出来时返回 null。 |
||||||
|
* |
||||||
|
* <p><b>币种不一致时返回 null</b>:沃尔玛一个订单只有一个币种, |
||||||
|
* 出现两个说明数据有问题;把不同币种直接相加会得到一个无意义的数。</p> |
||||||
|
*/ |
||||||
|
static Money totalOf(WalmartOrderDtos.Order dto) { |
||||||
|
if (dto.orderLines == null || dto.orderLines.orderLine == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
BigDecimal total = BigDecimal.ZERO; |
||||||
|
String currency = null; |
||||||
|
boolean any = false; |
||||||
|
for (WalmartOrderDtos.OrderLine line : dto.orderLines.orderLine) { |
||||||
|
if (line == null || line.charges == null || line.charges.charge == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
for (WalmartOrderDtos.Charge charge : line.charges.charge) { |
||||||
|
if (charge == null || charge.chargeAmount == null || charge.chargeAmount.amount == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
if (charge.chargeAmount.currency == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
if (currency == null) { |
||||||
|
currency = charge.chargeAmount.currency; |
||||||
|
} else if (!currency.equals(charge.chargeAmount.currency)) { |
||||||
|
// 同单多币种:数据异常,宁可不给总额,也不给一个加错的数
|
||||||
|
return null; |
||||||
|
} |
||||||
|
total = total.add(charge.chargeAmount.amount); |
||||||
|
any = true; |
||||||
|
if (charge.tax != null && charge.tax.taxAmount != null |
||||||
|
&& charge.tax.taxAmount.amount != null) { |
||||||
|
total = total.add(charge.tax.taxAmount.amount); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
if (!any) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Money.of(total, currency); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
// 平台给了非法币种代码:不阻断整页,按「金额不可用」处理
|
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单行。 */ |
||||||
|
static List<OrderLine> toOrderLines(WalmartOrderDtos.Order dto) { |
||||||
|
if (dto.orderLines == null || dto.orderLines.orderLine == null) { |
||||||
|
return Collections.emptyList(); |
||||||
|
} |
||||||
|
List<OrderLine> out = new ArrayList<OrderLine>(dto.orderLines.orderLine.size()); |
||||||
|
for (WalmartOrderDtos.OrderLine line : dto.orderLines.orderLine) { |
||||||
|
if (line == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
int quantity = parseQuantity(line.orderLineQuantity); |
||||||
|
out.add(OrderLine.builder() |
||||||
|
.lineId(line.lineNumber) |
||||||
|
.platformSku(line.item == null || line.item.sku == null ? "" : line.item.sku) |
||||||
|
.quantity(quantity) |
||||||
|
.lineAmount(lineAmountOf(line)) |
||||||
|
.unitPrice(unitPriceOf(line, quantity)) |
||||||
|
.tax(taxOf(line)) |
||||||
|
.status(currentLineStatus(line)) |
||||||
|
.build()); |
||||||
|
} |
||||||
|
return out; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行当前状态:取状态列表里最后一条。 */ |
||||||
|
static String currentLineStatus(WalmartOrderDtos.OrderLine line) { |
||||||
|
if (line.orderLineStatuses == null || line.orderLineStatuses.orderLineStatus == null |
||||||
|
|| line.orderLineStatuses.orderLineStatus.isEmpty()) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
List<WalmartOrderDtos.OrderLineStatus> list = line.orderLineStatuses.orderLineStatus; |
||||||
|
for (int i = list.size() - 1; i >= 0; i--) { |
||||||
|
WalmartOrderDtos.OrderLineStatus s = list.get(i); |
||||||
|
if (s != null && s.status != null) { |
||||||
|
return s.status; |
||||||
|
} |
||||||
|
} |
||||||
|
return null; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 行<b>金额</b>:{@code ItemPrice.chargeAmount} 原值,不做任何除法。 |
||||||
|
* |
||||||
|
* <p>这是金额的权威来源;{@link #unitPriceOf} 由它派生,除不尽时会给 null。</p> |
||||||
|
*/ |
||||||
|
static Money lineAmountOf(WalmartOrderDtos.OrderLine line) { |
||||||
|
BigDecimal amount = itemPriceTotalOf(line); |
||||||
|
String currency = itemPriceCurrencyOf(line); |
||||||
|
if (amount == null || currency == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Money.of(amount, currency); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 商品<b>单价</b>:由行金额除以数量得到,<b>除不尽时为 null</b>。 |
||||||
|
* |
||||||
|
* <p>示例:2 件共 99.98 → 单价 49.99,可精确表示;3 件共 100.00 → 33.3333…, |
||||||
|
* 除不尽,返回 null——用 33.3333 会让人误以为 {@code ×3} 等于原金额, |
||||||
|
* 实际差 0.0001。需要行金额时用 {@link OrderLine#lineAmount()}。</p> |
||||||
|
* |
||||||
|
* <p>数量缺失或为 0 时不拆:只有 1 件(或数量未知)时行金额即单价。</p> |
||||||
|
*/ |
||||||
|
static Money unitPriceOf(WalmartOrderDtos.OrderLine line, int quantity) { |
||||||
|
Money amount = lineAmountOf(line); |
||||||
|
if (amount == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
if (quantity <= 1) { |
||||||
|
return amount; |
||||||
|
} |
||||||
|
BigDecimal divisor = BigDecimal.valueOf(quantity); |
||||||
|
// 先按 4 位小数试除,再回乘校验:只有 unitPrice × quantity 精确等于行金额才认可
|
||||||
|
BigDecimal unit = amount.amount().divide(divisor, 4, java.math.RoundingMode.HALF_UP); |
||||||
|
if (unit.multiply(divisor).compareTo(amount.amount()) != 0) { |
||||||
|
// 除不尽:不四舍五入倒推,避免单价 × 数量 ≠ 行金额
|
||||||
|
return null; |
||||||
|
} |
||||||
|
return Money.of(unit.stripTrailingZeros(), amount.currencyCode()); |
||||||
|
} |
||||||
|
|
||||||
|
/** {@code ItemPrice} 的整行金额;没有则该行第一条带金额的 charge。 */ |
||||||
|
static BigDecimal itemPriceTotalOf(WalmartOrderDtos.OrderLine line) { |
||||||
|
WalmartOrderDtos.Charge charge = itemPriceChargeOf(line); |
||||||
|
return charge == null || charge.chargeAmount == null ? null : charge.chargeAmount.amount; |
||||||
|
} |
||||||
|
|
||||||
|
/** 与 {@link #itemPriceTotalOf} 同一条 charge 上的币种。 */ |
||||||
|
static String itemPriceCurrencyOf(WalmartOrderDtos.OrderLine line) { |
||||||
|
WalmartOrderDtos.Charge charge = itemPriceChargeOf(line); |
||||||
|
return charge == null || charge.chargeAmount == null ? null : charge.chargeAmount.currency; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 行金额对应的 charge:优先 {@code ItemPrice},其次<b>同类型商品费</b>。 |
||||||
|
* |
||||||
|
* <p><b>不把运费 / 手续费当商品价</b>:只有 {@code chargeType=PRODUCT} 的 charge |
||||||
|
* 才能退而求其次;一条商品费都没有时返回 null,让单价保持 null, |
||||||
|
* 而不是把 {@code Shipping} 的金额除以数量冒充单价。</p> |
||||||
|
*/ |
||||||
|
static WalmartOrderDtos.Charge itemPriceChargeOf(WalmartOrderDtos.OrderLine line) { |
||||||
|
if (line.charges == null || line.charges.charge == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
WalmartOrderDtos.Charge productFallback = null; |
||||||
|
for (WalmartOrderDtos.Charge charge : line.charges.charge) { |
||||||
|
if (charge == null || charge.chargeAmount == null || charge.chargeAmount.amount == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
if ("ItemPrice".equals(charge.chargeName)) { |
||||||
|
return charge; |
||||||
|
} |
||||||
|
if (productFallback == null && "PRODUCT".equals(charge.chargeType)) { |
||||||
|
productFallback = charge; |
||||||
|
} |
||||||
|
} |
||||||
|
return productFallback; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行税额:取所有 charge 上 tax 的合计;一条都没有时为 null。 */ |
||||||
|
static Money taxOf(WalmartOrderDtos.OrderLine line) { |
||||||
|
if (line.charges == null || line.charges.charge == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
BigDecimal total = BigDecimal.ZERO; |
||||||
|
String currency = null; |
||||||
|
boolean any = false; |
||||||
|
for (WalmartOrderDtos.Charge charge : line.charges.charge) { |
||||||
|
if (charge == null || charge.tax == null || charge.tax.taxAmount == null |
||||||
|
|| charge.tax.taxAmount.amount == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
total = total.add(charge.tax.taxAmount.amount); |
||||||
|
if (currency == null) { |
||||||
|
currency = charge.tax.taxAmount.currency; |
||||||
|
} |
||||||
|
any = true; |
||||||
|
} |
||||||
|
if (!any || currency == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Money.of(total, currency); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 数量解析:沃尔玛把数量放在字符串里({@code "1"}),也见过数字形式。 |
||||||
|
* |
||||||
|
* <p>非法值记 0,与「0 表示平台未给」的约定一致,不因一行脏数据卡住整页。</p> |
||||||
|
*/ |
||||||
|
static int parseQuantity(WalmartOrderDtos.Quantity quantity) { |
||||||
|
if (quantity == null || quantity.amount == null || quantity.amount.trim().isEmpty()) { |
||||||
|
return 0; |
||||||
|
} |
||||||
|
try { |
||||||
|
return new BigDecimal(quantity.amount.trim()).intValue(); |
||||||
|
} catch (NumberFormatException e) { |
||||||
|
return 0; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** epoch 毫秒 → 三轴时间;null 时返回当前时钟(订单下单时间不该为空,兜底不抛)。 */ |
||||||
|
static PlatformTime toPlatformTime(Long epochMillis, ZoneId zone) { |
||||||
|
if (epochMillis == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
return PlatformTime.of(Instant.ofEpochMilli(epochMillis.longValue()), zone); |
||||||
|
} |
||||||
|
|
||||||
|
private static Money money(WalmartOrderDtos.Amount amount) { |
||||||
|
if (amount == null || amount.amount == null || amount.currency == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Money.of(amount.amount, amount.currency); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,148 @@ |
|||||||
|
package common.ecommerce.walmart.mapper; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.product.ProductListing; |
||||||
|
import common.ecommerce.channel.model.product.ProductStatus; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.model.Platform; |
||||||
|
import common.ecommerce.shared.support.Money; |
||||||
|
import common.ecommerce.walmart.dto.WalmartItemDtos; |
||||||
|
import common.ecommerce.walmart.enums.WalmartPublishedStatus; |
||||||
|
import com.fasterxml.jackson.databind.JsonNode; |
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper; |
||||||
|
|
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.LinkedHashMap; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Map; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛商品 → 统一 {@link ProductListing}。 |
||||||
|
* |
||||||
|
* <p>字段对应:</p> |
||||||
|
* <ul> |
||||||
|
* <li>{@code platformSku} ← {@code sku},{@code listingId} ← {@code wpid}</li> |
||||||
|
* <li>{@code gtin} ← {@code gtin},缺失回落 {@code upc}</li> |
||||||
|
* <li>{@code status} ← {@code publishedStatus} + {@code lifecycleStatus} 组合, |
||||||
|
* 见 {@link WalmartPublishedStatus}</li> |
||||||
|
* <li>{@code rawStatus} ← {@code "UNPUBLISHED/ACTIVE"} 这样的组合串,便于排查</li> |
||||||
|
* <li>{@code attributes} ← 未标准化的 {@code mart} / {@code shelf} / {@code productType} / |
||||||
|
* {@code unpublishedReasons} / {@code upc}</li> |
||||||
|
* </ul> |
||||||
|
* |
||||||
|
* <p>{@code shelf} 是 JSON 字符串数组,这里二次解析成 {@code List<String>}; |
||||||
|
* 解析失败时按原串放进 attributes,不让一行脏数据卡住整页。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartProductMapper { |
||||||
|
|
||||||
|
/** 解析 {@code shelf} 用;只在解析字符串数组,不做路径查询。 */ |
||||||
|
private static final ObjectMapper SHELF_PARSER = new ObjectMapper(); |
||||||
|
|
||||||
|
private WalmartProductMapper() { |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 映射一个商品。 |
||||||
|
* |
||||||
|
* @param dto 平台商品 |
||||||
|
* @param omsStoreId 宿主店铺 ID |
||||||
|
* @return 统一商品;{@code dto} 为 null 或缺少 SKU 时返回 null |
||||||
|
*/ |
||||||
|
public static ProductListing toProductListing(WalmartItemDtos.ItemResponse dto, String omsStoreId) { |
||||||
|
if (dto == null || dto.sku == null || dto.sku.trim().isEmpty()) { |
||||||
|
// SKU 是 canonicalKey 的一部分,没有它就没有可落库的对象
|
||||||
|
return null; |
||||||
|
} |
||||||
|
ProductStatus status = WalmartPublishedStatus.toProductStatus( |
||||||
|
dto.publishedStatus, dto.lifecycleStatus); |
||||||
|
|
||||||
|
return ProductListing.builder() |
||||||
|
.platform(Platform.WALMART_SC) |
||||||
|
.omsStoreId(omsStoreId) |
||||||
|
.platformSku(dto.sku) |
||||||
|
.listingId(dto.wpid) |
||||||
|
.gtin(dto.gtin != null ? dto.gtin : dto.upc) |
||||||
|
.title(dto.productName) |
||||||
|
.price(priceOf(dto)) |
||||||
|
.currency(dto.price == null ? null : dto.price.currency) |
||||||
|
.status(status) |
||||||
|
.rawStatus(WalmartPublishedStatus.rawStatus(dto.publishedStatus, dto.lifecycleStatus)) |
||||||
|
.attributes(attributesOf(dto)) |
||||||
|
.sourceProvider(ChannelProvider.DIRECT) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 价格;金额或币种缺失时为 null(不猜币种)。 */ |
||||||
|
static Money priceOf(WalmartItemDtos.ItemResponse dto) { |
||||||
|
if (dto.price == null || dto.price.amount == null || dto.price.currency == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Money.of(dto.price.amount, dto.price.currency); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 未标准化字段。键名与沃尔玛一致,宿主可以直接读。 |
||||||
|
* |
||||||
|
* <p>值为 null 的字段不放进 Map,避免上游拿到一堆 null 分不清「没有」和「空」。</p> |
||||||
|
*/ |
||||||
|
static Map<String, Object> attributesOf(WalmartItemDtos.ItemResponse dto) { |
||||||
|
Map<String, Object> attributes = new LinkedHashMap<String, Object>(); |
||||||
|
putIfNotNull(attributes, "mart", dto.mart); |
||||||
|
putIfNotNull(attributes, "productType", dto.productType); |
||||||
|
putIfNotNull(attributes, "upc", dto.upc); |
||||||
|
putIfNotNull(attributes, "lifecycleStatus", dto.lifecycleStatus); |
||||||
|
putIfNotNull(attributes, "publishedStatus", dto.publishedStatus); |
||||||
|
if (dto.shelf != null) { |
||||||
|
attributes.put("shelf", parseShelf(dto.shelf)); |
||||||
|
attributes.put("shelfRaw", dto.shelf); |
||||||
|
} |
||||||
|
if (dto.unpublishedReasons != null && dto.unpublishedReasons.reason != null |
||||||
|
&& !dto.unpublishedReasons.reason.isEmpty()) { |
||||||
|
attributes.put("unpublishedReasons", |
||||||
|
new ArrayList<String>(dto.unpublishedReasons.reason)); |
||||||
|
} |
||||||
|
return attributes; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 解析 {@code shelf}。 |
||||||
|
* |
||||||
|
* @param raw 形如 {@code "[\"UNNAV\"]"} 的 JSON 字符串 |
||||||
|
* @return 解析成功返回字符串列表;不是合法 JSON 数组时返回只含原串的单元素列表 |
||||||
|
*/ |
||||||
|
static List<String> parseShelf(String raw) { |
||||||
|
List<String> out = new ArrayList<String>(); |
||||||
|
if (raw == null) { |
||||||
|
return out; |
||||||
|
} |
||||||
|
try { |
||||||
|
JsonNode node = SHELF_PARSER.readTree(raw); |
||||||
|
if (node != null && node.isArray()) { |
||||||
|
for (JsonNode item : node) { |
||||||
|
if (item != null && !item.isNull()) { |
||||||
|
out.add(item.asText()); |
||||||
|
} |
||||||
|
} |
||||||
|
return out; |
||||||
|
} |
||||||
|
// 不是数组:可能是单个裸字符串(如 "UNNAV"),也照收
|
||||||
|
if (node != null && node.isTextual()) { |
||||||
|
out.add(node.asText()); |
||||||
|
return out; |
||||||
|
} |
||||||
|
} catch (Exception e) { |
||||||
|
// 落回原文,不阻断同步
|
||||||
|
} |
||||||
|
out.add(raw); |
||||||
|
return out; |
||||||
|
} |
||||||
|
|
||||||
|
private static void putIfNotNull(Map<String, Object> map, String key, Object value) { |
||||||
|
if (value != null) { |
||||||
|
map.put(key, value); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,304 @@ |
|||||||
|
package common.ecommerce.walmart.mapper; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSale; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.model.Platform; |
||||||
|
import common.ecommerce.shared.support.Money; |
||||||
|
import common.ecommerce.shared.support.PlatformTime; |
||||||
|
import common.ecommerce.walmart.dto.WalmartReturnDtos; |
||||||
|
import common.ecommerce.walmart.enums.WalmartReturnType; |
||||||
|
|
||||||
|
import java.math.BigDecimal; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneId; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.Collections; |
||||||
|
import java.util.LinkedHashMap; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Map; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛退货单 → 统一 {@link AfterSale}(<b>按商品行展开</b>)。 |
||||||
|
* |
||||||
|
* <p>沃尔玛一个 {@code returnOrder} 里带多个 {@code returnOrderLines},而统一模型 |
||||||
|
* 一行 = 一个售后商品行,所以这里是 1 → N 展开。</p> |
||||||
|
* |
||||||
|
* <p>{@code afterSaleId} 用 {@code returnOrderId:returnOrderLineNumber}: |
||||||
|
* 两个字段都是平台侧稳定值,重复同步可幂等 upsert。</p> |
||||||
|
* |
||||||
|
* <p>退货行本身不带物流信息:承运商 / 跟踪号在 |
||||||
|
* {@code returnLineGroups[].labels[].carrierInfoList[]} 上,按 |
||||||
|
* {@code returnLineGroups[].returnLines[].returnOrderLineNumber} 关联到行。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartReturnMapper { |
||||||
|
|
||||||
|
private WalmartReturnMapper() { |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 把一个退货单展开成多个售后行。 |
||||||
|
* |
||||||
|
* <p><b>{@code returnOrderId} 缺失时整单丢弃</b>:它进 {@code afterSaleId} |
||||||
|
* (upsert 主键),漏了会拼出 {@code "null:1"} 这种键,脏数据会静默落库。 |
||||||
|
* 部分行缺行号仍可映射(行号退化为 0),因为单号还在。</p> |
||||||
|
* |
||||||
|
* @param dto 平台退货单 |
||||||
|
* @param omsStoreId 宿主店铺 ID |
||||||
|
* @param marketplaceZone 市场时区 |
||||||
|
* @return 售后行列表;{@code dto} 为 null、缺退货单号、或没有退货行时返回空列表 |
||||||
|
*/ |
||||||
|
public static List<AfterSale> toAfterSales(WalmartReturnDtos.ReturnOrder dto, String omsStoreId, |
||||||
|
ZoneId marketplaceZone) { |
||||||
|
if (dto == null || isBlank(dto.returnOrderId) |
||||||
|
|| dto.returnOrderLines == null || dto.returnOrderLines.isEmpty()) { |
||||||
|
return Collections.emptyList(); |
||||||
|
} |
||||||
|
Map<Integer, WalmartReturnDtos.CarrierInfo> carrierByLine = carrierIndex(dto); |
||||||
|
Map<Integer, Boolean> expectedByLine = expectedIndex(dto); |
||||||
|
|
||||||
|
List<AfterSale> out = new ArrayList<AfterSale>(dto.returnOrderLines.size()); |
||||||
|
for (WalmartReturnDtos.ReturnOrderLine line : dto.returnOrderLines) { |
||||||
|
if (line == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
AfterSale afterSale = toAfterSale(dto, line, omsStoreId, marketplaceZone, |
||||||
|
carrierByLine.get(line.returnOrderLineNumber), |
||||||
|
expectedByLine.get(line.returnOrderLineNumber)); |
||||||
|
if (afterSale != null) { |
||||||
|
out.add(afterSale); |
||||||
|
} |
||||||
|
} |
||||||
|
return out; |
||||||
|
} |
||||||
|
|
||||||
|
/** 单行映射。 */ |
||||||
|
static AfterSale toAfterSale(WalmartReturnDtos.ReturnOrder dto, WalmartReturnDtos.ReturnOrderLine line, |
||||||
|
String omsStoreId, ZoneId marketplaceZone, |
||||||
|
WalmartReturnDtos.CarrierInfo carrier, Boolean returnExpected) { |
||||||
|
return AfterSale.builder() |
||||||
|
.platform(Platform.WALMART_SC) |
||||||
|
.omsStoreId(omsStoreId) |
||||||
|
.afterSaleId(afterSaleId(dto.returnOrderId, line.returnOrderLineNumber)) |
||||||
|
.channelOrderId(line.purchaseOrderId != null ? line.purchaseOrderId : dto.customerOrderId) |
||||||
|
.type(WalmartReturnType.toCore(dto.returnType)) |
||||||
|
.rawType(dto.returnType) |
||||||
|
.status(line.status) |
||||||
|
.reason(line.returnReason) |
||||||
|
.quantity(line.quantity == null || line.quantity.measurementValue == null |
||||||
|
? 0 : line.quantity.measurementValue.intValue()) |
||||||
|
.platformSku(line.item == null ? null : line.item.sku) |
||||||
|
.refundAmount(refundAmountOf(line)) |
||||||
|
.afterSaleTime(toPlatformTime(dto.returnOrderDate, marketplaceZone)) |
||||||
|
.updatedAt(toPlatformTime(line.statusTime, marketplaceZone)) |
||||||
|
.carrier(carrier == null ? null : carrier.carrierName) |
||||||
|
.trackingNumber(carrier == null ? null : carrier.trackingNo) |
||||||
|
.exchangeOrderId(dto.replacementCustomerOrderId) |
||||||
|
.attributes(attributesOf(dto, line, returnExpected)) |
||||||
|
.sourceProvider(ChannelProvider.DIRECT) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** {@code returnOrderId:returnOrderLineNumber};行号缺失时退化为退货单号。 */ |
||||||
|
static String afterSaleId(String returnOrderId, Integer returnOrderLineNumber) { |
||||||
|
return returnOrderId + ":" + (returnOrderLineNumber == null ? "0" : returnOrderLineNumber); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 本行<b>应退</b>金额(按退货数量计,不是「已退」金额)。 |
||||||
|
* |
||||||
|
* <p>取 {@code chargeTotals} 里 {@code name=lineTotal} 的值——它是<b>退货行</b>的合计, |
||||||
|
* 等于「退货数量 × 单价」,不是原订单整行金额。没有时用 {@code unitPrice × quantity} 兜底。</p> |
||||||
|
* |
||||||
|
* <p>「已退多少」看行上的 {@code refundedQty}(可能小于退货数量,部分退款场景), |
||||||
|
* 换算成金额后放在 {@code attributes.refundedAmount},不覆盖本字段—— |
||||||
|
* 两个语义混在一起会让下游算错超退。</p> |
||||||
|
* |
||||||
|
* <p>币种只从 {@code unitPrice.currencyUnit} 取,拿不到币种时整体为 null—— |
||||||
|
* 不猜币种,也不拿订单总额硬摊。</p> |
||||||
|
*/ |
||||||
|
static Money refundAmountOf(WalmartReturnDtos.ReturnOrderLine line) { |
||||||
|
String currency = line.unitPrice == null ? null : line.unitPrice.currencyUnit; |
||||||
|
BigDecimal amount = lineTotalOf(line); |
||||||
|
if (amount == null) { |
||||||
|
amount = unitPriceTimesQuantity(line); |
||||||
|
} |
||||||
|
if (amount == null) { |
||||||
|
amount = line.unitPrice == null ? null : line.unitPrice.currencyAmount; |
||||||
|
} |
||||||
|
if (amount == null || currency == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Money.of(amount, currency); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** 已退金额 = {@code refundedQty × unitPrice};任一缺失返回 null。 */ |
||||||
|
static Money refundedAmountOf(WalmartReturnDtos.ReturnOrderLine line) { |
||||||
|
if (line.refundedQty == null || line.unitPrice == null |
||||||
|
|| line.unitPrice.currencyAmount == null || line.unitPrice.currencyUnit == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Money.of(line.refundedQty.multiply(line.unitPrice.currencyAmount), |
||||||
|
line.unitPrice.currencyUnit); |
||||||
|
} catch (IllegalArgumentException e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** {@code chargeTotals} 里 {@code lineTotal} 的值;没有返回 null。 */ |
||||||
|
static BigDecimal lineTotalOf(WalmartReturnDtos.ReturnOrderLine line) { |
||||||
|
if (line.chargeTotals == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
for (WalmartReturnDtos.ChargeTotal total : line.chargeTotals) { |
||||||
|
if (total != null && "lineTotal".equals(total.name)) { |
||||||
|
return total.value; |
||||||
|
} |
||||||
|
} |
||||||
|
return null; |
||||||
|
} |
||||||
|
|
||||||
|
/** 单价 × 数量;任一缺失返回 null。 */ |
||||||
|
static BigDecimal unitPriceTimesQuantity(WalmartReturnDtos.ReturnOrderLine line) { |
||||||
|
if (line.unitPrice == null || line.unitPrice.currencyAmount == null |
||||||
|
|| line.quantity == null || line.quantity.measurementValue == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
return line.unitPrice.currencyAmount.multiply(line.quantity.measurementValue); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 原始字段。沃尔玛售后的细分状态(退款状态、物流状态、keep-it 等)统一模型没有 |
||||||
|
* 对应字段,全部原样保留在这里;键名与平台一致。 |
||||||
|
*/ |
||||||
|
static Map<String, Object> attributesOf(WalmartReturnDtos.ReturnOrder dto, |
||||||
|
WalmartReturnDtos.ReturnOrderLine line, |
||||||
|
Boolean returnExpected) { |
||||||
|
Map<String, Object> attributes = new LinkedHashMap<String, Object>(); |
||||||
|
putIfNotNull(attributes, "returnOrderId", dto.returnOrderId); |
||||||
|
putIfNotNull(attributes, "customerOrderId", dto.customerOrderId); |
||||||
|
putIfNotNull(attributes, "customerEmailId", dto.customerEmailId); |
||||||
|
putIfNotNull(attributes, "refundMode", dto.refundMode); |
||||||
|
putIfNotNull(attributes, "returnByDate", dto.returnByDate); |
||||||
|
putIfNotNull(attributes, "returnChannel", |
||||||
|
dto.returnChannel == null ? null : dto.returnChannel.channelName); |
||||||
|
putIfNotNull(attributes, "totalRefundAmount", currencyAmount(dto.totalRefundAmount)); |
||||||
|
putIfNotNull(attributes, "salesOrderLineNumber", line.salesOrderLineNumber); |
||||||
|
putIfNotNull(attributes, "purchaseOrderLineNumber", line.purchaseOrderLineNumber); |
||||||
|
putIfNotNull(attributes, "sellerOrderId", line.sellerOrderId); |
||||||
|
putIfNotNull(attributes, "currentDeliveryStatus", line.currentDeliveryStatus); |
||||||
|
putIfNotNull(attributes, "currentRefundStatus", line.currentRefundStatus); |
||||||
|
putIfNotNull(attributes, "refundChannel", line.refundChannel); |
||||||
|
putIfNotNull(attributes, "refundedQty", line.refundedQty); |
||||||
|
Money refunded = refundedAmountOf(line); |
||||||
|
putIfNotNull(attributes, "refundedAmount", refunded == null ? null : refunded.toString()); |
||||||
|
putIfNotNull(attributes, "cancellableQty", line.cancellableQty); |
||||||
|
putIfNotNull(attributes, "rechargeableQty", line.rechargeableQty); |
||||||
|
putIfNotNull(attributes, "isKeepIt", line.isKeepIt); |
||||||
|
putIfNotNull(attributes, "isFastReplacement", line.isFastReplacement); |
||||||
|
putIfNotNull(attributes, "lastItem", line.lastItem); |
||||||
|
putIfNotNull(attributes, "unitOfMeasure", |
||||||
|
line.quantity == null ? null : line.quantity.unitOfMeasure); |
||||||
|
if (returnExpected != null) { |
||||||
|
attributes.put("returnExpectedFlag", returnExpected); |
||||||
|
} |
||||||
|
return attributes; |
||||||
|
} |
||||||
|
|
||||||
|
/** 按 {@code returnOrderLineNumber} 建承运商索引;一个行可能有多个面单,取第一个非空。 */ |
||||||
|
static Map<Integer, WalmartReturnDtos.CarrierInfo> carrierIndex(WalmartReturnDtos.ReturnOrder dto) { |
||||||
|
Map<Integer, WalmartReturnDtos.CarrierInfo> index = |
||||||
|
new LinkedHashMap<Integer, WalmartReturnDtos.CarrierInfo>(); |
||||||
|
if (dto.returnLineGroups == null) { |
||||||
|
return index; |
||||||
|
} |
||||||
|
for (WalmartReturnDtos.ReturnLineGroup group : dto.returnLineGroups) { |
||||||
|
if (group == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
WalmartReturnDtos.CarrierInfo carrier = firstCarrier(group); |
||||||
|
if (carrier == null || group.returnLines == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
for (WalmartReturnDtos.GroupReturnLine gl : group.returnLines) { |
||||||
|
if (gl != null && gl.returnOrderLineNumber != null |
||||||
|
&& !index.containsKey(gl.returnOrderLineNumber)) { |
||||||
|
index.put(gl.returnOrderLineNumber, carrier); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
return index; |
||||||
|
} |
||||||
|
|
||||||
|
/** 按 {@code returnOrderLineNumber} 建「是否预期退回」索引。 */ |
||||||
|
static Map<Integer, Boolean> expectedIndex(WalmartReturnDtos.ReturnOrder dto) { |
||||||
|
Map<Integer, Boolean> index = new LinkedHashMap<Integer, Boolean>(); |
||||||
|
if (dto.returnLineGroups == null) { |
||||||
|
return index; |
||||||
|
} |
||||||
|
for (WalmartReturnDtos.ReturnLineGroup group : dto.returnLineGroups) { |
||||||
|
if (group == null || group.returnExpectedFlag == null || group.returnLines == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
for (WalmartReturnDtos.GroupReturnLine gl : group.returnLines) { |
||||||
|
if (gl != null && gl.returnOrderLineNumber != null |
||||||
|
&& !index.containsKey(gl.returnOrderLineNumber)) { |
||||||
|
index.put(gl.returnOrderLineNumber, group.returnExpectedFlag); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
return index; |
||||||
|
} |
||||||
|
|
||||||
|
private static WalmartReturnDtos.CarrierInfo firstCarrier(WalmartReturnDtos.ReturnLineGroup group) { |
||||||
|
if (group.labels == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
for (WalmartReturnDtos.Label label : group.labels) { |
||||||
|
if (label == null || label.carrierInfoList == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
for (WalmartReturnDtos.CarrierInfo info : label.carrierInfoList) { |
||||||
|
if (info != null) { |
||||||
|
return info; |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
return null; |
||||||
|
} |
||||||
|
|
||||||
|
/** {@code {currencyAmount, currencyUnit}} → {@code "127.45 USD"};用于 attributes。 */ |
||||||
|
private static String currencyAmount(WalmartReturnDtos.CurrencyAmount amount) { |
||||||
|
if (amount == null || amount.currencyAmount == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
return amount.currencyAmount.toPlainString() + " " + amount.currencyUnit; |
||||||
|
} |
||||||
|
|
||||||
|
/** ISO-8601 字符串 → 三轴时间;解析失败返回 null,不让脏时间卡住整页。 */ |
||||||
|
static PlatformTime toPlatformTime(String iso, ZoneId zone) { |
||||||
|
if (iso == null || iso.trim().isEmpty()) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
try { |
||||||
|
return PlatformTime.of(Instant.parse(iso.trim()), zone); |
||||||
|
} catch (Exception e) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/** 平台必填字段缺失判定。 */ |
||||||
|
private static boolean isBlank(String value) { |
||||||
|
return value == null || value.trim().isEmpty(); |
||||||
|
} |
||||||
|
|
||||||
|
private static void putIfNotNull(Map<String, Object> map, String key, Object value) { |
||||||
|
if (value != null) { |
||||||
|
map.put(key, value); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,133 @@ |
|||||||
|
package common.ecommerce.walmart.mapper; |
||||||
|
|
||||||
|
import common.ecommerce.walmart.dto.WalmartShipmentDtos; |
||||||
|
|
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.Collections; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* 发货信息({@code GET /v3/orders/{id}/shipping})→ 行级发货记录。 |
||||||
|
* |
||||||
|
* <p>统一模型没有独立的「发货记录」实体:同样的 {@code trackingInfo} 也挂在订单详情的 |
||||||
|
* 行状态上,两种方式数据一致。本类只给「单独查发货信息」的场景用。</p> |
||||||
|
* |
||||||
|
* <p><b>不扩展 {@code OrderLine}</b>:跟踪号、承运商属于履约域,统一订单模型只保留交易信息; |
||||||
|
* 要发货信息请走 {@code WalmartAdapter.getShipping},不要在 {@code OrderLine} 上找。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartShipmentMapper { |
||||||
|
|
||||||
|
private WalmartShipmentMapper() { |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 抽取每行的发货记录。 |
||||||
|
* |
||||||
|
* <p>同一行可能有多个状态({@code Created} / {@code Shipped}),只取带 |
||||||
|
* {@code trackingInfo} 的那条;没有任何发货记录的行不出现在结果里(表示尚未发货)。</p> |
||||||
|
* |
||||||
|
* @param dto 发货信息响应 |
||||||
|
* @return 每行一条;响应为空时返回空列表 |
||||||
|
*/ |
||||||
|
public static List<ShipmentLine> toShipmentLines(WalmartShipmentDtos.ShipmentResponse dto) { |
||||||
|
if (dto == null || dto.orderShipment == null |
||||||
|
|| dto.orderShipment.orderLines == null |
||||||
|
|| dto.orderShipment.orderLines.orderLine == null) { |
||||||
|
return Collections.emptyList(); |
||||||
|
} |
||||||
|
List<ShipmentLine> out = new ArrayList<ShipmentLine>(); |
||||||
|
for (WalmartShipmentDtos.OrderLine line : dto.orderShipment.orderLines.orderLine) { |
||||||
|
if (line == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
WalmartShipmentDtos.TrackingInfo tracking = trackingOf(line); |
||||||
|
if (tracking == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
out.add(new ShipmentLine( |
||||||
|
line.lineNumber, |
||||||
|
carrierOf(tracking), |
||||||
|
tracking.methodCode, |
||||||
|
tracking.trackingNumber, |
||||||
|
tracking.shipDateTime)); |
||||||
|
} |
||||||
|
return out; |
||||||
|
} |
||||||
|
|
||||||
|
/** 行上的发货记录:取第一条带 {@code trackingInfo} 的状态。 */ |
||||||
|
static WalmartShipmentDtos.TrackingInfo trackingOf(WalmartShipmentDtos.OrderLine line) { |
||||||
|
if (line.orderLineStatuses == null || line.orderLineStatuses.orderLineStatus == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
for (WalmartShipmentDtos.OrderLineStatus status : line.orderLineStatuses.orderLineStatus) { |
||||||
|
if (status != null && status.trackingInfo != null) { |
||||||
|
return status.trackingInfo; |
||||||
|
} |
||||||
|
} |
||||||
|
return null; |
||||||
|
} |
||||||
|
|
||||||
|
/** 承运商:标准编码优先,没有时用非标准名称。 */ |
||||||
|
static String carrierOf(WalmartShipmentDtos.TrackingInfo tracking) { |
||||||
|
if (tracking.carrierName == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
return tracking.carrierName.carrier != null |
||||||
|
? tracking.carrierName.carrier : tracking.carrierName.otherCarrier; |
||||||
|
} |
||||||
|
|
||||||
|
/** 一行的发货记录。 */ |
||||||
|
public static final class ShipmentLine { |
||||||
|
|
||||||
|
/** 订单行号。 */ |
||||||
|
private final String lineNumber; |
||||||
|
/** 承运商编码;非标准承运商时为 {@code otherCarrier} 名称。 */ |
||||||
|
private final String carrier; |
||||||
|
/** 运输方式编码。 */ |
||||||
|
private final String methodCode; |
||||||
|
/** 跟踪号。 */ |
||||||
|
private final String trackingNumber; |
||||||
|
/** 发货时间,ISO-8601 原值。 */ |
||||||
|
private final String shipDateTime; |
||||||
|
|
||||||
|
ShipmentLine(String lineNumber, String carrier, String methodCode, |
||||||
|
String trackingNumber, String shipDateTime) { |
||||||
|
this.lineNumber = lineNumber; |
||||||
|
this.carrier = carrier; |
||||||
|
this.methodCode = methodCode; |
||||||
|
this.trackingNumber = trackingNumber; |
||||||
|
this.shipDateTime = shipDateTime; |
||||||
|
} |
||||||
|
|
||||||
|
/** 订单行号。 */ |
||||||
|
public String lineNumber() { |
||||||
|
return lineNumber; |
||||||
|
} |
||||||
|
|
||||||
|
/** 承运商编码 / 非标准承运商名称。 */ |
||||||
|
public String carrier() { |
||||||
|
return carrier; |
||||||
|
} |
||||||
|
|
||||||
|
/** 运输方式编码。 */ |
||||||
|
public String methodCode() { |
||||||
|
return methodCode; |
||||||
|
} |
||||||
|
|
||||||
|
/** 跟踪号。 */ |
||||||
|
public String trackingNumber() { |
||||||
|
return trackingNumber; |
||||||
|
} |
||||||
|
|
||||||
|
/** 发货时间(ISO-8601 原值)。 */ |
||||||
|
public String shipDateTime() { |
||||||
|
return shipDateTime; |
||||||
|
} |
||||||
|
|
||||||
|
/** 调试输出;不含收货人信息。 */ |
||||||
|
@Override |
||||||
|
public String toString() { |
||||||
|
return "ShipmentLine{" + lineNumber + ", " + carrier + ", " + trackingNumber + '}'; |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,154 @@ |
|||||||
|
package common.ecommerce.walmart; |
||||||
|
|
||||||
|
import common.ecommerce.channel.capability.CapabilityReport; |
||||||
|
import common.ecommerce.channel.capability.PlatformAdapter; |
||||||
|
import common.ecommerce.channel.model.account.AccountKey; |
||||||
|
import common.ecommerce.channel.model.account.ChannelAccount; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSale; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrder; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrderQuery; |
||||||
|
import common.ecommerce.channel.model.product.ProductListing; |
||||||
|
import common.ecommerce.channel.model.product.ProductQuery; |
||||||
|
import common.ecommerce.channel.sdk.AdapterFactory; |
||||||
|
import common.ecommerce.channel.sdk.ChannelSdk; |
||||||
|
import common.ecommerce.shared.error.ChannelException; |
||||||
|
import common.ecommerce.shared.model.Capability; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.model.Platform; |
||||||
|
import common.ecommerce.shared.spi.ChannelSecret; |
||||||
|
import common.ecommerce.shared.support.Page; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryAccounts; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||||
|
import common.ecommerce.shared.testkit.JsonFixture; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import common.ecommerce.walmart.adapter.WalmartAdapterFactory; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
import java.time.LocalDate; |
||||||
|
import java.util.EnumSet; |
||||||
|
|
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.CLIENT_ID; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.CLIENT_SECRET; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.CLOCK; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.ENDPOINT; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.account; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.adapter; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 门面集成:沃尔玛适配器注册后,{@code ChannelSdk} 按 DIRECT + WALMART_SC 路由, |
||||||
|
* 能力矩阵与领星账户互不干扰。 |
||||||
|
*/ |
||||||
|
class WalmartFacadeTest { |
||||||
|
|
||||||
|
private static final AccountKey WM = |
||||||
|
AccountKey.of(ChannelProvider.DIRECT, Platform.WALMART_SC, "oms-wm-001"); |
||||||
|
|
||||||
|
private static final common.ecommerce.channel.sdk.ChannelConnection CONNECTION = |
||||||
|
common.ecommerce.channel.sdk.ChannelConnection.of(ENDPOINT, |
||||||
|
ChannelSecret.builder().clientId(CLIENT_ID).clientSecret(CLIENT_SECRET).build()); |
||||||
|
|
||||||
|
private RecordingTransport transport() { |
||||||
|
return RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(JsonFixture.load("fixtures/walmart/token/success.json"))) |
||||||
|
.route("/v3/orders", r -> Responses.ok(JsonFixture.load("fixtures/walmart/orders/list.json"))) |
||||||
|
.route("/v3/items", r -> Responses.ok(JsonFixture.load("fixtures/walmart/items/list.json"))) |
||||||
|
.route("/v3/returns", r -> Responses.ok(JsonFixture.load("fixtures/walmart/returns/list.json"))); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 用录制传输层装配门面。 |
||||||
|
* |
||||||
|
* <p>工厂 {@code create()} 装配的是真实 OkHttp 传输层(生产路径),测试里直接 |
||||||
|
* 注册适配器实例,才能把网络关掉。工厂本身另由 |
||||||
|
* {@link #factoryRegistersDirectWalmart()} 覆盖。</p> |
||||||
|
*/ |
||||||
|
private ChannelSdk sdkWithRecording(RecordingTransport transport, InMemoryAccounts accounts) { |
||||||
|
return ChannelSdk.builder() |
||||||
|
.accountRepository(accounts) |
||||||
|
.register(adapter(transport)) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
private static InMemoryAccounts accounts() { |
||||||
|
return new InMemoryAccounts().put(account()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void factoryRegistersDirectWalmart() { |
||||||
|
AdapterFactory factory = new WalmartAdapterFactory( |
||||||
|
new InMemoryTokenStore(), new InMemoryLockProvider(), CLOCK); |
||||||
|
assertEquals(ChannelProvider.DIRECT, factory.provider()); |
||||||
|
assertEquals(EnumSet.of(Platform.WALMART_SC), factory.platforms()); |
||||||
|
|
||||||
|
PlatformAdapter adapter = factory.create(AdapterFactory.AdapterConfig.NONE); |
||||||
|
assertEquals(ChannelProvider.DIRECT, adapter.provider()); |
||||||
|
assertEquals(EnumSet.of(Platform.WALMART_SC), adapter.platforms()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void capabilityReportIsExactlyReadOnlyThree() { |
||||||
|
ChannelSdk sdk = sdkWithRecording(transport(), accounts()); |
||||||
|
CapabilityReport report = sdk.capabilities(WM); |
||||||
|
|
||||||
|
assertEquals(EnumSet.of(Capability.SALES_ORDER, Capability.PRODUCT, Capability.RETURNS), |
||||||
|
report.supported()); |
||||||
|
assertFalse(report.supports(Capability.MARK_SHIPPED)); |
||||||
|
assertFalse(report.supports(Capability.BILLING)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void pullsThroughFacade() { |
||||||
|
ChannelSdk sdk = sdkWithRecording(transport(), accounts()); |
||||||
|
|
||||||
|
Page<SalesOrder> orders = sdk.salesOrders(WM, CONNECTION).pull(SalesOrderQuery.builder() |
||||||
|
.updatedAfter(Instant.parse("2026-11-01T00:00:00Z")) |
||||||
|
.updatedBefore(Instant.parse("2026-11-02T00:00:00Z")) |
||||||
|
.build()); |
||||||
|
assertEquals(5, orders.size()); |
||||||
|
|
||||||
|
Page<ProductListing> products = sdk.products(WM, CONNECTION) |
||||||
|
.pull(ProductQuery.builder().build()); |
||||||
|
assertEquals(3, products.size()); |
||||||
|
|
||||||
|
Page<AfterSale> afterSales = sdk.afterSales(WM, CONNECTION).pull( |
||||||
|
common.ecommerce.channel.model.aftersale.AfterSaleQuery.builder() |
||||||
|
.startDate(LocalDate.of(2026, 11, 1)) |
||||||
|
.endDate(LocalDate.of(2026, 11, 18)) |
||||||
|
.build()); |
||||||
|
assertEquals(2, afterSales.size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void writeOperationsAreRejectedNotSilentlyIgnored() { |
||||||
|
ChannelSdk sdk = sdkWithRecording(transport(), accounts()); |
||||||
|
ChannelException.UnsupportedCapabilityException ex = assertThrows( |
||||||
|
ChannelException.UnsupportedCapabilityException.class, |
||||||
|
() -> sdk.outbounds(WM, CONNECTION).submit(java.util.Collections.emptyList())); |
||||||
|
assertEquals(Capability.MARK_SHIPPED, ex.capability()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unregisteredPlatformIsNotRouted() { |
||||||
|
// 账户存在但没有任何适配器覆盖 AMAZON_SC:报「没有适配器」而不是「账户未配置」
|
||||||
|
InMemoryAccounts accounts = accounts().put(ChannelAccount.builder() |
||||||
|
.key(AccountKey.of(ChannelProvider.DIRECT, Platform.AMAZON_SC, "oms-amz-001")) |
||||||
|
.externalStoreId("amz-seller-01") |
||||||
|
.credentialRef("kms://test/amazon") |
||||||
|
.marketplaceZone("America/Los_Angeles") |
||||||
|
.currency("USD") |
||||||
|
.build()); |
||||||
|
ChannelSdk sdk = sdkWithRecording(transport(), accounts); |
||||||
|
|
||||||
|
AccountKey amazon = AccountKey.of(ChannelProvider.DIRECT, Platform.AMAZON_SC, "oms-amz-001"); |
||||||
|
IllegalStateException ex = assertThrows(IllegalStateException.class, |
||||||
|
() -> sdk.capabilities(amazon)); |
||||||
|
assertTrue(ex.getMessage().contains("no adapter registered"), ex.getMessage()); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,209 @@ |
|||||||
|
package common.ecommerce.walmart.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleQuery; |
||||||
|
import common.ecommerce.channel.model.order.OrderLine; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrder; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrderQuery; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.shared.support.Page; |
||||||
|
import common.ecommerce.shared.testkit.JsonFixture; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import com.fasterxml.jackson.databind.node.ArrayNode; |
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
import java.time.LocalDate; |
||||||
|
|
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.adapter; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.context; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 脏数据韧性:平台给了缺字段 / 非预期费用的记录时, |
||||||
|
* 适配器要「丢一条 + 不崩页」,而不是抛 NPE 或写脏主键。 |
||||||
|
*/ |
||||||
|
class WalmartDirtyDataTest { |
||||||
|
|
||||||
|
private static final JacksonJsonCodec JSON = new JacksonJsonCodec(); |
||||||
|
|
||||||
|
private static RecordingTransport transport(String path, String body) { |
||||||
|
return RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(JsonFixture.load("fixtures/walmart/token/success.json"))) |
||||||
|
.route(path, r -> Responses.ok(body)); |
||||||
|
} |
||||||
|
|
||||||
|
private static SalesOrderQuery orderQuery() { |
||||||
|
return SalesOrderQuery.builder() |
||||||
|
.updatedAfter(Instant.parse("2026-11-01T00:00:00Z")) |
||||||
|
.updatedBefore(Instant.parse("2026-11-02T00:00:00Z")).build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 取一条正常订单,按需删字段 / 改费用。 */ |
||||||
|
private static ObjectNode sampleOrder() throws Exception { |
||||||
|
ObjectNode root = (ObjectNode) JSON.mapper().readTree( |
||||||
|
JsonFixture.load("fixtures/walmart/orders/list.json")); |
||||||
|
return (ObjectNode) root.at("/list/elements/order/0"); |
||||||
|
} |
||||||
|
|
||||||
|
private static String orderBody(ObjectNode order) { |
||||||
|
ObjectNode root = JSON.mapper().createObjectNode(); |
||||||
|
ObjectNode list = root.putObject("list"); |
||||||
|
ArrayNode orders = list.putObject("elements").putArray("order"); |
||||||
|
orders.add(order); |
||||||
|
return JSON.toJson(root); |
||||||
|
} |
||||||
|
|
||||||
|
private static String wrapOrders(String... orderJson) { |
||||||
|
StringBuilder sb = new StringBuilder("{\"list\":{\"elements\":{\"order\":["); |
||||||
|
for (int i = 0; i < orderJson.length; i++) { |
||||||
|
if (i > 0) { |
||||||
|
sb.append(','); |
||||||
|
} |
||||||
|
sb.append(orderJson[i]); |
||||||
|
} |
||||||
|
return sb.append("]}}}").toString(); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 订单
|
||||||
|
|
||||||
|
@Test |
||||||
|
void orderWithoutPurchaseOrderIdIsSkippedNotFatal() throws Exception { |
||||||
|
ObjectNode missing = sampleOrder(); |
||||||
|
missing.remove("purchaseOrderId"); |
||||||
|
|
||||||
|
Page<SalesOrder> page = adapter(transport("/v3/orders", |
||||||
|
wrapOrders(missing.toString(), sampleOrder().toString()))) |
||||||
|
.pull(context(), orderQuery()); |
||||||
|
|
||||||
|
// 坏的那条丢掉,好的那条照常返回
|
||||||
|
assertEquals(1, page.size()); |
||||||
|
assertEquals("108816631915371", page.items().get(0).channelOrderId()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void orderWithoutOrderDateIsSkippedNotFatal() throws Exception { |
||||||
|
ObjectNode missing = sampleOrder(); |
||||||
|
missing.remove("orderDate"); |
||||||
|
|
||||||
|
Page<SalesOrder> page = adapter(transport("/v3/orders", |
||||||
|
wrapOrders(missing.toString(), sampleOrder().toString()))) |
||||||
|
.pull(context(), orderQuery()); |
||||||
|
|
||||||
|
assertEquals(1, page.size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void blankPurchaseOrderIdIsSkipped() throws Exception { |
||||||
|
ObjectNode blank = sampleOrder(); |
||||||
|
blank.put("purchaseOrderId", " "); |
||||||
|
|
||||||
|
Page<SalesOrder> page = adapter(transport("/v3/orders", orderBody(blank))) |
||||||
|
.pull(context(), orderQuery()); |
||||||
|
assertTrue(page.items().isEmpty()); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 单价与行金额
|
||||||
|
|
||||||
|
@Test |
||||||
|
void lineAmountIsAuthoritativeAndUnitPriceDerived() throws Exception { |
||||||
|
OrderLine line = singleLine(sampleOrder()); |
||||||
|
// 1 件 499.99:行金额与单价相同
|
||||||
|
assertEquals("499.99", line.lineAmount().amount().toPlainString()); |
||||||
|
assertEquals("499.99", line.unitPrice().amount().toPlainString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unitPriceIsNullWhenNotExactlyDivisible() throws Exception { |
||||||
|
OrderLine line = singleLine(twoUnitsOf("100.00", 3)); |
||||||
|
// 3 件共 100:除不尽,不给四舍五入后的 33.3333
|
||||||
|
assertNull(line.unitPrice()); |
||||||
|
assertEquals("100", line.lineAmount().amount().stripTrailingZeros().toPlainString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unitPriceIsPresentWhenExactlyDivisible() throws Exception { |
||||||
|
OrderLine line = singleLine(twoUnitsOf("99.98", 2)); |
||||||
|
assertEquals("49.99", line.unitPrice().amount().toPlainString()); |
||||||
|
assertEquals("99.98", line.lineAmount().amount().toPlainString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void shippingChargeIsNotTreatedAsUnitPrice() throws Exception { |
||||||
|
ObjectNode order = sampleOrder(); |
||||||
|
ObjectNode line = (ObjectNode) order.at("/orderLines/orderLine/0"); |
||||||
|
// 去掉商品费,只剩运费
|
||||||
|
ObjectNode charges = (ObjectNode) line.at("/charges"); |
||||||
|
ArrayNode chargeArray = charges.putArray("charge"); |
||||||
|
ObjectNode shipping = chargeArray.addObject(); |
||||||
|
shipping.put("chargeType", "SHIPPING"); |
||||||
|
shipping.put("chargeName", "Shipping"); |
||||||
|
shipping.putObject("chargeAmount").put("currency", "USD").put("amount", 9.99); |
||||||
|
|
||||||
|
OrderLine mapped = singleLine(order); |
||||||
|
// 运费不是商品价:单价与行金额都不给,但订单总额仍能算出来
|
||||||
|
assertNull(mapped.unitPrice()); |
||||||
|
assertNull(mapped.lineAmount()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void totalIsNullWhenCurrenciesDiffer() throws Exception { |
||||||
|
ObjectNode order = sampleOrder(); |
||||||
|
ObjectNode line = (ObjectNode) order.at("/orderLines/orderLine/0"); |
||||||
|
ArrayNode chargeArray = (ArrayNode) line.at("/charges/charge"); |
||||||
|
ObjectNode other = chargeArray.addObject(); |
||||||
|
other.put("chargeType", "FEE"); |
||||||
|
other.put("chargeName", "Fee"); |
||||||
|
other.putObject("chargeAmount").put("currency", "CAD").put("amount", 5.0); |
||||||
|
|
||||||
|
Page<SalesOrder> page = adapter(transport("/v3/orders", orderBody(order))) |
||||||
|
.pull(context(), orderQuery()); |
||||||
|
// 同单两个币种属于数据异常:宁可不给总额
|
||||||
|
assertNull(page.items().get(0).totalAmount()); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 售后
|
||||||
|
|
||||||
|
@Test |
||||||
|
void returnWithoutReturnOrderIdIsDropped() { |
||||||
|
String body = "{\"returnOrders\":[{\"returnOrderLines\":[{\"returnOrderLineNumber\":1}]}]}"; |
||||||
|
Page<common.ecommerce.channel.model.aftersale.AfterSale> page = |
||||||
|
adapter(transport("/v3/returns", body)).pull(context(), AfterSaleQuery.builder() |
||||||
|
.startDate(LocalDate.of(2026, 11, 1)) |
||||||
|
.endDate(LocalDate.of(2026, 11, 18)).build()); |
||||||
|
// 不能拼出 "null:1" 这种主键
|
||||||
|
assertTrue(page.items().isEmpty()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void returnLineWithoutLineNumberStillUsesReturnOrderId() { |
||||||
|
String body = "{\"returnOrders\":[{\"returnOrderId\":\"R-9\",\"returnOrderLines\":[{\"status\":\"INITIATED\"}]}]}"; |
||||||
|
Page<common.ecommerce.channel.model.aftersale.AfterSale> page = |
||||||
|
adapter(transport("/v3/returns", body)).pull(context(), AfterSaleQuery.builder() |
||||||
|
.startDate(LocalDate.of(2026, 11, 1)) |
||||||
|
.endDate(LocalDate.of(2026, 11, 18)).build()); |
||||||
|
assertEquals("R-9:0", page.items().get(0).afterSaleId()); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- helpers
|
||||||
|
|
||||||
|
private static OrderLine singleLine(ObjectNode order) throws Exception { |
||||||
|
Page<SalesOrder> page = adapter(transport("/v3/orders", orderBody(order))) |
||||||
|
.pull(context(), orderQuery()); |
||||||
|
return page.items().get(0).lines().get(0); |
||||||
|
} |
||||||
|
|
||||||
|
/** 把样例订单改成「quantity 件共 amount」。 */ |
||||||
|
private static ObjectNode twoUnitsOf(String amount, int quantity) throws Exception { |
||||||
|
ObjectNode order = sampleOrder(); |
||||||
|
ObjectNode line = (ObjectNode) order.at("/orderLines/orderLine/0"); |
||||||
|
ObjectNode charge = (ObjectNode) line.at("/charges/charge/0"); |
||||||
|
charge.putObject("chargeAmount").put("currency", "USD").put("amount", new java.math.BigDecimal(amount)); |
||||||
|
((ObjectNode) charge.at("/tax/taxAmount")).put("amount", 0); |
||||||
|
((ObjectNode) line.at("/orderLineQuantity")).put("amount", String.valueOf(quantity)); |
||||||
|
return order; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,171 @@ |
|||||||
|
package common.ecommerce.walmart.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSale; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleQuery; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleType; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.testkit.JsonFixture; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import common.ecommerce.walmart.mapper.WalmartShipmentMapper; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.LocalDate; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.ENDPOINT; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.adapter; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.assertUrlContains; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.context; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.lastUrl; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 两个「有路由但不在能力接口里」的查询:退货单详情、发货信息。 |
||||||
|
* |
||||||
|
* <p>两者沙箱都 404,所以这里用契约测试锁住请求构造与响应映射; |
||||||
|
* 真实可用性由沙箱探针在生产环境补齐。</p> |
||||||
|
*/ |
||||||
|
class WalmartExtraQueryTest { |
||||||
|
|
||||||
|
private static final String TOKEN_BODY = JsonFixture.load("fixtures/walmart/token/success.json"); |
||||||
|
|
||||||
|
private RecordingTransport transport() { |
||||||
|
return RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns/103738048909818825", |
||||||
|
r -> Responses.ok(JsonFixture.load("fixtures/walmart/returns/detail.json"))) |
||||||
|
.route("/shipping", r -> Responses.ok( |
||||||
|
JsonFixture.load("fixtures/walmart/orders/shipping.json"))); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 退货单详情
|
||||||
|
|
||||||
|
@Test |
||||||
|
void returnDetailUsesReturnOrderIdPath() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
List<AfterSale> afterSales = adapter(transport).getReturn(context(), "103738048909818825"); |
||||||
|
|
||||||
|
assertUrlContains(lastUrl(transport), ENDPOINT + "/v3/returns/103738048909818825"); |
||||||
|
assertEquals(1, afterSales.size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void returnDetailExpandsLinesLikeList() { |
||||||
|
AfterSale a = adapter(transport()).getReturn(context(), "103738048909818825").get(0); |
||||||
|
|
||||||
|
// 与列表接口相同的 id 规则,可直接 upsert
|
||||||
|
assertEquals("103738048909818825:1", a.afterSaleId()); |
||||||
|
assertEquals(AfterSaleType.RETURN, a.type()); |
||||||
|
assertEquals("IN_TRANSIT", a.status()); |
||||||
|
assertEquals(2, a.quantity()); |
||||||
|
assertEquals("239.9", a.refundAmount().amount().toPlainString()); |
||||||
|
assertEquals("FEDEX", a.carrier()); |
||||||
|
assertEquals("785611449666", a.trackingNumber()); |
||||||
|
assertEquals("ONLINE", a.attributes().get("returnChannel")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void returnDetailEncodesId() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns/", r -> Responses.ok( |
||||||
|
JsonFixture.load("fixtures/walmart/returns/detail.json"))); |
||||||
|
adapter(transport).getReturn(context(), "R 1/2"); |
||||||
|
assertUrlContains(lastUrl(transport), "/v3/returns/R%201%2F2"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void blankReturnOrderIdIsRejectedBeforeAnyRequest() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
assertThrows(ValidationException.class, () -> adapter(transport).getReturn(context(), " ")); |
||||||
|
assertEquals(0, transport.recorded().size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void returnDetail404PropagatesAsValidationException() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns/", r -> Responses.status(404, |
||||||
|
JsonFixture.load("fixtures/walmart/errors/gateway-404.json"))); |
||||||
|
|
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).getReturn(context(), "SOMETHING")); |
||||||
|
assertEquals("CONTENT_NOT_FOUND.GMP_GATEWAY_API", ex.platformCode()); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 发货信息
|
||||||
|
|
||||||
|
@Test |
||||||
|
void shippingUsesOrderPathAndMapsShippedLinesOnly() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
List<WalmartShipmentMapper.ShipmentLine> lines = |
||||||
|
adapter(transport).getShipping(context(), "108816631915371"); |
||||||
|
|
||||||
|
assertUrlContains(lastUrl(transport), ENDPOINT + "/v3/orders/108816631915371/shipping"); |
||||||
|
// 3 行里只有 2 行有 trackingInfo;未发货行不出现
|
||||||
|
assertEquals(2, lines.size()); |
||||||
|
assertEquals("1", lines.get(0).lineNumber()); |
||||||
|
assertEquals("UPS", lines.get(0).carrier()); |
||||||
|
assertEquals("Standard", lines.get(0).methodCode()); |
||||||
|
assertEquals("1Z999AA10123456784", lines.get(0).trackingNumber()); |
||||||
|
assertEquals("2026-11-16T07:00:00.000Z", lines.get(0).shipDateTime()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void shippingFallsBackToOtherCarrier() { |
||||||
|
List<WalmartShipmentMapper.ShipmentLine> lines = |
||||||
|
adapter(transport()).getShipping(context(), "108816631915371"); |
||||||
|
// 非标准承运商:carrier 为空时用 otherCarrier
|
||||||
|
assertEquals("Local Courier", lines.get(1).carrier()); |
||||||
|
assertEquals("Freight", lines.get(1).methodCode()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void blankOrderIdIsRejectedBeforeAnyRequest() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
assertThrows(ValidationException.class, () -> adapter(transport).getShipping(context(), "")); |
||||||
|
assertEquals(0, transport.recorded().size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void emptyShipmentReturnsEmptyList() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/shipping", r -> Responses.ok("{\"orderShipment\":{\"orderLines\":{\"orderLine\":[]}}}")); |
||||||
|
assertTrue(adapter(transport).getShipping(context(), "PO-1").isEmpty()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void shipmentLineCarriesTrackingButNoRecipientInfo() { |
||||||
|
WalmartShipmentMapper.ShipmentLine line = |
||||||
|
adapter(transport()).getShipping(context(), "108816631915371").get(0); |
||||||
|
// 发货记录只含履约字段,不含收件人 / 地址
|
||||||
|
assertEquals("1Z999AA10123456784", line.trackingNumber()); |
||||||
|
assertTrue(line.toString().contains("1Z999AA10123456784"), line.toString()); |
||||||
|
assertTrue(!line.toString().contains("@"), line.toString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void listAndDetailAgreeOnReturnPathPrefix() { |
||||||
|
// 两个接口共用 /v3/returns 前缀;详情多一段 id,别把列表路由吃掉
|
||||||
|
assertEquals("/v3/returns", WalmartConstants.PATH_RETURNS); |
||||||
|
assertEquals("/v3/returns/", WalmartConstants.PATH_RETURN_BY_ID); |
||||||
|
} |
||||||
|
|
||||||
|
/** 列表接口仍然可用(详情方法没有误改列表路由)。 */ |
||||||
|
@Test |
||||||
|
void listStillWorks() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns", r -> Responses.ok(JsonFixture.load("fixtures/walmart/returns/list.json"))); |
||||||
|
int size = adapter(transport).pull(context(), AfterSaleQuery.builder() |
||||||
|
.startDate(LocalDate.of(2026, 11, 1)) |
||||||
|
.endDate(LocalDate.of(2026, 11, 18)) |
||||||
|
.build()).size(); |
||||||
|
assertEquals(2, size); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,346 @@ |
|||||||
|
package common.ecommerce.walmart.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.order.OrderLine; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrder; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrderQuery; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.model.Capability; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.model.Platform; |
||||||
|
import common.ecommerce.shared.support.Page; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||||
|
import common.ecommerce.shared.testkit.JsonFixture; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
import java.util.EnumSet; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.ENDPOINT; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.adapter; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.assertUrlContains; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.context; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.lastUrl; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** 沃尔玛订单:请求构造 + 响应映射 + 增量语义。 */ |
||||||
|
class WalmartOrderTest { |
||||||
|
|
||||||
|
private static final String TOKEN_BODY = JsonFixture.load("fixtures/walmart/token/success.json"); |
||||||
|
|
||||||
|
private RecordingTransport transport() { |
||||||
|
return RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/orders/108816631915371", |
||||||
|
r -> Responses.ok(JsonFixture.load("fixtures/walmart/orders/detail.json"))) |
||||||
|
.route("/v3/orders", r -> Responses.ok(JsonFixture.load("fixtures/walmart/orders/list.json"))); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 请求
|
||||||
|
|
||||||
|
@Test |
||||||
|
void pullSendsAuthHeadersAndCreatedWindow() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")); |
||||||
|
|
||||||
|
String url = lastUrl(transport); |
||||||
|
assertUrlContains(url, ENDPOINT + WalmartConstants.PATH_ORDERS); |
||||||
|
assertUrlContains(url, "createdStartDate=2026-11-01T00%3A00%3A00.000Z"); |
||||||
|
assertUrlContains(url, "createdEndDate=2026-11-02T00%3A00%3A00.000Z"); |
||||||
|
|
||||||
|
common.ecommerce.http.HttpRequest request = transport.recorded().get(transport.recorded().size() - 1); |
||||||
|
assertEquals("Walmart Marketplace", request.headers().get(WalmartConstants.HEADER_SVC_NAME)); |
||||||
|
assertEquals("req-1", request.headers().get(WalmartConstants.HEADER_CORRELATION_ID)); |
||||||
|
// 业务请求带的是 WM_SEC.ACCESS_TOKEN,不是 Authorization
|
||||||
|
assertNotNull(request.headers().get(WalmartConstants.HEADER_ACCESS_TOKEN)); |
||||||
|
assertNull(request.headers().get("Authorization")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void tokenRequestUsesBasicAuthAndFormBody() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")); |
||||||
|
|
||||||
|
common.ecommerce.http.HttpRequest token = transport.recorded().get(0); |
||||||
|
assertEquals(ENDPOINT + WalmartConstants.PATH_TOKEN, token.url()); |
||||||
|
assertEquals("POST", token.method()); |
||||||
|
assertEquals("application/x-www-form-urlencoded", token.contentType()); |
||||||
|
assertEquals("grant_type=client_credentials", token.body()); |
||||||
|
assertTrue(token.headers().get("Authorization").startsWith("Basic "), |
||||||
|
token.headers().get("Authorization")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void tokenIsCachedAcrossCalls() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
InMemoryTokenStore tokens = new InMemoryTokenStore(); |
||||||
|
common.ecommerce.walmart.adapter.WalmartAdapter walmart = adapter(transport, tokens, |
||||||
|
new common.ecommerce.shared.testkit.InMemoryLockProvider()); |
||||||
|
|
||||||
|
walmart.pull(context(), query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")); |
||||||
|
walmart.pull(context(), query("2026-11-03T00:00:00Z", "2026-11-04T00:00:00Z")); |
||||||
|
|
||||||
|
// 只换一次 token:沙箱有效令牌数接近上限,必须复用
|
||||||
|
assertEquals(1, tokens.saveCount()); |
||||||
|
assertEquals(1, countTokenRequests(transport)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void cursorIsPassedThrough() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), SalesOrderQuery.builder() |
||||||
|
.updatedAfter(Instant.parse("2026-11-01T00:00:00Z")) |
||||||
|
.updatedBefore(Instant.parse("2026-11-02T00:00:00Z")) |
||||||
|
.pageSize(50) |
||||||
|
.cursor("FGluY2x1ZGQ==") |
||||||
|
.build()); |
||||||
|
|
||||||
|
String url = lastUrl(transport); |
||||||
|
assertUrlContains(url, "limit=50"); |
||||||
|
assertUrlContains(url, "nextCursor=FGluY2x1ZGQ%3D%3D"); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 校验
|
||||||
|
|
||||||
|
@Test |
||||||
|
void windowOver180DaysIsRejected() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).pull(context(), |
||||||
|
query("2026-01-01T00:00:00Z", "2026-11-02T00:00:00Z"))); |
||||||
|
assertTrue(ex.getMessage().contains("max 180"), ex.getMessage()); |
||||||
|
// 本地拒绝,不发出业务请求
|
||||||
|
assertEquals(0, transport.dataRequests().size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void invertedWindowIsRejected() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).pull(context(), |
||||||
|
query("2026-11-02T00:00:00Z", "2026-11-01T00:00:00Z"))); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 映射
|
||||||
|
|
||||||
|
@Test |
||||||
|
void mapsOrderFields() { |
||||||
|
Page<SalesOrder> page = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")); |
||||||
|
|
||||||
|
assertEquals(5, page.size()); |
||||||
|
SalesOrder order = page.items().get(0); |
||||||
|
assertEquals("oms-wm-001", order.omsStoreId()); |
||||||
|
assertEquals("108816631915371", order.channelOrderId()); |
||||||
|
assertEquals("Created", order.status()); |
||||||
|
assertEquals("Astro Test", order.buyerName()); |
||||||
|
assertEquals("emailID123456@relay.walmart.com", order.buyerEmail()); |
||||||
|
assertEquals("USA", order.shipToCountryCode()); |
||||||
|
assertEquals(ChannelProvider.DIRECT, order.sourceProvider()); |
||||||
|
// orderDate 是 epoch 毫秒
|
||||||
|
assertEquals(Instant.ofEpochMilli(1686736267000L), order.occurredAt().utc()); |
||||||
|
assertNull(page.nextCursor()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void mapsShippingAddress() { |
||||||
|
SalesOrder order = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(0); |
||||||
|
|
||||||
|
assertNotNull(order.shipToAddress()); |
||||||
|
assertEquals("5809 W 44th Ave", order.shipToAddress().address1()); |
||||||
|
assertEquals("Lakeside", order.shipToAddress().city()); |
||||||
|
assertEquals("CO", order.shipToAddress().state()); |
||||||
|
assertEquals("80212", order.shipToAddress().postalCode()); |
||||||
|
assertEquals("USA", order.shipToAddress().countryCode()); |
||||||
|
assertEquals("OFFICE", order.shipToAddress().addressType()); |
||||||
|
assertEquals("555-0100", order.shipToAddress().phone()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void mapsLinesWithStringQuantityAndCharges() { |
||||||
|
SalesOrder order = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(0); |
||||||
|
|
||||||
|
assertEquals(1, order.lines().size()); |
||||||
|
OrderLine line = order.lines().get(0); |
||||||
|
assertEquals("1", line.lineId()); |
||||||
|
assertEquals("67022229561Test5_skuUpdate", line.platformSku()); |
||||||
|
// 订单接口的 amount 是字符串
|
||||||
|
assertEquals(1, line.quantity()); |
||||||
|
assertEquals("499.99", line.unitPrice().amount().toPlainString()); |
||||||
|
assertEquals("USD", line.unitPrice().currencyCode()); |
||||||
|
assertEquals("29.72", line.tax().amount().toPlainString()); |
||||||
|
assertEquals("Created", line.status()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unitPriceIsLineTotalDividedByQuantity() { |
||||||
|
// 2 件共 99.98:ItemPrice.chargeAmount 是整行金额,unitPrice 必须是 49.99
|
||||||
|
SalesOrder multi = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(4); |
||||||
|
assertEquals(2, multi.lines().get(0).quantity()); |
||||||
|
assertEquals("49.99", multi.lines().get(0).unitPrice().amount().toPlainString()); |
||||||
|
// 总额仍是行金额 + 税,与单价拆分互不影响
|
||||||
|
assertEquals("105.92", multi.totalAmount().amount().toPlainString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void singleQuantityKeepsChargeAmountAsUnitPrice() { |
||||||
|
SalesOrder single = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(0); |
||||||
|
assertEquals(1, single.lines().get(0).quantity()); |
||||||
|
assertEquals("499.99", single.lines().get(0).unitPrice().amount().toPlainString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void authFailureRetriesOnceWithFreshToken() { |
||||||
|
final int[] attempts = new int[2]; |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/orders", r -> { |
||||||
|
attempts[0]++; |
||||||
|
return attempts[0] == 1 |
||||||
|
? Responses.status(401, "{\"error\":[{\"code\":\"UNAUTHORIZED\"}]}") |
||||||
|
: Responses.ok(JsonFixture.load("fixtures/walmart/orders/list.json")); |
||||||
|
}); |
||||||
|
|
||||||
|
Page<SalesOrder> page = adapter(transport).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")); |
||||||
|
|
||||||
|
// 第一次 401 → 强制换 token → 第二次成功
|
||||||
|
assertEquals(5, page.size()); |
||||||
|
assertEquals(2, attempts[0]); |
||||||
|
assertEquals(2, countTokenRequests(transport)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void authFailureOnRetryIsNotSwallowed() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/orders", r -> Responses.status(401, |
||||||
|
"{\"error\":[{\"code\":\"UNAUTHORIZED\"}]}")); |
||||||
|
|
||||||
|
assertThrows(common.ecommerce.shared.error.AuthException.class, |
||||||
|
() -> adapter(transport).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z"))); |
||||||
|
// 只重试一次,不能无限刷 token
|
||||||
|
assertEquals(2, countTokenRequests(transport)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void privacySafeAddressToString() { |
||||||
|
// ShipToAddress.toString 只输出城市/州/邮编/国家,不输出街道与收件人
|
||||||
|
SalesOrder order = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(0); |
||||||
|
String text = order.shipToAddress().toString(); |
||||||
|
org.junit.jupiter.api.Assertions.assertFalse(text.contains("5809 W 44th Ave"), text); |
||||||
|
org.junit.jupiter.api.Assertions.assertFalse(text.contains("Astro Test"), text); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void totalIsSumOfChargesAndTax() { |
||||||
|
SalesOrder order = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(0); |
||||||
|
// ItemPrice 499.99 + tax 29.72 + Shipping 0.00 + tax 0.00
|
||||||
|
assertEquals("529.71", order.totalAmount().amount().toPlainString()); |
||||||
|
assertEquals("USD", order.totalAmount().currencyCode()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void shippedOrderHasShippedStatus() { |
||||||
|
SalesOrder order = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(1); |
||||||
|
assertEquals("Shipped", order.status()); |
||||||
|
assertEquals("Shipped", order.lines().get(0).status()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void partialShipmentKeepsOrderCreatedAndRecordsRealLineStatus() { |
||||||
|
// Created(2) + Shipped(1) of 3:还差 2 件没发,订单级别仍是 Created
|
||||||
|
List<SalesOrder> orders = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items(); |
||||||
|
SalesOrder partial = orders.get(2); |
||||||
|
assertEquals("108816631915373", partial.channelOrderId()); |
||||||
|
assertEquals("Created", partial.status()); |
||||||
|
// 行上是平台原值:状态列表最后一条
|
||||||
|
assertEquals("Shipped", partial.lines().get(0).status()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void fullyShippedHistoryResolvesToShippedNotCreated() { |
||||||
|
// Created(0) + Shipped(3) of 3:历史里残留 Created,但整行已发完
|
||||||
|
SalesOrder full = adapter(transport()).pull(context(), |
||||||
|
query("2026-11-01T00:00:00Z", "2026-11-02T00:00:00Z")).items().get(3); |
||||||
|
assertEquals("108816631915374", full.channelOrderId()); |
||||||
|
assertEquals("Shipped", full.status()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void getUnwrapsOrderEnvelope() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
SalesOrder order = adapter(transport).get(context(), |
||||||
|
common.ecommerce.channel.model.order.SalesOrderRef.of("108816631915371")); |
||||||
|
|
||||||
|
assertUrlContains(lastUrl(transport), ENDPOINT + "/v3/orders/108816631915371"); |
||||||
|
assertEquals("108816631915371", order.channelOrderId()); |
||||||
|
assertEquals("Astro Test", order.shipToAddress().name()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void getUrlEncodesOrderId() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/orders/", r -> Responses.ok(JsonFixture.load("fixtures/walmart/orders/detail.json"))); |
||||||
|
adapter(transport).get(context(), |
||||||
|
common.ecommerce.channel.model.order.SalesOrderRef.of("PO 1/2")); |
||||||
|
// 路径里的空格编成 %20,不是 +(+ 在路径里是字面量加号)
|
||||||
|
assertUrlContains(lastUrl(transport), "/v3/orders/PO%201%2F2"); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 能力
|
||||||
|
|
||||||
|
@Test |
||||||
|
void declaresOnlyReadCapabilities() { |
||||||
|
assertEquals(EnumSet.of(Capability.SALES_ORDER, Capability.PRODUCT, Capability.RETURNS), |
||||||
|
adapter(transport()).capabilities()); |
||||||
|
assertEquals(ChannelProvider.DIRECT, adapter(transport()).provider()); |
||||||
|
assertEquals(EnumSet.of(Platform.WALMART_SC), adapter(transport()).platforms()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void openOrderReconciliationFiltersByStatus() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
Page<SalesOrder> page = adapter(transport).pullOpenOrders(context(), null, null, null); |
||||||
|
|
||||||
|
String url = lastUrl(transport); |
||||||
|
assertUrlContains(url, "status=Created%2CAcknowledged"); |
||||||
|
assertEquals(5, page.size()); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- helpers
|
||||||
|
|
||||||
|
private static SalesOrderQuery query(String from, String to) { |
||||||
|
return SalesOrderQuery.builder() |
||||||
|
.updatedAfter(Instant.parse(from)) |
||||||
|
.updatedBefore(Instant.parse(to)) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
private static int countTokenRequests(RecordingTransport transport) { |
||||||
|
int count = 0; |
||||||
|
for (common.ecommerce.http.HttpRequest request : transport.recorded()) { |
||||||
|
if (request.url().contains(WalmartConstants.PATH_TOKEN)) { |
||||||
|
count++; |
||||||
|
} |
||||||
|
} |
||||||
|
return count; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,233 @@ |
|||||||
|
package common.ecommerce.walmart.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.product.ProductListing; |
||||||
|
import common.ecommerce.channel.model.product.ProductQuery; |
||||||
|
import common.ecommerce.channel.model.product.ProductSearchField; |
||||||
|
import common.ecommerce.channel.model.product.ProductStatus; |
||||||
|
import common.ecommerce.channel.model.product.ProductSyncStrategy; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.support.Page; |
||||||
|
import common.ecommerce.shared.testkit.JsonFixture; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Instant; |
||||||
|
import java.util.Arrays; |
||||||
|
import java.util.Collections; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.ENDPOINT; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.adapter; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.assertUrlContains; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.context; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.lastUrl; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** 沃尔玛商品:请求构造 + 响应映射 + 不支持的过滤条件必须显式报错。 */ |
||||||
|
class WalmartProductTest { |
||||||
|
|
||||||
|
private static final String TOKEN_BODY = JsonFixture.load("fixtures/walmart/token/success.json"); |
||||||
|
|
||||||
|
private RecordingTransport transport() { |
||||||
|
return RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/items/", r -> Responses.ok( |
||||||
|
"{\"sku\":\"5212572\",\"productName\":\"Detail Item\",\"publishedStatus\":\"PUBLISHED\"," |
||||||
|
+ "\"lifecycleStatus\":\"ACTIVE\",\"price\":{\"currency\":\"USD\",\"amount\":1.5}}")) |
||||||
|
.route("/v3/items", r -> Responses.ok(JsonFixture.load("fixtures/walmart/items/list.json"))); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 请求
|
||||||
|
|
||||||
|
@Test |
||||||
|
void pullSendsLimitAndCursor() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), ProductQuery.builder().pageSize(50).cursor("CUR").build()); |
||||||
|
|
||||||
|
String url = lastUrl(transport); |
||||||
|
assertUrlContains(url, ENDPOINT + WalmartConstants.PATH_ITEMS); |
||||||
|
assertUrlContains(url, "limit=50"); |
||||||
|
assertUrlContains(url, "nextCursor=CUR"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void limitIsCappedAtPlatformMaximum() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), ProductQuery.builder().pageSize(5_000).build()); |
||||||
|
assertUrlContains(lastUrl(transport), "limit=" + WalmartConstants.MAX_ITEM_PAGE_SIZE); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void skuSearchBecomesQueryParameter() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), ProductQuery.builder() |
||||||
|
.searchField(ProductSearchField.PLATFORM_SKU) |
||||||
|
.searchValue("ABC-1") |
||||||
|
.build()); |
||||||
|
assertUrlContains(lastUrl(transport), "sku=ABC-1"); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 不支持的过滤
|
||||||
|
|
||||||
|
@Test |
||||||
|
void timeWindowIsRejectedInsteadOfSilentlyIgnored() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).pull(context(), ProductQuery.builder() |
||||||
|
.updatedAfter(Instant.parse("2026-11-01T00:00:00Z")) |
||||||
|
.build())); |
||||||
|
assertTrue(ex.getMessage().contains("update-time filtering"), ex.getMessage()); |
||||||
|
// 本地拒绝:连 token 都不换
|
||||||
|
assertEquals(0, transport.recorded().size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void multiValueSearchIsRejected() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).pull(context(), ProductQuery.builder() |
||||||
|
.searchField(ProductSearchField.PLATFORM_SKU) |
||||||
|
.searchValues(Arrays.asList("A", "B")) |
||||||
|
.build())); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void localSkuSearchIsRejected() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).pull(context(), ProductQuery.builder() |
||||||
|
.searchField(ProductSearchField.LOCAL_SKU) |
||||||
|
.searchValue("LOCAL-1") |
||||||
|
.build())); |
||||||
|
assertTrue(ex.getMessage().contains("no local-sku"), ex.getMessage()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void syncStrategyIsFullPullDiff() { |
||||||
|
assertEquals(ProductSyncStrategy.FULL_PULL_DIFF, adapter(transport()).syncStrategy()); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 映射
|
||||||
|
|
||||||
|
@Test |
||||||
|
void mapsUnpublishedItem() { |
||||||
|
ProductListing p = adapter(transport()).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items().get(0); |
||||||
|
|
||||||
|
assertEquals("5212572", p.platformSku()); |
||||||
|
assertEquals("1YKTCEME6DEH", p.listingId()); |
||||||
|
assertEquals("00888555387476", p.gtin()); |
||||||
|
assertEquals("Obermeyer Kid's Ultra Gear Bottom", p.title()); |
||||||
|
assertEquals("USD", p.currency()); |
||||||
|
assertEquals("34.5", p.price().amount().toPlainString()); |
||||||
|
// 未发布即不可售,即使生命周期仍是 ACTIVE
|
||||||
|
assertEquals(ProductStatus.INACTIVE, p.status()); |
||||||
|
assertEquals("UNPUBLISHED/ACTIVE", p.rawStatus()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void mapsPublishedActiveItem() { |
||||||
|
ProductListing p = adapter(transport()).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items().get(1); |
||||||
|
assertEquals(ProductStatus.ACTIVE, p.status()); |
||||||
|
assertEquals("PUBLISHED/ACTIVE", p.rawStatus()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void archivedLifecycleMapsToInactiveEvenIfPublished() { |
||||||
|
ProductListing p = adapter(transport()).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items().get(2); |
||||||
|
assertEquals(ProductStatus.INACTIVE, p.status()); |
||||||
|
assertEquals("PUBLISHED/RETIRED", p.rawStatus()); |
||||||
|
// 没有 gtin 时回落 upc
|
||||||
|
assertEquals("888555387490", p.gtin()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void parsesShelfJsonString() { |
||||||
|
List<ProductListing> items = adapter(transport()).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items(); |
||||||
|
assertEquals(Collections.singletonList("UNNAV"), items.get(0).attributes().get("shelf")); |
||||||
|
assertEquals(Arrays.asList("Home Page", "Clothing"), items.get(1).attributes().get("shelf")); |
||||||
|
// 原文也保留一份,便于对照平台
|
||||||
|
assertEquals("[\"UNNAV\"]", items.get(0).attributes().get("shelfRaw")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void keepsUnpublishedReasonsInAttributes() { |
||||||
|
ProductListing p = adapter(transport()).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items().get(0); |
||||||
|
Object reasons = p.attributes().get("unpublishedReasons"); |
||||||
|
assertTrue(reasons instanceof List, String.valueOf(reasons)); |
||||||
|
assertEquals(2, ((List<?>) reasons).size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void malformedShelfFallsBackToRawString() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/items", r -> Responses.ok( |
||||||
|
"{\"ItemResponse\":[{\"sku\":\"S1\",\"shelf\":\"NOT_JSON\"," |
||||||
|
+ "\"publishedStatus\":\"PUBLISHED\",\"lifecycleStatus\":\"ACTIVE\"}]}")); |
||||||
|
ProductListing p = adapter(transport).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items().get(0); |
||||||
|
assertEquals(Collections.singletonList("NOT_JSON"), p.attributes().get("shelf")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void itemWithoutSkuIsSkipped() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/items", r -> Responses.ok( |
||||||
|
"{\"ItemResponse\":[{\"productName\":\"no sku\"},{\"sku\":\"S2\"}]}")); |
||||||
|
Page<ProductListing> page = adapter(transport).pull(context(), ProductQuery.builder().build()); |
||||||
|
assertEquals(1, page.size()); |
||||||
|
assertEquals("S2", page.items().get(0).platformSku()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nextCursorIsReturned() { |
||||||
|
Page<ProductListing> page = adapter(transport()).pull(context(), ProductQuery.builder().build()); |
||||||
|
assertEquals("FGluY2x1ZGQ==", page.nextCursor()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void getUsesSkuPath() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
ProductListing item = adapter(transport).get(context(), |
||||||
|
common.ecommerce.channel.model.product.ProductRef.of("5212572")); |
||||||
|
|
||||||
|
assertUrlContains(lastUrl(transport), ENDPOINT + "/v3/items/5212572"); |
||||||
|
assertEquals("Detail Item", item.title()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unknownStatusMapsToUnknown() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/items", r -> Responses.ok( |
||||||
|
"{\"ItemResponse\":[{\"sku\":\"S3\",\"publishedStatus\":\"WHATEVER\"}]}")); |
||||||
|
ProductListing p = adapter(transport).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items().get(0); |
||||||
|
assertEquals(ProductStatus.UNKNOWN, p.status()); |
||||||
|
assertEquals("WHATEVER/UNKNOWN", p.rawStatus()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void itemWithoutPriceHasNullPrice() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/items", r -> Responses.ok( |
||||||
|
"{\"ItemResponse\":[{\"sku\":\"S4\",\"publishedStatus\":\"PUBLISHED\"," |
||||||
|
+ "\"lifecycleStatus\":\"ACTIVE\"}]}")); |
||||||
|
ProductListing p = adapter(transport).pull(context(), ProductQuery.builder().build()) |
||||||
|
.items().get(0); |
||||||
|
assertNull(p.price()); |
||||||
|
assertNull(p.currency()); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,210 @@ |
|||||||
|
package common.ecommerce.walmart.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSale; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleQuery; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleType; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.support.Page; |
||||||
|
import common.ecommerce.shared.testkit.JsonFixture; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.LocalDate; |
||||||
|
import java.util.Collections; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.ENDPOINT; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.adapter; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.assertUrlContains; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.context; |
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.lastUrl; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** 沃尔玛售后:1 个退货单拆 N 个售后行 + 查询串型游标。 */ |
||||||
|
class WalmartReturnTest { |
||||||
|
|
||||||
|
private static final String TOKEN_BODY = JsonFixture.load("fixtures/walmart/token/success.json"); |
||||||
|
|
||||||
|
private RecordingTransport transport() { |
||||||
|
return RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns", r -> Responses.ok(JsonFixture.load("fixtures/walmart/returns/list.json"))); |
||||||
|
} |
||||||
|
|
||||||
|
private static AfterSaleQuery query() { |
||||||
|
return AfterSaleQuery.builder() |
||||||
|
.startDate(LocalDate.of(2026, 11, 1)) |
||||||
|
.endDate(LocalDate.of(2026, 11, 18)) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 请求
|
||||||
|
|
||||||
|
@Test |
||||||
|
void pullSendsCreatedWindowAndLimit() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), query()); |
||||||
|
|
||||||
|
String url = lastUrl(transport); |
||||||
|
assertUrlContains(url, ENDPOINT + WalmartConstants.PATH_RETURNS); |
||||||
|
assertUrlContains(url, "createdStartDate=2026-11-01T00%3A00%3A00.000Z"); |
||||||
|
assertUrlContains(url, "createdEndDate=2026-11-18T00%3A00%3A00.000Z"); |
||||||
|
assertUrlContains(url, "limit=100"); |
||||||
|
assertUrlContains(url, "offset=0"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void cursorIsASingleQueryStringAppendedAsIs() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
adapter(transport).pull(context(), query().toBuilder() |
||||||
|
.cursor("?sellerId=151&limit=10&offset=10") |
||||||
|
.build()); |
||||||
|
|
||||||
|
String url = lastUrl(transport); |
||||||
|
// 游标整串追加,不再二次编码,也不重复加 ?
|
||||||
|
assertUrlContains(url, ENDPOINT + WalmartConstants.PATH_RETURNS |
||||||
|
+ "?sellerId=151&limit=10&offset=10"); |
||||||
|
assertEquals(1, countOccurrences(url, '?'), url); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nonSaleTimeDateTypeIsRejected() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).pull(context(), query().toBuilder() |
||||||
|
.dateType(AfterSaleQuery.DateType.UPDATE_TIME) |
||||||
|
.build())); |
||||||
|
assertTrue(ex.getMessage().contains("return-created date"), ex.getMessage()); |
||||||
|
assertEquals(0, transport.recorded().size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void orderIdFilterIsRejected() { |
||||||
|
RecordingTransport transport = transport(); |
||||||
|
assertThrows(ValidationException.class, |
||||||
|
() -> adapter(transport).pull(context(), query().toBuilder() |
||||||
|
.channelOrderIds(Collections.singletonList("123")) |
||||||
|
.build())); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 映射
|
||||||
|
|
||||||
|
@Test |
||||||
|
void oneReturnOrderExpandsToAllLines() { |
||||||
|
Page<AfterSale> page = adapter(transport()).pull(context(), query()); |
||||||
|
// 一个退货单里两个退货行
|
||||||
|
assertEquals(2, page.size()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void mapsFirstLine() { |
||||||
|
AfterSale a = adapter(transport()).pull(context(), query()).items().get(0); |
||||||
|
|
||||||
|
assertEquals("103738048909818825:1", a.afterSaleId()); |
||||||
|
assertEquals("4790210558890", a.channelOrderId()); |
||||||
|
// REPLACEMENT → EXCHANGE
|
||||||
|
assertEquals(AfterSaleType.EXCHANGE, a.type()); |
||||||
|
assertEquals("REPLACEMENT", a.rawType()); |
||||||
|
assertEquals("COMPLETED", a.status()); |
||||||
|
assertEquals("ARRIVED_LATE", a.reason()); |
||||||
|
// 退货接口的数量是数字,不是字符串
|
||||||
|
assertEquals(3, a.quantity()); |
||||||
|
assertEquals("ANTL_GDL-0700", a.platformSku()); |
||||||
|
// 应退金额:chargeTotals 里的 lineTotal(退货行合计)优先
|
||||||
|
assertEquals("359.85", a.refundAmount().amount().toPlainString()); |
||||||
|
// 已退金额:refundedQty(1) × unitPrice(119.95),与应退分开
|
||||||
|
assertEquals("119.95 USD", a.attributes().get("refundedAmount")); |
||||||
|
assertEquals("USD", a.refundAmount().currencyCode()); |
||||||
|
assertEquals("FEDEX", a.carrier()); |
||||||
|
assertEquals("785611449666", a.trackingNumber()); |
||||||
|
assertEquals("1234567891234", a.exchangeOrderId()); |
||||||
|
assertNotNull(a.afterSaleTime()); |
||||||
|
assertEquals("2019-02-21T01:01:08Z", a.afterSaleTime().utc().toString()); |
||||||
|
assertEquals("2019-03-02T05:45:45Z", a.updatedAt().utc().toString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void refundFallsBackToUnitPriceTimesQuantity() { |
||||||
|
AfterSale a = adapter(transport()).pull(context(), query()).items().get(1); |
||||||
|
// 第二行没有 chargeTotals:79.5 × 1 = 79.5(不做额外舍入)
|
||||||
|
assertEquals("79.5", a.refundAmount().amount().toPlainString()); |
||||||
|
// 第二行没有分组面单,承运商为空
|
||||||
|
assertNull(a.carrier()); |
||||||
|
assertNull(a.trackingNumber()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void keepsRefundDetailInAttributes() { |
||||||
|
AfterSale a = adapter(transport()).pull(context(), query()).items().get(0); |
||||||
|
assertEquals("POST_DELIVERY", a.attributes().get("refundMode")); |
||||||
|
assertEquals("IN_STORE", a.attributes().get("returnChannel")); |
||||||
|
assertEquals("REFUND_INITIATED", a.attributes().get("currentRefundStatus")); |
||||||
|
assertEquals("NOT_SHIPPED", a.attributes().get("currentDeliveryStatus")); |
||||||
|
assertEquals(Boolean.TRUE, a.attributes().get("returnExpectedFlag")); |
||||||
|
assertEquals("127.45 USD", a.attributes().get("totalRefundAmount")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void lineStatusTimeIsUsedForUpdateTime() { |
||||||
|
AfterSale a = adapter(transport()).pull(context(), query()).items().get(1); |
||||||
|
assertEquals("IN_TRANSIT", a.status()); |
||||||
|
assertEquals("2019-03-01T00:00:00Z", a.updatedAt().utc().toString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nextCursorIsTheRawQueryString() { |
||||||
|
assertEquals("?sellerId=151&limit=10&offset=10", |
||||||
|
adapter(transport()).pull(context(), query()).nextCursor()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void returnWithoutLinesIsDropped() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns", r -> Responses.ok( |
||||||
|
"{\"meta\":{\"totalCount\":0},\"returnOrders\":[{\"returnOrderId\":\"R1\"}]}")); |
||||||
|
List<AfterSale> items = adapter(transport).pull(context(), query()).items(); |
||||||
|
assertTrue(items.isEmpty()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unknownReturnTypeMapsToUnknown() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns", r -> Responses.ok( |
||||||
|
"{\"returnOrders\":[{\"returnOrderId\":\"R2\",\"returnType\":\"SOMETHING\"," |
||||||
|
+ "\"returnOrderLines\":[{\"returnOrderLineNumber\":1,\"status\":\"INITIATED\"}]}]}")); |
||||||
|
AfterSale a = adapter(transport).pull(context(), query()).items().get(0); |
||||||
|
assertEquals(AfterSaleType.UNKNOWN, a.type()); |
||||||
|
assertEquals("SOMETHING", a.rawType()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void badStatusTimeDoesNotBreakThePage() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route("/v3/token", r -> Responses.ok(TOKEN_BODY)) |
||||||
|
.route("/v3/returns", r -> Responses.ok( |
||||||
|
"{\"returnOrders\":[{\"returnOrderId\":\"R3\",\"returnOrderDate\":\"not-a-date\"," |
||||||
|
+ "\"returnOrderLines\":[{\"returnOrderLineNumber\":1," |
||||||
|
+ "\"statusTime\":\"2026-13-45\"}]}]}")); |
||||||
|
AfterSale a = adapter(transport).pull(context(), query()).items().get(0); |
||||||
|
assertNull(a.afterSaleTime()); |
||||||
|
assertNull(a.updatedAt()); |
||||||
|
} |
||||||
|
|
||||||
|
private static int countOccurrences(String text, char c) { |
||||||
|
int count = 0; |
||||||
|
for (int i = 0; i < text.length(); i++) { |
||||||
|
if (text.charAt(i) == c) { |
||||||
|
count++; |
||||||
|
} |
||||||
|
} |
||||||
|
return count; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,131 @@ |
|||||||
|
package common.ecommerce.walmart.enums; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleType; |
||||||
|
import common.ecommerce.channel.model.product.ProductStatus; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.util.Arrays; |
||||||
|
import java.util.Collections; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
|
||||||
|
/** 状态映射的边界值:精确匹配、未知值、空值。 */ |
||||||
|
class WalmartStatusMappingTest { |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 订单状态聚合
|
||||||
|
|
||||||
|
@Test |
||||||
|
void singleCreatedLineIsCreated() { |
||||||
|
assertEquals(WalmartOrderStatus.CREATED, |
||||||
|
WalmartOrderStatus.aggregate(Collections.singletonList("Created"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void acknowledgedOnlyIsAcknowledged() { |
||||||
|
assertEquals(WalmartOrderStatus.ACKNOWLEDGED, |
||||||
|
WalmartOrderStatus.aggregate(Collections.singletonList("Acknowledged"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void allCancelledIsCancelled() { |
||||||
|
assertEquals(WalmartOrderStatus.CANCELLED, |
||||||
|
WalmartOrderStatus.aggregate(Arrays.asList("Cancelled", "Cancelled"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void allDeliveredIsDelivered() { |
||||||
|
assertEquals(WalmartOrderStatus.DELIVERED, |
||||||
|
WalmartOrderStatus.aggregate(Arrays.asList("Delivered", "Delivered"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void partiallyShippedStaysCreatedBecauseLinesRemain() { |
||||||
|
// 还有未发货的行:订单仍需发货动作,逐行状态看 OrderLine.status()
|
||||||
|
assertEquals(WalmartOrderStatus.CREATED, |
||||||
|
WalmartOrderStatus.aggregate(Arrays.asList("Created", "Shipped"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void shippedAndCancelledMixIsShipped() { |
||||||
|
assertEquals(WalmartOrderStatus.SHIPPED, |
||||||
|
WalmartOrderStatus.aggregate(Arrays.asList("Shipped", "Cancelled"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void createdWinsOverAcknowledged() { |
||||||
|
assertEquals(WalmartOrderStatus.CREATED, |
||||||
|
WalmartOrderStatus.aggregate(Arrays.asList("Acknowledged", "Created"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unknownValueIsIgnoredButDoesNotPoison() { |
||||||
|
assertEquals(WalmartOrderStatus.CREATED, |
||||||
|
WalmartOrderStatus.aggregate(Arrays.asList("Created", "Bogus"))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void allUnknownIsUnknown() { |
||||||
|
assertEquals(WalmartOrderStatus.UNKNOWN, |
||||||
|
WalmartOrderStatus.aggregate(Arrays.asList("Bogus", null))); |
||||||
|
assertEquals(WalmartOrderStatus.UNKNOWN, WalmartOrderStatus.aggregate(Collections.<String>emptyList())); |
||||||
|
assertEquals(WalmartOrderStatus.UNKNOWN, WalmartOrderStatus.aggregate(null)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void matchingIsExactNotContains() { |
||||||
|
// 模糊匹配会把 "NotCreated" 判成 Created
|
||||||
|
assertEquals(WalmartOrderStatus.UNKNOWN, WalmartOrderStatus.fromRaw("NotCreated")); |
||||||
|
assertEquals(WalmartOrderStatus.UNKNOWN, WalmartOrderStatus.fromRaw("created")); |
||||||
|
assertEquals(WalmartOrderStatus.CREATED, WalmartOrderStatus.fromRaw("Created")); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 商品状态
|
||||||
|
|
||||||
|
@Test |
||||||
|
void publishedActiveIsActive() { |
||||||
|
assertEquals(ProductStatus.ACTIVE, |
||||||
|
WalmartPublishedStatus.toProductStatus("PUBLISHED", "ACTIVE")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void publishedArchivedIsInactive() { |
||||||
|
assertEquals(ProductStatus.INACTIVE, |
||||||
|
WalmartPublishedStatus.toProductStatus("PUBLISHED", "ARCHIVED")); |
||||||
|
assertEquals(ProductStatus.INACTIVE, |
||||||
|
WalmartPublishedStatus.toProductStatus("PUBLISHED", "RETIRED")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unpublishedAnythingIsInactive() { |
||||||
|
assertEquals(ProductStatus.INACTIVE, |
||||||
|
WalmartPublishedStatus.toProductStatus("UNPUBLISHED", "ACTIVE")); |
||||||
|
assertEquals(ProductStatus.INACTIVE, |
||||||
|
WalmartPublishedStatus.toProductStatus("STAGE", "ACTIVE")); |
||||||
|
assertEquals(ProductStatus.INACTIVE, |
||||||
|
WalmartPublishedStatus.toProductStatus("IN_PROGRESS", null)); |
||||||
|
assertEquals(ProductStatus.INACTIVE, |
||||||
|
WalmartPublishedStatus.toProductStatus("SYSTEM_PROBLEM", null)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unknownPublishedStatusIsUnknown() { |
||||||
|
assertEquals(ProductStatus.UNKNOWN, WalmartPublishedStatus.toProductStatus(null, "ACTIVE")); |
||||||
|
assertEquals(ProductStatus.UNKNOWN, WalmartPublishedStatus.toProductStatus("BOGUS", "ACTIVE")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void rawStatusCombinesBothDimensions() { |
||||||
|
assertEquals("UNPUBLISHED/ACTIVE", WalmartPublishedStatus.rawStatus("UNPUBLISHED", "ACTIVE")); |
||||||
|
assertEquals("UNKNOWN/UNKNOWN", WalmartPublishedStatus.rawStatus(null, null)); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 售后类型
|
||||||
|
|
||||||
|
@Test |
||||||
|
void returnTypeMapping() { |
||||||
|
assertEquals(AfterSaleType.RETURN, WalmartReturnType.toCore("RETURN")); |
||||||
|
assertEquals(AfterSaleType.EXCHANGE, WalmartReturnType.toCore("REPLACEMENT")); |
||||||
|
assertEquals(AfterSaleType.UNKNOWN, WalmartReturnType.toCore("SOMETHING")); |
||||||
|
assertEquals(AfterSaleType.UNKNOWN, WalmartReturnType.toCore(null)); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,132 @@ |
|||||||
|
package common.ecommerce.walmart.http; |
||||||
|
|
||||||
|
import common.ecommerce.channel.sdk.ChannelContext; |
||||||
|
import common.ecommerce.http.HttpResponse; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.shared.error.AuthException; |
||||||
|
import common.ecommerce.shared.error.RateLimitException; |
||||||
|
import common.ecommerce.shared.error.TransientException; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.testkit.JsonFixture; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.util.Collections; |
||||||
|
|
||||||
|
import static common.ecommerce.walmart.support.WalmartTestSupport.context; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** 两种错误格式的解析与异常分类。 */ |
||||||
|
class WalmartErrorsTest { |
||||||
|
|
||||||
|
private static final JacksonJsonCodec JSON = new JacksonJsonCodec(); |
||||||
|
|
||||||
|
private final WalmartErrors errors = new WalmartErrors(JSON); |
||||||
|
private final ChannelContext ctx = context(); |
||||||
|
|
||||||
|
@Test |
||||||
|
void gatewayErrorFormatCarriesCodeAndDescription() { |
||||||
|
HttpResponse response = Responses.withHeaders(400, |
||||||
|
Collections.<String, String>emptyMap(), |
||||||
|
JsonFixture.load("fixtures/walmart/errors/gateway-404.json")); |
||||||
|
|
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> errors.throwIfError(response, ctx, "afterSales.pull")); |
||||||
|
|
||||||
|
assertEquals("CONTENT_NOT_FOUND.GMP_GATEWAY_API", ex.platformCode()); |
||||||
|
assertTrue(ex.getMessage().contains("CONTENT_NOT_FOUND.GMP_GATEWAY_API"), ex.getMessage()); |
||||||
|
assertTrue(ex.getMessage().contains("No static resource"), ex.getMessage()); |
||||||
|
assertEquals("req-1", ex.requestId()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void routeLevelErrorFormatFallsBackToStatusAndMessage() { |
||||||
|
HttpResponse response = Responses.status(404, |
||||||
|
JsonFixture.load("fixtures/walmart/errors/route-404.json")); |
||||||
|
|
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> errors.throwIfError(response, ctx, "salesOrders.get")); |
||||||
|
|
||||||
|
// 没有业务码时用 HTTP 状态码兜底,消息里带平台原文
|
||||||
|
assertEquals("404", ex.platformCode()); |
||||||
|
assertTrue(ex.getMessage().contains("Request Not Found"), ex.getMessage()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void authFailureIsAuthException() { |
||||||
|
HttpResponse response = Responses.status(401, "{\"error\":[{\"code\":\"UNAUTHORIZED\"}]}"); |
||||||
|
assertThrows(AuthException.class, () -> errors.throwIfError(response, ctx, "salesOrders.pull")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void rateLimitHonoursRetryAfter() { |
||||||
|
RateLimitException ex = assertThrows(RateLimitException.class, |
||||||
|
() -> errors.throwIfError(Responses.rateLimited("7"), ctx, "products.pull")); |
||||||
|
assertEquals(7_000L, ex.retryAfterMillis()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void rateLimitWithoutHeaderUsesOneSecond() { |
||||||
|
RateLimitException ex = assertThrows(RateLimitException.class, |
||||||
|
() -> errors.throwIfError(Responses.status(429, ""), ctx, "products.pull")); |
||||||
|
assertEquals(1_000L, ex.retryAfterMillis()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void serverErrorIsRetryable() { |
||||||
|
TransientException ex = assertThrows(TransientException.class, |
||||||
|
() -> errors.throwIfError(Responses.status(520, "{\"error\":\"boom\"}"), ctx, "products.pull")); |
||||||
|
assertTrue(ex.retryable()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void systemErrorCodeOn4xxIsAlsoRetryable() { |
||||||
|
// 平台侧数据状态问题:HTTP 是 4xx,但重跑常能成功
|
||||||
|
HttpResponse response = Responses.status(400, |
||||||
|
"{\"error\":[{\"code\":\"SYSTEM_ERROR.GMP_DATA_STATUS_API\",\"description\":\"try later\"}]}"); |
||||||
|
TransientException ex = assertThrows(TransientException.class, |
||||||
|
() -> errors.throwIfError(response, ctx, "salesOrders.pull")); |
||||||
|
assertTrue(ex.retryable()); |
||||||
|
assertEquals("SYSTEM_ERROR.GMP_DATA_STATUS_API", ex.platformCode()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void unknown4xxCodeIsNotGuessedAsRetryable() { |
||||||
|
// 文档实测只有 CONTENT_NOT_FOUND.* 与 SYSTEM_ERROR.*;其余 4xx 按数据错误处理,
|
||||||
|
// 不做前缀猜测——猜错会把可重试错误判成终态
|
||||||
|
HttpResponse response = Responses.status(400, |
||||||
|
"{\"error\":[{\"code\":\"SOME_UNKNOWN.CODE\",\"description\":\"nope\"}]}"); |
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> errors.throwIfError(response, ctx, "salesOrders.pull")); |
||||||
|
assertEquals("SOME_UNKNOWN.CODE", ex.platformCode()); |
||||||
|
assertFalse(ex.retryable()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void successPassesThrough() { |
||||||
|
errors.throwIfError(Responses.ok("{}"), ctx, "salesOrders.pull"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void emptyBodyStillThrowsByStatus() { |
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> errors.throwIfError(Responses.status(400, ""), ctx, "products.get")); |
||||||
|
assertEquals("400", ex.platformCode()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void rawResponseIsTruncated() { |
||||||
|
StringBuilder big = new StringBuilder("{\"error\":[{\"description\":\""); |
||||||
|
for (int i = 0; i < 5_000; i++) { |
||||||
|
big.append('x'); |
||||||
|
} |
||||||
|
big.append("\"}]}"); |
||||||
|
ValidationException ex = assertThrows(ValidationException.class, |
||||||
|
() -> errors.throwIfError(Responses.status(400, big.toString()), ctx, "products.get")); |
||||||
|
assertEquals(common.ecommerce.walmart.WalmartConstants.RAW_RESPONSE_LIMIT, |
||||||
|
ex.rawResponse().length()); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,319 @@ |
|||||||
|
package common.ecommerce.walmart.probe; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSale; |
||||||
|
import common.ecommerce.channel.model.aftersale.AfterSaleQuery; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrder; |
||||||
|
import common.ecommerce.channel.model.order.SalesOrderQuery; |
||||||
|
import common.ecommerce.channel.model.product.ProductListing; |
||||||
|
import common.ecommerce.channel.model.product.ProductQuery; |
||||||
|
import common.ecommerce.channel.model.product.ProductSearchField; |
||||||
|
import common.ecommerce.channel.sdk.ChannelConnection; |
||||||
|
import common.ecommerce.channel.sdk.ChannelContext; |
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.http.HttpResponse; |
||||||
|
import common.ecommerce.http.HttpTransport; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.http.OkHttpTransport; |
||||||
|
import common.ecommerce.shared.error.ChannelException; |
||||||
|
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.walmart.adapter.WalmartAdapter; |
||||||
|
import common.ecommerce.walmart.support.WalmartTestSupport; |
||||||
|
import org.junit.jupiter.api.MethodOrderer; |
||||||
|
import org.junit.jupiter.api.Order; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
import org.junit.jupiter.api.TestInstance; |
||||||
|
import org.junit.jupiter.api.TestMethodOrder; |
||||||
|
import org.junit.jupiter.api.condition.EnabledIfSystemProperty; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.LocalDate; |
||||||
|
import java.time.ZoneOffset; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛沙箱探针(<b>只读</b>)。 |
||||||
|
* |
||||||
|
* <p>默认跳过,用 {@code -Dwalmart.probe=true} 显式开启;凭据走系统属性, |
||||||
|
* <b>真实凭据不入库</b>:</p> |
||||||
|
* |
||||||
|
* <pre> |
||||||
|
* mvn -pl channel-sdk-walmart -am -DfailIfNoTests=false \ |
||||||
|
* -Dwalmart.probe=true \ |
||||||
|
* -Dwalmart.probe.clientId=你的clientId \ |
||||||
|
* -Dwalmart.probe.clientSecret=你的clientSecret \ |
||||||
|
* -Dtest=WalmartProbeTest test |
||||||
|
* </pre> |
||||||
|
* |
||||||
|
* <p>可选:{@code -Dwalmart.probe.baseUrl=https://marketplace.walmartapis.com} 打生产环境
|
||||||
|
* (<b>只跑读接口</b>),{@code -Dwalmart.probe.sku=SKU} 单独查一个商品。</p> |
||||||
|
* |
||||||
|
* <h2>沙箱已知限制(2026-11-16 实测)</h2> |
||||||
|
* <table> |
||||||
|
* <tr><th>接口</th><th>沙箱行为</th></tr> |
||||||
|
* <tr><td>GET /v3/items</td><td>固定 20 条,limit / sku / nextCursor 过滤不生效</td></tr> |
||||||
|
* <tr><td>GET /v3/items/{sku}</td><td>404,mock 未实现</td></tr> |
||||||
|
* <tr><td>GET /v3/orders</td><td>固定 12 条,过滤参数是否生效以生产为准</td></tr> |
||||||
|
* <tr><td>GET /v3/returns</td><td>固定 10 条 totalCount=30,过滤参数不生效</td></tr> |
||||||
|
* </table> |
||||||
|
* |
||||||
|
* <p>因此探针<b>不把 404 / 固定条数当失败</b>,只打印原始报文,方便逐条核对字段; |
||||||
|
* 唯一硬断言是 token 能换到。</p> |
||||||
|
*/ |
||||||
|
@EnabledIfSystemProperty(named = "walmart.probe", matches = "true") |
||||||
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) |
||||||
|
@TestInstance(TestInstance.Lifecycle.PER_CLASS) |
||||||
|
class WalmartProbeTest { |
||||||
|
|
||||||
|
// 真实凭据不入库:本地跑探针时用 -D 传入
|
||||||
|
private static final String CLIENT_ID = System.getProperty("walmart.probe.clientId", ""); |
||||||
|
private static final String CLIENT_SECRET = System.getProperty("walmart.probe.clientSecret", ""); |
||||||
|
private static final String BASE_URL = System.getProperty("walmart.probe.baseUrl", |
||||||
|
common.ecommerce.walmart.WalmartConstants.SANDBOX_BASE_URL); |
||||||
|
private static final String SKU = System.getProperty("walmart.probe.sku", ""); |
||||||
|
|
||||||
|
private static final JacksonJsonCodec JSON = new JacksonJsonCodec(); |
||||||
|
|
||||||
|
/** 打印用;真实 token 不打印,只打印前 12 位指纹。 */ |
||||||
|
private final LoggingTransport transport = new LoggingTransport( |
||||||
|
new OkHttpTransport("common-ecommerce-walmart-probe")); |
||||||
|
|
||||||
|
private final WalmartAdapter adapter = new WalmartAdapter(transport, JSON, |
||||||
|
new InMemoryTokenStore(), new InMemoryLockProvider(), Clock.systemUTC()); |
||||||
|
|
||||||
|
/** 最近一次拉到的售后行;详情探针按它取一个 returnOrderId。 */ |
||||||
|
private List<AfterSale> lastAfterSales = new ArrayList<AfterSale>(); |
||||||
|
|
||||||
|
private final ChannelContext ctx = ChannelContext.of( |
||||||
|
WalmartTestSupport.account("probe-store"), |
||||||
|
ChannelConnection.of(BASE_URL, ChannelSecret.builder() |
||||||
|
.clientId(CLIENT_ID).clientSecret(CLIENT_SECRET).build()), |
||||||
|
"probe-1", Clock.systemUTC()); |
||||||
|
|
||||||
|
@Test |
||||||
|
@Order(1) |
||||||
|
void probeOrderList() { |
||||||
|
requireCredentials(); |
||||||
|
section("GET /v3/orders createdStartDate=[now-7d, now]"); |
||||||
|
Instant to = Instant.now(); |
||||||
|
Instant from = to.minusSeconds(7 * 24 * 3600L); |
||||||
|
probe(() -> { |
||||||
|
Page<SalesOrder> page = adapter.pull(ctx, SalesOrderQuery.builder() |
||||||
|
.updatedAfter(from).updatedBefore(to).pageSize(5).build()); |
||||||
|
System.out.println("orders=" + page.size() + " nextCursor=" + page.nextCursor()); |
||||||
|
for (SalesOrder order : page.items()) { |
||||||
|
System.out.println(" " + order.channelOrderId() |
||||||
|
+ " status=" + order.status() |
||||||
|
+ " buyer=" + order.buyerName() |
||||||
|
+ " addr=" + order.shipToAddress() |
||||||
|
+ " lines=" + order.lines().size() |
||||||
|
+ " total=" + order.totalAmount() |
||||||
|
+ " at=" + order.occurredAt()); |
||||||
|
order.lines().forEach(line -> System.out.println(" line " + line.lineId() |
||||||
|
+ " sku=" + line.platformSku() |
||||||
|
+ " qty=" + line.quantity() |
||||||
|
+ " status=" + line.status() |
||||||
|
+ " unitPrice=" + line.unitPrice() |
||||||
|
+ " tax=" + line.tax())); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
@Order(2) |
||||||
|
void probeOrderDetail() { |
||||||
|
requireCredentials(); |
||||||
|
List<SalesOrder> orders = ordersOfLastWindow(); |
||||||
|
if (orders.isEmpty()) { |
||||||
|
System.out.println("skip detail: no order in last 7 days"); |
||||||
|
return; |
||||||
|
} |
||||||
|
String id = orders.get(0).channelOrderId(); |
||||||
|
section("GET /v3/orders/" + id); |
||||||
|
probe(() -> { |
||||||
|
SalesOrder order = adapter.get(ctx, |
||||||
|
common.ecommerce.channel.model.order.SalesOrderRef.of(id)); |
||||||
|
System.out.println("status=" + order.status() + " addr=" + order.shipToAddress()); |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
@Order(3) |
||||||
|
void probeItemList() { |
||||||
|
requireCredentials(); |
||||||
|
section("GET /v3/items?limit=20"); |
||||||
|
probe(() -> { |
||||||
|
Page<ProductListing> page = adapter.pull(ctx, ProductQuery.builder().pageSize(20).build()); |
||||||
|
System.out.println("items=" + page.size() + " nextCursor=" + page.nextCursor()); |
||||||
|
for (ProductListing item : page.items()) { |
||||||
|
System.out.println(" " + item.platformSku() |
||||||
|
+ " status=" + item.status() + "/" + item.rawStatus() |
||||||
|
+ " price=" + item.price() |
||||||
|
+ " shelf=" + item.attributes().get("shelf") |
||||||
|
+ " reasons=" + item.attributes().get("unpublishedReasons")); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
@Order(4) |
||||||
|
void probeItemSearchAndDetail() { |
||||||
|
requireCredentials(); |
||||||
|
String sku = SKU.isEmpty() ? "5212572" : SKU; |
||||||
|
section("GET /v3/items?sku=" + sku + "(沙箱可能忽略该过滤)"); |
||||||
|
probe(() -> { |
||||||
|
Page<ProductListing> page = adapter.pull(ctx, ProductQuery.builder() |
||||||
|
.searchField(ProductSearchField.PLATFORM_SKU).searchValue(sku).build()); |
||||||
|
System.out.println("items=" + page.size() + " (沙箱固定 20 条属正常)"); |
||||||
|
}); |
||||||
|
|
||||||
|
section("GET /v3/items/" + sku + "(沙箱 404 属正常)"); |
||||||
|
probe(() -> System.out.println("detail=" + adapter.get(ctx, |
||||||
|
common.ecommerce.channel.model.product.ProductRef.of(sku)))); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
@Order(5) |
||||||
|
void probeReturns() { |
||||||
|
requireCredentials(); |
||||||
|
LocalDate today = LocalDate.now(ZoneOffset.UTC); |
||||||
|
section("GET /v3/returns createdStartDate=[" + today.minusDays(7) + ", " + today + "]"); |
||||||
|
probe(() -> { |
||||||
|
Page<AfterSale> page = adapter.pull(ctx, AfterSaleQuery.builder() |
||||||
|
.startDate(today.minusDays(7)).endDate(today).pageSize(10).build()); |
||||||
|
lastAfterSales = page.items(); |
||||||
|
System.out.println("afterSales=" + page.size() + " nextCursor=" + page.nextCursor()); |
||||||
|
for (AfterSale a : page.items()) { |
||||||
|
System.out.println(" " + a.afterSaleId() |
||||||
|
+ " type=" + a.type() + "/" + a.rawType() |
||||||
|
+ " status=" + a.status() |
||||||
|
+ " qty=" + a.quantity() |
||||||
|
+ " refund=" + a.refundAmount() |
||||||
|
+ " carrier=" + a.carrier() |
||||||
|
+ " tracking=" + a.trackingNumber() |
||||||
|
+ " refundStatus=" + a.attributes().get("currentRefundStatus")); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
@Order(6) |
||||||
|
void probeReturnDetail() { |
||||||
|
requireCredentials(); |
||||||
|
List<AfterSale> page = lastAfterSales; |
||||||
|
if (page.isEmpty()) { |
||||||
|
System.out.println("skip return detail: no return in last 7 days (sandbox mock is fixed data)"); |
||||||
|
return; |
||||||
|
} |
||||||
|
String id = String.valueOf(page.get(0).attributes().get("returnOrderId")); |
||||||
|
section("GET /v3/returns/" + id + "(沙箱 404 属正常)"); |
||||||
|
probe(() -> { |
||||||
|
List<AfterSale> lines = adapter.getReturn(ctx, id); |
||||||
|
System.out.println("detail afterSales=" + lines.size()); |
||||||
|
for (AfterSale a : lines) { |
||||||
|
System.out.println(" " + a.afterSaleId() + " status=" + a.status() |
||||||
|
+ " refund=" + a.refundAmount()); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
@Order(7) |
||||||
|
void probeOrderShipping() { |
||||||
|
requireCredentials(); |
||||||
|
List<SalesOrder> orders = ordersOfLastWindow(); |
||||||
|
if (orders.isEmpty()) { |
||||||
|
System.out.println("skip shipping: no order in last 7 days"); |
||||||
|
return; |
||||||
|
} |
||||||
|
String id = orders.get(0).channelOrderId(); |
||||||
|
section("GET /v3/orders/" + id + "/shipping(沙箱 404 属正常)"); |
||||||
|
probe(() -> { |
||||||
|
List<common.ecommerce.walmart.mapper.WalmartShipmentMapper.ShipmentLine> lines = |
||||||
|
adapter.getShipping(ctx, id); |
||||||
|
System.out.println("shipped lines=" + lines.size()); |
||||||
|
for (common.ecommerce.walmart.mapper.WalmartShipmentMapper.ShipmentLine line : lines) { |
||||||
|
System.out.println(" " + line); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
|
||||||
|
// ---------------------------------------------------------------- internals
|
||||||
|
|
||||||
|
/** 探针不因平台 404 / 固定条数失败:打印异常后继续跑下一段。 */ |
||||||
|
private static void probe(Runnable action) { |
||||||
|
try { |
||||||
|
action.run(); |
||||||
|
} catch (ChannelException e) { |
||||||
|
System.out.println(" !! " + e.getClass().getSimpleName() |
||||||
|
+ " code=" + e.platformCode() + " : " + e.getMessage()); |
||||||
|
} catch (RuntimeException e) { |
||||||
|
System.out.println(" !! " + e.getClass().getSimpleName() + " : " + e.getMessage()); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private List<SalesOrder> ordersOfLastWindow() { |
||||||
|
List<SalesOrder> out = new ArrayList<SalesOrder>(); |
||||||
|
try { |
||||||
|
Instant to = Instant.now(); |
||||||
|
out.addAll(adapter.pull(ctx, SalesOrderQuery.builder() |
||||||
|
.updatedAfter(to.minusSeconds(7 * 24 * 3600L)).updatedBefore(to).build()).items()); |
||||||
|
} catch (RuntimeException e) { |
||||||
|
System.out.println(" order window unavailable: " + e.getMessage()); |
||||||
|
} |
||||||
|
return out; |
||||||
|
} |
||||||
|
|
||||||
|
private static void requireCredentials() { |
||||||
|
assertTrue(!CLIENT_ID.isEmpty() && !CLIENT_SECRET.isEmpty(), |
||||||
|
"set -Dwalmart.probe.clientId=... -Dwalmart.probe.clientSecret=... " |
||||||
|
+ "(或用环境变量注入后转成系统属性)"); |
||||||
|
} |
||||||
|
|
||||||
|
private static void section(String title) { |
||||||
|
System.out.println("\n========== " + title + " =========="); |
||||||
|
} |
||||||
|
|
||||||
|
/** 打印请求与响应摘要;token 头只打印前缀。 */ |
||||||
|
private static final class LoggingTransport implements HttpTransport { |
||||||
|
|
||||||
|
private final HttpTransport delegate; |
||||||
|
|
||||||
|
private LoggingTransport(HttpTransport delegate) { |
||||||
|
this.delegate = delegate; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public HttpResponse execute(HttpRequest request) { |
||||||
|
System.out.println("-> " + request.method() + " " + request.url()); |
||||||
|
System.out.println(" corr=" + request.headers().get("WM_QOS.CORRELATION_ID") |
||||||
|
+ " token=" + mask(request.headers().get("WM_SEC.ACCESS_TOKEN")) |
||||||
|
+ " count=" + request.headers().get("x-current-token-count")); |
||||||
|
HttpResponse response = delegate.execute(request); |
||||||
|
System.out.println("<- " + response.statusCode() |
||||||
|
+ " tokenCount=" + response.header("x-current-token-count") |
||||||
|
+ " body=" + shorten(response.body())); |
||||||
|
return response; |
||||||
|
} |
||||||
|
|
||||||
|
private static String mask(String token) { |
||||||
|
if (token == null) { |
||||||
|
return "null"; |
||||||
|
} |
||||||
|
return token.length() <= 12 ? "***" : token.substring(0, 12) + "..."; |
||||||
|
} |
||||||
|
|
||||||
|
private static String shorten(String body) { |
||||||
|
if (body == null) { |
||||||
|
return "null"; |
||||||
|
} |
||||||
|
return body.length() <= 1_200 ? body : body.substring(0, 1_200) + "...(" + body.length() + " chars)"; |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,112 @@ |
|||||||
|
package common.ecommerce.walmart.support; |
||||||
|
|
||||||
|
import common.ecommerce.channel.model.account.AccountKey; |
||||||
|
import common.ecommerce.channel.model.account.ChannelAccount; |
||||||
|
import common.ecommerce.channel.sdk.ChannelConnection; |
||||||
|
import common.ecommerce.channel.sdk.ChannelContext; |
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.shared.model.ChannelProvider; |
||||||
|
import common.ecommerce.shared.model.Platform; |
||||||
|
import common.ecommerce.shared.spi.ChannelSecret; |
||||||
|
import common.ecommerce.shared.spi.LockProvider; |
||||||
|
import common.ecommerce.shared.spi.TokenStore; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.walmart.WalmartConstants; |
||||||
|
import common.ecommerce.walmart.adapter.WalmartAdapter; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneOffset; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
/** |
||||||
|
* 沃尔玛测试的公共样板:固定时钟、固定账户、组装适配器。 |
||||||
|
* |
||||||
|
* <p>各契约测试只关心「请求怎么拼」和「响应怎么映射」, |
||||||
|
* token、缓存、错误映射的装配都在这里完成。</p> |
||||||
|
*/ |
||||||
|
public final class WalmartTestSupport { |
||||||
|
|
||||||
|
/** 认的 clientId / secret;测试里不出现真实凭据。 */ |
||||||
|
public static final String CLIENT_ID = "test-client-id"; |
||||||
|
|
||||||
|
public static final String CLIENT_SECRET = "test-client-secret"; |
||||||
|
|
||||||
|
/** 沙箱端点,与线上地址格式一致。 */ |
||||||
|
public static final String ENDPOINT = WalmartConstants.SANDBOX_BASE_URL; |
||||||
|
|
||||||
|
/** 固定时钟:2026-11-18T00:00:00Z,测试里的「现在」。 */ |
||||||
|
public static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-18T00:00:00Z"), ZoneOffset.UTC); |
||||||
|
|
||||||
|
public static final JacksonJsonCodec JSON = new JacksonJsonCodec(); |
||||||
|
|
||||||
|
private WalmartTestSupport() { |
||||||
|
} |
||||||
|
|
||||||
|
/** 沃尔玛直连账户。 */ |
||||||
|
public static ChannelAccount account() { |
||||||
|
return account("oms-wm-001"); |
||||||
|
} |
||||||
|
|
||||||
|
/** 指定 OMS 店铺 ID 的账户。 */ |
||||||
|
public static ChannelAccount account(String omsStoreId) { |
||||||
|
return ChannelAccount.builder() |
||||||
|
.key(AccountKey.of(ChannelProvider.DIRECT, Platform.WALMART_SC, omsStoreId)) |
||||||
|
.externalStoreId("wm-seller-01") |
||||||
|
.credentialRef("kms://test/walmart") |
||||||
|
.marketplaceZone("America/Chicago") |
||||||
|
.currency("USD") |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 连接:端点 + 凭据。 */ |
||||||
|
public static ChannelConnection connection() { |
||||||
|
return ChannelConnection.of(ENDPOINT, ChannelSecret.builder() |
||||||
|
.clientId(CLIENT_ID) |
||||||
|
.clientSecret(CLIENT_SECRET) |
||||||
|
.build()); |
||||||
|
} |
||||||
|
|
||||||
|
/** 一次调用的上下文。 */ |
||||||
|
public static ChannelContext context() { |
||||||
|
return ChannelContext.of(account(), connection(), "req-1", CLOCK); |
||||||
|
} |
||||||
|
|
||||||
|
/** 带指定账户与链路 ID 的上下文。 */ |
||||||
|
public static ChannelContext context(ChannelAccount account, String requestId) { |
||||||
|
return ChannelContext.of(account, connection(), requestId, CLOCK); |
||||||
|
} |
||||||
|
|
||||||
|
/** 装配一个使用内存令牌存储与锁的适配器。 */ |
||||||
|
public static WalmartAdapter adapter(RecordingTransport transport) { |
||||||
|
return adapter(transport, new InMemoryTokenStore(), new InMemoryLockProvider()); |
||||||
|
} |
||||||
|
|
||||||
|
public static WalmartAdapter adapter(RecordingTransport transport, TokenStore tokens, LockProvider locks) { |
||||||
|
return new WalmartAdapter(transport, JSON, tokens, locks, CLOCK); |
||||||
|
} |
||||||
|
|
||||||
|
/** 业务请求(排除令牌请求)。 */ |
||||||
|
public static List<HttpRequest> dataRequests(RecordingTransport transport) { |
||||||
|
return transport.dataRequests(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 最后一个请求的 URL。 */ |
||||||
|
public static String lastUrl(RecordingTransport transport) { |
||||||
|
List<HttpRequest> requests = transport.recorded(); |
||||||
|
if (requests.isEmpty()) { |
||||||
|
throw new IllegalStateException("no request recorded"); |
||||||
|
} |
||||||
|
return requests.get(requests.size() - 1).url(); |
||||||
|
} |
||||||
|
|
||||||
|
/** 断言 URL 含某段;失败时打印完整 URL 便于定位。 */ |
||||||
|
public static void assertUrlContains(String url, String expected) { |
||||||
|
if (url == null || !url.contains(expected)) { |
||||||
|
throw new AssertionError("expected url to contain <" + expected + "> but was <" + url + ">"); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,13 @@ |
|||||||
|
{ |
||||||
|
"error": [ |
||||||
|
{ |
||||||
|
"code": "CONTENT_NOT_FOUND.GMP_GATEWAY_API", |
||||||
|
"description": "No static resource v3/returns/103738048909818825.", |
||||||
|
"info": "Requested content could not be found.", |
||||||
|
"severity": "INFO", |
||||||
|
"category": "APPLICATION", |
||||||
|
"causes": [], |
||||||
|
"errorIdentifiers": {} |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
@ -0,0 +1,6 @@ |
|||||||
|
{ |
||||||
|
"timestamp": "2026-11-16T07:23:08Z", |
||||||
|
"status": 404, |
||||||
|
"error": "Request Not Found, Please correct the request!", |
||||||
|
"path": "/v3/orders/INVALID-PO-999/shipping" |
||||||
|
} |
||||||
@ -0,0 +1,49 @@ |
|||||||
|
{ |
||||||
|
"ItemResponse": [ |
||||||
|
{ |
||||||
|
"mart": "WALMART_US", |
||||||
|
"sku": "5212572", |
||||||
|
"wpid": "1YKTCEME6DEH", |
||||||
|
"upc": "888555387476", |
||||||
|
"gtin": "00888555387476", |
||||||
|
"productName": "Obermeyer Kid's Ultra Gear Bottom", |
||||||
|
"shelf": "[\"UNNAV\"]", |
||||||
|
"productType": "T-Shirts", |
||||||
|
"price": { "currency": "USD", "amount": 34.5 }, |
||||||
|
"publishedStatus": "UNPUBLISHED", |
||||||
|
"unpublishedReasons": { |
||||||
|
"reason": [ |
||||||
|
"No shipping information was set up.", |
||||||
|
"There is no primary image for your item." |
||||||
|
] |
||||||
|
}, |
||||||
|
"lifecycleStatus": "ACTIVE" |
||||||
|
}, |
||||||
|
{ |
||||||
|
"mart": "WALMART_US", |
||||||
|
"sku": "5212573", |
||||||
|
"wpid": "1YKTCEME6DEJ", |
||||||
|
"gtin": "00888555387483", |
||||||
|
"productName": "Published Item", |
||||||
|
"shelf": "[\"Home Page\",\"Clothing\"]", |
||||||
|
"productType": "Pants", |
||||||
|
"price": { "currency": "USD", "amount": 19.99 }, |
||||||
|
"publishedStatus": "PUBLISHED", |
||||||
|
"lifecycleStatus": "ACTIVE" |
||||||
|
}, |
||||||
|
{ |
||||||
|
"mart": "WALMART_US", |
||||||
|
"sku": "5212574", |
||||||
|
"wpid": "1YKTCEME6DEK", |
||||||
|
"upc": "888555387490", |
||||||
|
"productName": "Retired Item", |
||||||
|
"shelf": "[\"UNNAV\"]", |
||||||
|
"productType": "Pants", |
||||||
|
"price": { "currency": "USD", "amount": 9.5 }, |
||||||
|
"publishedStatus": "PUBLISHED", |
||||||
|
"lifecycleStatus": "RETIRED" |
||||||
|
} |
||||||
|
], |
||||||
|
"totalItems": 20, |
||||||
|
"nextCursor": "FGluY2x1ZGQ==" |
||||||
|
} |
||||||
@ -0,0 +1,56 @@ |
|||||||
|
{ |
||||||
|
"order": { |
||||||
|
"purchaseOrderId": "108816631915371", |
||||||
|
"customerOrderId": "100000159992851", |
||||||
|
"customerEmailId": "emailID123456@relay.walmart.com", |
||||||
|
"orderDate": 1686736267000, |
||||||
|
"shippingInfo": { |
||||||
|
"phone": "555-0100", |
||||||
|
"methodCode": "Value", |
||||||
|
"postalAddress": { |
||||||
|
"name": "Astro Test", |
||||||
|
"address1": "5809 W 44th Ave", |
||||||
|
"city": "Lakeside", |
||||||
|
"state": "CO", |
||||||
|
"postalCode": "80212", |
||||||
|
"country": "USA", |
||||||
|
"addressType": "OFFICE" |
||||||
|
} |
||||||
|
}, |
||||||
|
"orderLines": { |
||||||
|
"orderLine": [ |
||||||
|
{ |
||||||
|
"lineNumber": "1", |
||||||
|
"item": { |
||||||
|
"productName": "Delta Children Disney Mickey Mouse Upholstered Toddler Chair with Side Pockets", |
||||||
|
"sku": "67022229561Test5_skuUpdate" |
||||||
|
}, |
||||||
|
"charges": { |
||||||
|
"charge": [ |
||||||
|
{ |
||||||
|
"chargeType": "PRODUCT", |
||||||
|
"chargeName": "ItemPrice", |
||||||
|
"chargeAmount": { "currency": "USD", "amount": 499.99 }, |
||||||
|
"tax": { |
||||||
|
"taxName": "Tax1", |
||||||
|
"taxAmount": { "currency": "USD", "amount": 29.72 } |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"orderLineQuantity": { "unitOfMeasurement": "EACH", "amount": "1" }, |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Created", |
||||||
|
"statusQuantity": { "unitOfMeasurement": "EACH", "amount": "1" }, |
||||||
|
"trackingInfo": null |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"shipNode": { "type": "SellerFulfilled" } |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,330 @@ |
|||||||
|
{ |
||||||
|
"list": { |
||||||
|
"meta": { |
||||||
|
"totalCount": 12, |
||||||
|
"limit": 5, |
||||||
|
"nextCursor": null |
||||||
|
}, |
||||||
|
"elements": { |
||||||
|
"order": [ |
||||||
|
{ |
||||||
|
"purchaseOrderId": "108816631915371", |
||||||
|
"customerOrderId": "100000159992851", |
||||||
|
"customerEmailId": "emailID123456@relay.walmart.com", |
||||||
|
"orderDate": 1686736267000, |
||||||
|
"shippingInfo": { |
||||||
|
"phone": "555-0100", |
||||||
|
"estimatedShipDate": 1686822667000, |
||||||
|
"estimatedDeliveryDate": 1686995467000, |
||||||
|
"methodCode": "Value", |
||||||
|
"postalAddress": { |
||||||
|
"name": "Astro Test", |
||||||
|
"address1": "5809 W 44th Ave", |
||||||
|
"address2": null, |
||||||
|
"city": "Lakeside", |
||||||
|
"state": "CO", |
||||||
|
"postalCode": "80212", |
||||||
|
"country": "USA", |
||||||
|
"addressType": "OFFICE" |
||||||
|
} |
||||||
|
}, |
||||||
|
"orderLines": { |
||||||
|
"orderLine": [ |
||||||
|
{ |
||||||
|
"lineNumber": "1", |
||||||
|
"item": { |
||||||
|
"productName": "Delta Children Disney Mickey Mouse Upholstered Toddler Chair", |
||||||
|
"sku": "67022229561Test5_skuUpdate" |
||||||
|
}, |
||||||
|
"charges": { |
||||||
|
"charge": [ |
||||||
|
{ |
||||||
|
"chargeType": "PRODUCT", |
||||||
|
"chargeName": "ItemPrice", |
||||||
|
"chargeAmount": { |
||||||
|
"currency": "USD", |
||||||
|
"amount": 499.99 |
||||||
|
}, |
||||||
|
"tax": { |
||||||
|
"taxName": "Tax1", |
||||||
|
"taxAmount": { |
||||||
|
"currency": "USD", |
||||||
|
"amount": 29.72 |
||||||
|
} |
||||||
|
} |
||||||
|
}, |
||||||
|
{ |
||||||
|
"chargeType": "SHIPPING", |
||||||
|
"chargeName": "Shipping", |
||||||
|
"chargeAmount": { |
||||||
|
"currency": "USD", |
||||||
|
"amount": 0.0 |
||||||
|
}, |
||||||
|
"tax": { |
||||||
|
"taxName": "Tax1", |
||||||
|
"taxAmount": { |
||||||
|
"currency": "USD", |
||||||
|
"amount": 0.0 |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"orderLineQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "1" |
||||||
|
}, |
||||||
|
"statusDate": 1686736267000, |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Created", |
||||||
|
"statusQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "1" |
||||||
|
}, |
||||||
|
"trackingInfo": null |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"shipNode": { |
||||||
|
"type": "SellerFulfilled" |
||||||
|
} |
||||||
|
}, |
||||||
|
{ |
||||||
|
"purchaseOrderId": "108816631915372", |
||||||
|
"customerOrderId": "100000159992852", |
||||||
|
"orderDate": 1686736300000, |
||||||
|
"shippingInfo": { |
||||||
|
"methodCode": "Standard", |
||||||
|
"postalAddress": { |
||||||
|
"name": "Second Buyer", |
||||||
|
"address1": "1 Main St", |
||||||
|
"city": "Dallas", |
||||||
|
"state": "TX", |
||||||
|
"postalCode": "75201", |
||||||
|
"country": "USA", |
||||||
|
"addressType": "RESIDENTIAL" |
||||||
|
} |
||||||
|
}, |
||||||
|
"orderLines": { |
||||||
|
"orderLine": [ |
||||||
|
{ |
||||||
|
"lineNumber": "1", |
||||||
|
"item": { |
||||||
|
"productName": "Chair", |
||||||
|
"sku": "SKU-1" |
||||||
|
}, |
||||||
|
"orderLineQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "1" |
||||||
|
}, |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Shipped", |
||||||
|
"statusQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "1" |
||||||
|
}, |
||||||
|
"trackingInfo": { |
||||||
|
"shipDateTime": "2026-11-16T07:00:00.000Z", |
||||||
|
"carrierName": { |
||||||
|
"carrier": "UPS" |
||||||
|
}, |
||||||
|
"methodCode": "Standard", |
||||||
|
"trackingNumber": "1Z999AA10123456784" |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"shipNode": { |
||||||
|
"type": "SellerFulfilled" |
||||||
|
} |
||||||
|
}, |
||||||
|
{ |
||||||
|
"purchaseOrderId": "108816631915373", |
||||||
|
"customerOrderId": "C-108816631915373", |
||||||
|
"orderDate": 1686736400000, |
||||||
|
"shippingInfo": { |
||||||
|
"methodCode": "Value", |
||||||
|
"postalAddress": { |
||||||
|
"name": "History Buyer", |
||||||
|
"address1": "9 Elm St", |
||||||
|
"city": "Austin", |
||||||
|
"state": "TX", |
||||||
|
"postalCode": "73301", |
||||||
|
"country": "USA", |
||||||
|
"addressType": "RESIDENTIAL" |
||||||
|
} |
||||||
|
}, |
||||||
|
"orderLines": { |
||||||
|
"orderLine": [ |
||||||
|
{ |
||||||
|
"lineNumber": "1", |
||||||
|
"item": { |
||||||
|
"productName": "Partially Shipped Chair", |
||||||
|
"sku": "SKU-PARTIAL" |
||||||
|
}, |
||||||
|
"orderLineQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "3" |
||||||
|
}, |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Created", |
||||||
|
"statusQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "2" |
||||||
|
}, |
||||||
|
"trackingInfo": null |
||||||
|
}, |
||||||
|
{ |
||||||
|
"status": "Shipped", |
||||||
|
"statusQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "1" |
||||||
|
}, |
||||||
|
"trackingInfo": null |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"shipNode": { |
||||||
|
"type": "SellerFulfilled" |
||||||
|
} |
||||||
|
}, |
||||||
|
{ |
||||||
|
"purchaseOrderId": "108816631915374", |
||||||
|
"customerOrderId": "C-108816631915374", |
||||||
|
"orderDate": 1686736400000, |
||||||
|
"shippingInfo": { |
||||||
|
"methodCode": "Value", |
||||||
|
"postalAddress": { |
||||||
|
"name": "History Buyer", |
||||||
|
"address1": "9 Elm St", |
||||||
|
"city": "Austin", |
||||||
|
"state": "TX", |
||||||
|
"postalCode": "73301", |
||||||
|
"country": "USA", |
||||||
|
"addressType": "RESIDENTIAL" |
||||||
|
} |
||||||
|
}, |
||||||
|
"orderLines": { |
||||||
|
"orderLine": [ |
||||||
|
{ |
||||||
|
"lineNumber": "1", |
||||||
|
"item": { |
||||||
|
"productName": "Fully Shipped Chair", |
||||||
|
"sku": "SKU-FULL" |
||||||
|
}, |
||||||
|
"orderLineQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "3" |
||||||
|
}, |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Created", |
||||||
|
"statusQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "0" |
||||||
|
}, |
||||||
|
"trackingInfo": null |
||||||
|
}, |
||||||
|
{ |
||||||
|
"status": "Shipped", |
||||||
|
"statusQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "3" |
||||||
|
}, |
||||||
|
"trackingInfo": null |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"shipNode": { |
||||||
|
"type": "SellerFulfilled" |
||||||
|
} |
||||||
|
}, |
||||||
|
{ |
||||||
|
"purchaseOrderId": "108816631915375", |
||||||
|
"customerOrderId": "C-108816631915375", |
||||||
|
"orderDate": 1686736500000, |
||||||
|
"shippingInfo": { |
||||||
|
"methodCode": "Value", |
||||||
|
"postalAddress": { |
||||||
|
"name": "Multi Qty Buyer", |
||||||
|
"address1": "1 Two St", |
||||||
|
"city": "Denver", |
||||||
|
"state": "CO", |
||||||
|
"postalCode": "80202", |
||||||
|
"country": "USA", |
||||||
|
"addressType": "RESIDENTIAL" |
||||||
|
} |
||||||
|
}, |
||||||
|
"orderLines": { |
||||||
|
"orderLine": [ |
||||||
|
{ |
||||||
|
"lineNumber": "1", |
||||||
|
"item": { |
||||||
|
"productName": "Two Pack", |
||||||
|
"sku": "SKU-MULTI" |
||||||
|
}, |
||||||
|
"charges": { |
||||||
|
"charge": [ |
||||||
|
{ |
||||||
|
"chargeType": "PRODUCT", |
||||||
|
"chargeName": "ItemPrice", |
||||||
|
"chargeAmount": { |
||||||
|
"currency": "USD", |
||||||
|
"amount": 99.98 |
||||||
|
}, |
||||||
|
"tax": { |
||||||
|
"taxName": "Tax1", |
||||||
|
"taxAmount": { |
||||||
|
"currency": "USD", |
||||||
|
"amount": 5.94 |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"orderLineQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "2" |
||||||
|
}, |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Created", |
||||||
|
"statusQuantity": { |
||||||
|
"unitOfMeasurement": "EACH", |
||||||
|
"amount": "2" |
||||||
|
}, |
||||||
|
"trackingInfo": null |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
}, |
||||||
|
"shipNode": { |
||||||
|
"type": "SellerFulfilled" |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,59 @@ |
|||||||
|
{ |
||||||
|
"orderShipment": { |
||||||
|
"orderLines": { |
||||||
|
"orderLine": [ |
||||||
|
{ |
||||||
|
"lineNumber": "1", |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Created", |
||||||
|
"statusQuantity": { "unitOfMeasurement": "EACH", "amount": "1" }, |
||||||
|
"trackingInfo": null |
||||||
|
}, |
||||||
|
{ |
||||||
|
"status": "Shipped", |
||||||
|
"statusQuantity": { "unitOfMeasurement": "EACH", "amount": "1" }, |
||||||
|
"trackingInfo": { |
||||||
|
"shipDateTime": "2026-11-16T07:00:00.000Z", |
||||||
|
"carrierName": { "carrier": "UPS" }, |
||||||
|
"methodCode": "Standard", |
||||||
|
"trackingNumber": "1Z999AA10123456784" |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
}, |
||||||
|
{ |
||||||
|
"lineNumber": "2", |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Created", |
||||||
|
"statusQuantity": { "unitOfMeasurement": "EACH", "amount": "1" }, |
||||||
|
"trackingInfo": null |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
}, |
||||||
|
{ |
||||||
|
"lineNumber": "3", |
||||||
|
"orderLineStatuses": { |
||||||
|
"orderLineStatus": [ |
||||||
|
{ |
||||||
|
"status": "Shipped", |
||||||
|
"statusQuantity": { "unitOfMeasurement": "EACH", "amount": "1" }, |
||||||
|
"trackingInfo": { |
||||||
|
"shipDateTime": "2026-11-16T08:00:00.000Z", |
||||||
|
"carrierName": { "otherCarrier": "Local Courier" }, |
||||||
|
"methodCode": "Freight", |
||||||
|
"trackingNumber": "LC-0001" |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,52 @@ |
|||||||
|
{ |
||||||
|
"returnOrderId": "103738048909818825", |
||||||
|
"customerEmailId": "emailID123456@relay.walmart.com", |
||||||
|
"customerName": { "firstName": "Jane", "lastName": "Doe" }, |
||||||
|
"customerOrderId": "1234567891234", |
||||||
|
"refundMode": "POST_DELIVERY", |
||||||
|
"returnOrderDate": "2019-02-21T01:01:08.000Z", |
||||||
|
"returnType": "RETURN", |
||||||
|
"returnByDate": "2019-03-23T01:01:06.000Z", |
||||||
|
"totalRefundAmount": { "currencyAmount": 127.45, "currencyUnit": "USD" }, |
||||||
|
"returnChannel": { "channelName": "ONLINE" }, |
||||||
|
"returnLineGroups": [ |
||||||
|
{ |
||||||
|
"groupNo": 1, |
||||||
|
"returnLines": [ { "returnOrderLineNumber": 1 } ], |
||||||
|
"labels": [ |
||||||
|
{ |
||||||
|
"labelImageURL": "https://i5.walmartimages.com/asr/label.png", |
||||||
|
"carrierInfoList": [ |
||||||
|
{ |
||||||
|
"carrierId": "11", |
||||||
|
"carrierName": "FEDEX", |
||||||
|
"serviceType": "FedEx Ground", |
||||||
|
"trackingNo": "785611449666" |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
], |
||||||
|
"returnExpectedFlag": true |
||||||
|
} |
||||||
|
], |
||||||
|
"returnOrderLines": [ |
||||||
|
{ |
||||||
|
"returnOrderLineNumber": 1, |
||||||
|
"salesOrderLineNumber": 1, |
||||||
|
"returnReason": "DAMAGED", |
||||||
|
"purchaseOrderId": "4790210558890", |
||||||
|
"item": { |
||||||
|
"sku": "ANTL_GDL-0700", |
||||||
|
"productName": "Antlion Audio ModMic" |
||||||
|
}, |
||||||
|
"quantity": { "unitOfMeasure": "EACH", "measurementValue": 2 }, |
||||||
|
"unitPrice": { "currencyAmount": 119.95, "currencyUnit": "USD" }, |
||||||
|
"chargeTotals": [ { "name": "lineTotal", "value": 239.9 } ], |
||||||
|
"currentDeliveryStatus": "IN_TRANSIT", |
||||||
|
"currentRefundStatus": "REFUND_PROCESSED", |
||||||
|
"refundedQty": 2, |
||||||
|
"status": "IN_TRANSIT", |
||||||
|
"statusTime": "2019-03-05T00:00:00.000Z" |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
@ -0,0 +1,82 @@ |
|||||||
|
{ |
||||||
|
"meta": { "totalCount": 30, "limit": 10, "nextCursor": "?sellerId=151&limit=10&offset=10" }, |
||||||
|
"returnOrders": [ |
||||||
|
{ |
||||||
|
"returnOrderId": "103738048909818825", |
||||||
|
"customerEmailId": "emailID123456@relay.walmart.com", |
||||||
|
"customerName": { "firstName": "Jane", "lastName": "Doe" }, |
||||||
|
"customerOrderId": "1234567891234", |
||||||
|
"refundMode": "POST_DELIVERY", |
||||||
|
"returnOrderDate": "2019-02-21T01:01:08.000Z", |
||||||
|
"returnType": "REPLACEMENT", |
||||||
|
"replacementCustomerOrderId": "1234567891234", |
||||||
|
"returnByDate": "2019-03-23T01:01:06.000Z", |
||||||
|
"totalRefundAmount": { "currencyAmount": 127.45, "currencyUnit": "USD" }, |
||||||
|
"returnChannel": { "channelName": "IN_STORE" }, |
||||||
|
"returnLineGroups": [ |
||||||
|
{ |
||||||
|
"groupNo": 1, |
||||||
|
"returnLines": [ { "returnOrderLineNumber": 1 } ], |
||||||
|
"labels": [ |
||||||
|
{ |
||||||
|
"labelImageURL": "https://i5.walmartimages.com/asr/label.png", |
||||||
|
"carrierInfoList": [ |
||||||
|
{ |
||||||
|
"carrierId": "11", |
||||||
|
"carrierName": "FEDEX", |
||||||
|
"serviceType": "FedEx Ground", |
||||||
|
"trackingNo": "785611449666" |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
], |
||||||
|
"returnExpectedFlag": true |
||||||
|
} |
||||||
|
], |
||||||
|
"returnOrderLines": [ |
||||||
|
{ |
||||||
|
"returnOrderLineNumber": 1, |
||||||
|
"salesOrderLineNumber": 1, |
||||||
|
"returnReason": "ARRIVED_LATE", |
||||||
|
"purchaseOrderId": "4790210558890", |
||||||
|
"sellerOrderId": "123", |
||||||
|
"purchaseOrderLineNumber": 1, |
||||||
|
"item": { |
||||||
|
"sku": "ANTL_GDL-0700", |
||||||
|
"productName": "Antlion Audio ModMic", |
||||||
|
"itemWeight": { "unitOfMeasure": "POUND", "measurementValue": 0.5 } |
||||||
|
}, |
||||||
|
"quantity": { "unitOfMeasure": "EACH", "measurementValue": 3 }, |
||||||
|
"unitPrice": { "currencyAmount": 119.95, "currencyUnit": "USD" }, |
||||||
|
"chargeTotals": [ |
||||||
|
{ "name": "lineUnitPrice", "value": 119.95 }, |
||||||
|
{ "name": "lineTotal", "value": 359.85 } |
||||||
|
], |
||||||
|
"currentDeliveryStatus": "NOT_SHIPPED", |
||||||
|
"currentRefundStatus": "REFUND_INITIATED", |
||||||
|
"refundedQty": 1, |
||||||
|
"cancellableQty": 0, |
||||||
|
"rechargeableQty": 2, |
||||||
|
"status": "COMPLETED", |
||||||
|
"statusTime": "2019-03-02T05:45:45.000Z" |
||||||
|
}, |
||||||
|
{ |
||||||
|
"returnOrderLineNumber": 2, |
||||||
|
"salesOrderLineNumber": 2, |
||||||
|
"returnReason": "DAMAGED", |
||||||
|
"purchaseOrderId": "4790210558890", |
||||||
|
"item": { |
||||||
|
"sku": "ANTL_GDL-0701", |
||||||
|
"productName": "Antlion Audio ModMic USB" |
||||||
|
}, |
||||||
|
"quantity": { "unitOfMeasure": "EACH", "measurementValue": 1 }, |
||||||
|
"unitPrice": { "currencyAmount": 79.5, "currencyUnit": "USD" }, |
||||||
|
"currentDeliveryStatus": "SHIPPED", |
||||||
|
"currentRefundStatus": "NO_REFUND", |
||||||
|
"status": "IN_TRANSIT", |
||||||
|
"statusTime": "2019-03-01T00:00:00.000Z" |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
@ -0,0 +1,5 @@ |
|||||||
|
{ |
||||||
|
"access_token": "eyJraWQiOiI1ZTI5N2Q4Yi05MWZjLTRiNDctYTliMS02NmJhZmU0ZjE4Y2EiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ3YWxtYXJ0In0.c2lnbmF0dXJl", |
||||||
|
"token_type": "Bearer", |
||||||
|
"expires_in": 900 |
||||||
|
} |
||||||
Loading…
Reference in new issue