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.
734 lines
33 KiB
734 lines
33 KiB
|
5 days ago
|
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.WalmartRefundDtos;
|
||
|
|
import common.ecommerce.walmart.dto.WalmartShipmentWriteDtos;
|
||
|
|
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.WalmartRefundMapper;
|
||
|
|
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>实现五个能力接口,覆盖本期对接的 7 条路由:</p>
|
||
|
|
* <ul>
|
||
|
|
* <li>{@link SalesOrderCapable}:{@code GET /v3/orders}、{@code GET /v3/orders/{id}}</li>
|
||
|
|
* <li>{@link ProductCapable}:{@code GET /v3/items}(单品查询未接,见 {@link #get})</li>
|
||
|
|
* <li>{@link AfterSaleCapable}:{@code GET /v3/returns}</li>
|
||
|
|
* <li>{@link MarkShippedCapable}:{@code POST /v3/orders/{id}/shipping}</li>
|
||
|
|
* <li>{@link RefundCapable}:{@code POST /v3/returns/{id}/refund}</li>
|
||
|
|
* </ul>
|
||
|
|
*
|
||
|
|
* <p>退货单详情 {@code GET /v3/returns/{id}} 不在能力接口里,
|
||
|
|
* 由 {@link #getReturn} 提供——门面调用不到,需要先取得本适配器实例。</p>
|
||
|
|
*
|
||
|
|
* <h2>增量语义</h2>
|
||
|
|
* <p>沃尔玛订单接口只有<b>创建时间</b>过滤({@code createdStartDate/createdEndDate}),
|
||
|
|
* 没有更新时间。因此 {@link SalesOrderQuery#updatedAfter()} 被解释为创建时间窗,
|
||
|
|
* {@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;
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------- 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);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 本期只接商品列表,不接单品查询({@code GET /v3/items/{sku}})。
|
||
|
|
*
|
||
|
|
* <p>方法是 {@link ProductCapable} 的必需实现,这里显式报错而不是发请求——
|
||
|
|
* 静默返回 null 会让调用方以为「商品不存在」,与「没接这个接口」是两回事。</p>
|
||
|
|
*
|
||
|
|
* @throws ValidationException 恒抛,提示改用 {@link #pull}
|
||
|
|
*/
|
||
|
|
@Override
|
||
|
|
public ProductListing get(ChannelContext ctx, ProductRef ref) {
|
||
|
|
throw unsupportedFilter("walmart item detail is not integrated; "
|
||
|
|
+ "use products.pull to sync the catalog");
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------- 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>官方文档《Returns Management API overview》明确列出该路由,并把它作为
|
||
|
|
* approve/reject、refund、shippinglabel 的前置查询;reference 目录没有单列
|
||
|
|
* 响应 schema,所以解析时兼容单条包装、列表包装和顶层裸对象三种形状。</p>
|
||
|
|
*
|
||
|
|
* <p>与列表一样<b>按商品行展开</b>:一个退货单可能含多个退货行,
|
||
|
|
* 返回的 {@link AfterSale#afterSaleId()} 与列表里的完全一致({@code returnOrderId:行号}),
|
||
|
|
* 可以直接拿去 upsert。解析后仍按单号核对一次,避免混入别的退货单。</p>
|
||
|
|
*
|
||
|
|
* <p>⚠ 沙箱 mock 未实现该路由(404),只能在生产环境验证。</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");
|
||
|
|
}
|
||
|
|
final String id = returnOrderId.trim();
|
||
|
|
ChannelAccount account = ctx.account();
|
||
|
|
String path = WalmartConstants.PATH_RETURN_BY_ID
|
||
|
|
+ WalmartRequestFactory.pathSegment(id);
|
||
|
|
|
||
|
|
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");
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
List<AfterSale> out = new ArrayList<AfterSale>();
|
||
|
|
for (WalmartReturnDtos.ReturnOrder order : parseReturnDetail(response.body())) {
|
||
|
|
if (order == null || !id.equals(order.returnOrderId)) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
out.addAll(WalmartReturnMapper.toAfterSales(order, account.omsStoreId(), zoneOf(ctx)));
|
||
|
|
}
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 兼容详情接口的三种响应形状;解不出来返回空列表,不抛。 */
|
||
|
|
private List<WalmartReturnDtos.ReturnOrder> parseReturnDetail(String body) {
|
||
|
|
List<WalmartReturnDtos.ReturnOrder> candidates =
|
||
|
|
new ArrayList<WalmartReturnDtos.ReturnOrder>();
|
||
|
|
WalmartReturnDtos.ReturnDetailResponse detail =
|
||
|
|
parseQuietly(body, WalmartReturnDtos.ReturnDetailResponse.class);
|
||
|
|
if (detail != null) {
|
||
|
|
if (detail.returnOrder != null) {
|
||
|
|
candidates.add(detail.returnOrder);
|
||
|
|
}
|
||
|
|
if (detail.returnOrders != null) {
|
||
|
|
candidates.addAll(detail.returnOrders);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (candidates.isEmpty()) {
|
||
|
|
WalmartReturnDtos.ReturnOrder direct =
|
||
|
|
parseQuietly(body, WalmartReturnDtos.ReturnOrder.class);
|
||
|
|
if (direct != null && !isBlank(direct.returnOrderId)) {
|
||
|
|
candidates.add(direct);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return candidates;
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------- 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;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------- 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));
|
||
|
|
}
|
||
|
|
}
|