You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
908 lines
42 KiB
908 lines
42 KiB
package common.ecommerce.walmart.adapter; |
|
|
|
import common.ecommerce.channel.capability.AfterSaleCapable; |
|
import common.ecommerce.channel.capability.MarkShippedCapable; |
|
import common.ecommerce.channel.capability.RefundCapable; |
|
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.aftersale.RefundCommand; |
|
import common.ecommerce.channel.model.aftersale.RefundResult; |
|
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.model.fulfillment.ShipmentCommand; |
|
import common.ecommerce.channel.model.fulfillment.ShipmentResult; |
|
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.WalmartFeedDtos; |
|
import common.ecommerce.walmart.dto.WalmartRefundDtos; |
|
import common.ecommerce.walmart.dto.WalmartShipmentWriteDtos; |
|
import common.ecommerce.walmart.http.WalmartErrors; |
|
import common.ecommerce.walmart.http.WalmartRequestFactory; |
|
import common.ecommerce.walmart.model.WalmartFeedCommand; |
|
import common.ecommerce.walmart.model.WalmartFeedStatus; |
|
import common.ecommerce.walmart.mapper.WalmartOrderMapper; |
|
import common.ecommerce.walmart.mapper.WalmartProductMapper; |
|
import common.ecommerce.walmart.mapper.WalmartReturnMapper; |
|
import common.ecommerce.walmart.mapper.WalmartFeedMapper; |
|
import common.ecommerce.walmart.mapper.WalmartRefundMapper; |
|
import common.ecommerce.walmart.mapper.WalmartShipmentMapper; |
|
import common.ecommerce.walmart.mapper.WalmartShipmentWriteMapper; |
|
|
|
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, |
|
MarkShippedCapable, RefundCapable { |
|
|
|
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, |
|
Capability.MARK_SHIPPED, Capability.REFUND); |
|
} |
|
|
|
// ---------------------------------------------------------------- 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>时间窗映射:{@link AfterSaleQuery.DateType#AFTER_SALE_TIME} 用 |
|
* {@code returnCreationStartDate/EndDate}, |
|
* {@link AfterSaleQuery.DateType#UPDATE_TIME} 用 |
|
* {@code returnLastModifiedStartDate/EndDate}(官方两套参数都有)。 |
|
* {@code PURCHASE_TIME} 没有对应参数,显式报错,不做「拿别的字段顶替」的静默降级。</p> |
|
*/ |
|
@Override |
|
public Page<AfterSale> pull(ChannelContext ctx, AfterSaleQuery query) { |
|
ChannelAccount account = ctx.account(); |
|
if (query.dateType() == AfterSaleQuery.DateType.PURCHASE_TIME) { |
|
throw unsupportedFilter("walmart /v3/returns has no purchase-time filter; " |
|
+ "use AFTER_SALE_TIME or UPDATE_TIME"); |
|
} |
|
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(); |
|
// 官方参数名是 returnCreationStartDate/EndDate 与 returnLastModifiedStartDate/EndDate |
|
// (不是 createdStartDate);传错名字平台会忽略过滤条件、返回全量数据 |
|
String from = WALMART_TIME_FORMAT.format( |
|
query.startDate().atStartOfDay(ZoneId.of("UTC")).toInstant()); |
|
String to = WALMART_TIME_FORMAT.format( |
|
query.endDate().atStartOfDay(ZoneId.of("UTC")).toInstant()); |
|
if (query.dateType() == AfterSaleQuery.DateType.UPDATE_TIME) { |
|
queryParams.put("returnLastModifiedStartDate", from); |
|
queryParams.put("returnLastModifiedEndDate", to); |
|
} else { |
|
queryParams.put("returnCreationStartDate", from); |
|
queryParams.put("returnCreationEndDate", to); |
|
} |
|
queryParams.put("limit", query.pageSize() <= 0 |
|
? WalmartConstants.DEFAULT_RETURN_PAGE_SIZE |
|
: Math.min(query.pageSize(), WalmartConstants.MAX_RETURN_PAGE_SIZE)); |
|
// 官方退货接口没有 offset 参数,翻页只靠 meta.nextCursor |
|
|
|
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>沃尔玛没有 {@code GET /v3/returns/{returnOrderId}}</b>——官方 Returns |
|
* spec 里只有列表与退款两条。这里改用官方列表接口按 {@code returnOrderId} 过滤, |
|
* 对外行为与「查详情」一致:返回该退货单展开出的所有售后行。</p> |
|
* |
|
* <p>与列表一样<b>按商品行展开</b>:一个退货单可能含多个退货行, |
|
* 返回的 {@link AfterSale#afterSaleId()} 与列表里的完全一致({@code returnOrderId:行号}), |
|
* 可以直接拿去 upsert。</p> |
|
* |
|
* <p>平台不保证过滤参数生效(沙箱 mock 就不生效),所以本地会再按单号筛一次, |
|
* 不会把别的退货单混进来。</p> |
|
* |
|
* @param returnOrderId 退货单号 |
|
* @return 该退货单展开出的售后行;退货单没有行时返回空列表 |
|
* @throws ChannelException 平台 404 / 其它错误,由 {@link WalmartErrors} 分类 |
|
*/ |
|
public List<AfterSale> getReturn(ChannelContext ctx, String returnOrderId) { |
|
if (isBlank(returnOrderId)) { |
|
throw unsupportedFilter("walmart return detail requires returnOrderId"); |
|
} |
|
ChannelAccount account = ctx.account(); |
|
Map<String, Object> queryParams = WalmartRequestFactory.query(); |
|
// 官方没有 GET /v3/returns/{id},只能走列表接口的 returnOrderId 过滤 |
|
queryParams.put("returnOrderId", returnOrderId.trim()); |
|
queryParams.put("limit", 1); |
|
|
|
HttpResponse response = execute(ctx, "afterSales.get", new GetPlan() { |
|
@Override |
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
|
return requestFactory.get(c.endpointBaseUrl(), WalmartConstants.PATH_RETURNS, |
|
queryParams, t, c, "afterSales.get"); |
|
} |
|
}); |
|
|
|
WalmartReturnDtos.ReturnListResponse dto = |
|
json.fromJson(response.body(), WalmartReturnDtos.ReturnListResponse.class); |
|
if (dto == null || dto.returnOrders == null) { |
|
return java.util.Collections.emptyList(); |
|
} |
|
List<AfterSale> out = new ArrayList<AfterSale>(); |
|
for (WalmartReturnDtos.ReturnOrder order : dto.returnOrders) { |
|
// 平台不保证过滤参数生效(沙箱 mock 就不生效),本地再筛一次 |
|
if (order != null && returnOrderId.trim().equals(order.returnOrderId)) { |
|
out.addAll(WalmartReturnMapper.toAfterSales(order, account.omsStoreId(), zoneOf(ctx))); |
|
} |
|
} |
|
return out; |
|
} |
|
|
|
// ---------------------------------------------------------------- MarkShippedCapable |
|
|
|
/** |
|
* 标发:{@code POST /v3/orders/{purchaseOrderId}/shipping}。 |
|
* |
|
* <p>沃尔玛<b>没有批量标发接口</b>,一次一个订单。支持部分发货:同一行可以 |
|
* 多次调用,{@code statusQuantity.amount} 累计;剩余数量标完后行状态才变 |
|
* {@code Shipped}。</p> |
|
* |
|
* <p>幂等由调用方经 {@code sdk.writes()} 保证,推荐业务键 |
|
* {@link ShipmentCommand#businessRef()}:订单号 + 行号 + 数量。</p> |
|
* |
|
* <p>⚠ 沙箱实测该路由 404(mock 未实现),只能在生产环境验证。</p> |
|
* |
|
* @throws common.ecommerce.shared.error.ValidationException 命令不完整 |
|
* @throws common.ecommerce.shared.error.PlatformBusinessException 平台拒绝(如订单已取消) |
|
*/ |
|
@Override |
|
public ShipmentResult markShipped(ChannelContext ctx, ShipmentCommand command) { |
|
if (command == null) { |
|
throw new ValidationException(ChannelException.builder() |
|
.message("walmart markShipped requires a shipment command") |
|
.operation("salesOrders.markShipped") |
|
.provider(provider().name()) |
|
.platform(Platform.WALMART_SC) |
|
.retryable(false)); |
|
} |
|
String path = WalmartConstants.PATH_ORDER_BY_ID |
|
+ WalmartRequestFactory.pathSegment(command.channelOrderId()) |
|
+ WalmartConstants.PATH_ORDER_SHIPPING; |
|
|
|
WalmartShipmentWriteDtos.ShipmentRequest body = |
|
WalmartShipmentWriteMapper.toRequest(command, ctx.clock()); |
|
|
|
HttpResponse response = execute(ctx, "salesOrders.markShipped", new GetPlan() { |
|
@Override |
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
|
return requestFactory.write("POST", c.endpointBaseUrl(), path, null, body, json, t, c, |
|
"salesOrders.markShipped"); |
|
} |
|
}); |
|
|
|
// 沃尔玛标发成功回更新后的订单;也见过只回受理结果的情况,两种都兼容 |
|
WalmartOrderDtos.OrderDetailResponse dto = |
|
parseQuietly(response.body(), WalmartOrderDtos.OrderDetailResponse.class); |
|
return WalmartShipmentWriteMapper.toResult(dto == null ? null : dto.order, command); |
|
} |
|
|
|
// ---------------------------------------------------------------- RefundCapable |
|
|
|
/** |
|
* 发起退款:{@code POST /v3/returns/{returnOrderId}/refund}。 |
|
* |
|
* <p>沃尔玛退款细到<b>退货行 × 费用项</b>:每个退货行可只退部分费用 |
|
* (商品价 / 运费 / 税)。命令里给什么就退什么,适配器不补全。</p> |
|
* |
|
* <p>业务规则(文档 §5.3):部分售后由平台自动退款,只有 |
|
* {@code currentRefundStatus} 需要卖家处理时才需调用;调用前应查详情核对 |
|
* {@code refundedQty} / {@code cancellableQty},避免超退。</p> |
|
* |
|
* <p>幂等由调用方经 {@code sdk.writes()} 保证。</p> |
|
* |
|
* <p>⚠ 沙箱实测该路由 404(mock 未实现),只能在生产环境验证。</p> |
|
* |
|
* @throws ValidationException 退货行号不是整数(沃尔玛要求 integer) |
|
* @throws common.ecommerce.shared.error.PlatformBusinessException 平台拒绝(已退过 / 超退) |
|
*/ |
|
@Override |
|
public RefundResult refund(ChannelContext ctx, RefundCommand command) { |
|
if (command == null) { |
|
throw new ValidationException(ChannelException.builder() |
|
.message("walmart refund requires a refund command") |
|
.operation("afterSales.refund") |
|
.provider(provider().name()) |
|
.platform(Platform.WALMART_SC) |
|
.retryable(false)); |
|
} |
|
final WalmartRefundDtos.RefundRequest body; |
|
try { |
|
body = WalmartRefundMapper.toRequest(command, command.afterSaleId()); |
|
} catch (IllegalArgumentException e) { |
|
throw new ValidationException(ChannelException.builder() |
|
.message(e.getMessage()) |
|
.operation("afterSales.refund") |
|
.provider(provider().name()) |
|
.platform(Platform.WALMART_SC) |
|
.retryable(false)); |
|
} |
|
|
|
String path = WalmartConstants.PATH_RETURN_BY_ID |
|
+ WalmartRequestFactory.pathSegment(command.afterSaleId()) |
|
+ WalmartConstants.PATH_RETURN_REFUND; |
|
|
|
HttpResponse response = execute(ctx, "afterSales.refund", new GetPlan() { |
|
@Override |
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
|
return requestFactory.write("POST", c.endpointBaseUrl(), path, null, body, json, t, c, |
|
"afterSales.refund"); |
|
} |
|
}); |
|
|
|
// 响应结构未实测:能解成退货单就取行级状态,否则只保留单号 |
|
WalmartReturnDtos.ReturnOrder applied = parseReturnOrderQuietly(response.body()); |
|
return WalmartRefundMapper.toResult(applied, command); |
|
} |
|
|
|
/** |
|
* 尽力解析响应体:空体、非 JSON、结构不符都返回 null,不抛。 |
|
* |
|
* <p>用于「平台可能只回受理结果」的写接口——把解析失败当成异常抛出, |
|
* 会让一次成功的写操作变成失败(幂等层会记 FAILED,重试可能重复执行)。</p> |
|
*/ |
|
private <T> T parseQuietly(String body, Class<T> type) { |
|
if (body == null || body.trim().isEmpty()) { |
|
return null; |
|
} |
|
try { |
|
return json.fromJson(body, type); |
|
} catch (RuntimeException e) { |
|
return null; |
|
} |
|
} |
|
|
|
/** 退款响应尽力解析成退货单;解不出来返回 null,不抛。 */ |
|
private WalmartReturnDtos.ReturnOrder parseReturnOrderQuietly(String body) { |
|
if (body == null || body.trim().isEmpty()) { |
|
return null; |
|
} |
|
try { |
|
return json.fromJson(body, WalmartReturnDtos.ReturnOrder.class); |
|
} catch (RuntimeException e) { |
|
return null; |
|
} |
|
} |
|
|
|
// ---------------------------------------------------------------- Feed(非能力接口) |
|
|
|
/** |
|
* 提交商品 Feed:{@code POST /v3/feeds?feedType=MP_ITEM}。 |
|
* |
|
* <p>沃尔玛的商品写入是<b>异步批量</b>:提交只回一个 {@code feedId}, |
|
* 真正的成败要用 {@link #getFeedStatus} 轮询。成功响应是 <b>HTTP 200</b> |
|
* 且 body 带 {@code feedId}(官方 schema 只声明了 200,没有 202)。</p> |
|
* |
|
* <p>商品报文字段原样透传({@code MPItem[]} 每个元素的结构由调用方按 |
|
* Walmart《Item Spec》给),本适配器只补报文头。</p> |
|
* |
|
* <p>⚠ 沙箱实测返回 520(mock 未实现),只能在生产环境验证。</p> |
|
* |
|
* @param command Feed 命令 |
|
* @return 批次 ID |
|
* @throws common.ecommerce.shared.error.TransientException 平台 5xx(可重试) |
|
*/ |
|
public String submitFeed(ChannelContext ctx, WalmartFeedCommand command) { |
|
if (command == null) { |
|
throw unsupportedFilter("walmart feed submit requires a command"); |
|
} |
|
if (!WalmartFeedDtos.isSupportedFeedType(command.feedType())) { |
|
throw unsupportedFilter("walmart feedType is not supported: " + command.feedType() |
|
+ "; valid values: " + WalmartFeedDtos.FEED_TYPES); |
|
} |
|
Map<String, Object> queryParams = WalmartRequestFactory.query(); |
|
queryParams.put("feedType", command.feedType()); |
|
WalmartFeedDtos.FeedRequest body = WalmartFeedMapper.toRequest(command); |
|
|
|
HttpResponse response = execute(ctx, "feeds.submit", new GetPlan() { |
|
@Override |
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
|
return requestFactory.write("POST", c.endpointBaseUrl(), WalmartConstants.PATH_FEEDS, |
|
queryParams, body, json, t, c, "feeds.submit"); |
|
} |
|
}); |
|
|
|
WalmartFeedDtos.FeedSubmitResponse dto = |
|
json.fromJson(response.body(), WalmartFeedDtos.FeedSubmitResponse.class); |
|
if (dto == null || isBlank(dto.feedId)) { |
|
throw new ValidationException(ChannelException.builder() |
|
.message("walmart feed submit returned no feedId") |
|
.operation("feeds.submit") |
|
.provider(provider().name()) |
|
.omsStoreId(ctx.omsStoreId()) |
|
.platform(ctx.platform()) |
|
.requestId(ctx.requestId()) |
|
.rawResponse(response.body()) |
|
.retryable(false)); |
|
} |
|
return dto.feedId; |
|
} |
|
|
|
/** |
|
* 查询 Feed 处理状态:{@code GET /v3/feeds/{feedId}}。 |
|
* |
|
* <p>典型轮询:{@code RECEIVED} → {@code INPROGRESS} → {@code PROCESSED} / {@code ERROR}。 |
|
* {@code PROCESSED} 也可能有部分失败,看 {@code itemsFailed()} 与 |
|
* {@code items()} 里的逐条 {@code DATA_ERROR}。</p> |
|
* |
|
* @param feedId submitFeed 返回的批次 ID |
|
* @param includeDetails 是否要逐商品明细 |
|
* @return 处理状态 |
|
*/ |
|
public WalmartFeedStatus getFeedStatus(ChannelContext ctx, String feedId, boolean includeDetails) { |
|
if (isBlank(feedId)) { |
|
throw unsupportedFilter("walmart feed status requires feedId"); |
|
} |
|
String path = WalmartConstants.PATH_FEEDS |
|
+ "/" + WalmartRequestFactory.pathSegment(feedId.trim()); |
|
Map<String, Object> queryParams = WalmartRequestFactory.query(); |
|
if (includeDetails) { |
|
queryParams.put("includeDetails", true); |
|
} |
|
|
|
HttpResponse response = execute(ctx, "feeds.status", new GetPlan() { |
|
@Override |
|
public HttpRequest request(ChannelContext c, AccessToken t) { |
|
return requestFactory.get(c.endpointBaseUrl(), path, queryParams, t, c, "feeds.status"); |
|
} |
|
}); |
|
|
|
WalmartFeedDtos.FeedStatusResponse dto = |
|
json.fromJson(response.body(), WalmartFeedDtos.FeedStatusResponse.class); |
|
return WalmartFeedMapper.toStatus(dto); |
|
} |
|
|
|
// ---------------------------------------------------------------- 发货信息(非能力接口) |
|
|
|
/** |
|
* 查询发货信息:{@code GET /v3/orders/{purchaseOrderId}/shipping}。 |
|
* |
|
* <p><b>沃尔玛没有 {@code GET /v3/orders/{id}/shipping}</b>——官方 Orders spec 里 |
|
* 该路径只有 POST(标发)。所以这里改读订单详情 |
|
* {@code GET /v3/orders/{purchaseOrderId}},从 |
|
* {@code orderLines[].orderLineStatuses[].trackingInfo} 抽行级发货记录; |
|
* 数据与「发货信息」完全一致。</p> |
|
* |
|
* <p>返回行级记录(行号 / 承运商 / 运输方式 / 跟踪号 / 发货时间), |
|
* 只包含有 {@code trackingInfo} 的行。</p> |
|
* |
|
* @param purchaseOrderId 沃尔玛订单号 |
|
* @return 已发货行的记录;未发货时返回空列表 |
|
*/ |
|
public List<WalmartShipmentMapper.ShipmentLine> getShipping(ChannelContext ctx, |
|
String purchaseOrderId) { |
|
if (isBlank(purchaseOrderId)) { |
|
throw unsupportedFilter("walmart shipping query requires purchaseOrderId"); |
|
} |
|
String path = WalmartConstants.PATH_ORDER_BY_ID |
|
+ WalmartRequestFactory.pathSegment(purchaseOrderId.trim()); |
|
|
|
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"); |
|
} |
|
}); |
|
|
|
WalmartOrderDtos.OrderDetailResponse dto = |
|
json.fromJson(response.body(), WalmartOrderDtos.OrderDetailResponse.class); |
|
return WalmartShipmentMapper.fromOrder(dto == null ? null : dto.order); |
|
} |
|
|
|
// ---------------------------------------------------------------- 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)); |
|
} |
|
}
|
|
|