From 6214462ba92774c07f44cb24c9f532f6c76cb694 Mon Sep 17 00:00:00 2001 From: chenchuchuan <13554600537@163.com> Date: Wed, 4 Nov 2026 16:48:36 +0800 Subject: [PATCH] =?UTF-8?q?feat(lingxing):=20=E6=8E=A5=E5=85=A5=E5=94=AE?= =?UTF-8?q?=E5=90=8E=E8=AE=A2=E5=8D=95=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core: - 新增 model/aftersale:AfterSaleType(REFUND/RETURN/EXCHANGE/UNKNOWN)、 AfterSaleQuery(时间窗必填、dateType、类型与订单号过滤)、AfterSale(按商品行展开) - 新增 AfterSaleCapable + AfterSales 视图,ChannelSdk.afterSales(key, conn) lingxing: - LingxingApi.AFTER_SALE_LIST /erp/sc/routing/amzod/order/afterSaleList(POST, qps 1) - platform/aftersale:DTO(订单级 + item_list 行级 + 金额明细)、Mapper、ListSource - AmazonScSubPlatform 装配 afterSaleSource;适配器声明 RETURNS 能力 映射要点: - 领星按订单聚合,统一模型按 item_list 商品行展开 - 分页游标按「领星记录数」推进,不用展开后的条目数 - 行级 after_time / data_update_time 优先于订单级 - 唯一标识优先 md5_v2 → item_identifier → 订单号+msku+时间+row_index - 金额只保留数字与符号位;币种按符号映射,映射不出则金额为 null - 兼容文档笔误:示例里的 total_refund_amount__number(双下划线) 测试:Mapper 10 例 + 请求构造 1 例,夹具用官方文档示例。 Co-Authored-By: Claude --- .../ecommerce/capability/AfterSaleCapable.java | 20 ++ .../common/ecommerce/capability/AfterSales.java | 36 +++ .../ecommerce/model/aftersale/AfterSale.java | 242 +++++++++++++++++++ .../ecommerce/model/aftersale/AfterSaleQuery.java | 147 ++++++++++++ .../ecommerce/model/aftersale/AfterSaleType.java | 19 ++ .../main/java/common/ecommerce/sdk/ChannelSdk.java | 12 + .../common/ecommerce/lingxing/LingxingApi.java | 3 + .../lingxing/adapter/LingxingAdapter.java | 20 +- .../lingxing/platform/LingxingAfterSaleSource.java | 17 ++ .../lingxing/platform/LingxingSubPlatform.java | 5 + .../aftersale/LingxingAfterSaleListSource.java | 145 +++++++++++ .../aftersale/LingxingAfterSaleMapper.java | 267 +++++++++++++++++++++ .../platform/aftersale/dto/AfterSaleDto.java | 129 ++++++++++ .../platform/aftersale/dto/AfterSaleItemDto.java | 153 ++++++++++++ .../platform/aftersale/dto/AmountDetailDto.java | 21 ++ .../platform/amazon/sc/AmazonScSubPlatform.java | 9 + .../ecommerce/lingxing/SdkCallGuideTest.java | 3 +- .../aftersale/LingxingAfterSaleListSourceTest.java | 134 +++++++++++ .../aftersale/LingxingAfterSaleMapperTest.java | 146 +++++++++++ .../lingxing/probe/SearchFieldProbeTest.java | 254 ++++++++++++++++++++ .../lingxing/probe/ShopListProbeTest.java | 221 +++++++++++++++++ .../fixtures/lingxing/afterSale/success.json | 89 +++++++ 22 files changed, 2088 insertions(+), 4 deletions(-) create mode 100644 core/src/main/java/common/ecommerce/capability/AfterSaleCapable.java create mode 100644 core/src/main/java/common/ecommerce/capability/AfterSales.java create mode 100644 core/src/main/java/common/ecommerce/model/aftersale/AfterSale.java create mode 100644 core/src/main/java/common/ecommerce/model/aftersale/AfterSaleQuery.java create mode 100644 core/src/main/java/common/ecommerce/model/aftersale/AfterSaleType.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingAfterSaleSource.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSource.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapper.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleDto.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleItemDto.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AmountDetailDto.java create mode 100644 lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSourceTest.java create mode 100644 lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapperTest.java create mode 100644 lingxing/src/test/java/common/ecommerce/lingxing/probe/SearchFieldProbeTest.java create mode 100644 lingxing/src/test/java/common/ecommerce/lingxing/probe/ShopListProbeTest.java create mode 100644 lingxing/src/test/resources/fixtures/lingxing/afterSale/success.json diff --git a/core/src/main/java/common/ecommerce/capability/AfterSaleCapable.java b/core/src/main/java/common/ecommerce/capability/AfterSaleCapable.java new file mode 100644 index 0000000..a79c9d7 --- /dev/null +++ b/core/src/main/java/common/ecommerce/capability/AfterSaleCapable.java @@ -0,0 +1,20 @@ +package common.ecommerce.capability; + +import common.ecommerce.error.ChannelException; +import common.ecommerce.model.Capability; +import common.ecommerce.model.account.ChannelAccount; +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleQuery; +import common.ecommerce.model.support.Page; +import common.ecommerce.sdk.ChannelContext; + +/** + * 售后能力:拉取售后订单(退款 / 退货 / 换货)。 + * + *

只读。写操作(审批、退款)属于另一组能力,后续单独定义。

+ */ +public interface AfterSaleCapable extends PlatformAdapter { + + /** 分页拉取售后订单;统一模型按商品行展开。 */ + Page pull(ChannelContext ctx, AfterSaleQuery query); +} diff --git a/core/src/main/java/common/ecommerce/capability/AfterSales.java b/core/src/main/java/common/ecommerce/capability/AfterSales.java new file mode 100644 index 0000000..f932feb --- /dev/null +++ b/core/src/main/java/common/ecommerce/capability/AfterSales.java @@ -0,0 +1,36 @@ +package common.ecommerce.capability; + +import common.ecommerce.error.ChannelException; +import common.ecommerce.model.Capability; +import common.ecommerce.model.account.ChannelAccount; +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleQuery; +import common.ecommerce.model.support.Page; +import common.ecommerce.sdk.ChannelContext; + +/** + * 门面持有的售后视图。调用前做能力检查,缺失时显式拒绝。 + */ +public final class AfterSales { + + private final PlatformAdapter adapter; + private final ChannelAccount account; + private final ChannelContext ctx; + + public AfterSales(PlatformAdapter adapter, ChannelAccount account, ChannelContext ctx) { + this.adapter = adapter; + this.account = account; + this.ctx = ctx; + } + + public Page pull(AfterSaleQuery query) { + requireAfterSaleCapable(); + return ((AfterSaleCapable) adapter).pull(ctx, query); + } + + private void requireAfterSaleCapable() { + if (!adapter.supports(account, Capability.RETURNS) || !(adapter instanceof AfterSaleCapable)) { + throw new ChannelException.UnsupportedCapabilityException(Capability.RETURNS); + } + } +} diff --git a/core/src/main/java/common/ecommerce/model/aftersale/AfterSale.java b/core/src/main/java/common/ecommerce/model/aftersale/AfterSale.java new file mode 100644 index 0000000..9af1379 --- /dev/null +++ b/core/src/main/java/common/ecommerce/model/aftersale/AfterSale.java @@ -0,0 +1,242 @@ +package common.ecommerce.model.aftersale; + +import common.ecommerce.model.ChannelProvider; +import common.ecommerce.model.Platform; +import common.ecommerce.model.support.Money; +import common.ecommerce.model.support.PlatformTime; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * 统一售后单(一行 = 一个售后商品行)。 + * + *

平台侧的「售后单」往往是按订单聚合、按商品行拆分的(领星一份数据里带 + * {@code item_list})。统一模型按商品行展开:一行对应一个 + * {@link AfterSaleItem},避免下游再拆。

+ * + *

唯一标识 {@link #afterSaleId()} 参与 upsert;必须是稳定的平台侧标识。

+ */ +public final class AfterSale { + + private final Platform platform; + private final String omsStoreId; + private final String afterSaleId; + private final String channelOrderId; + private final AfterSaleType type; + private final String rawType; + private final String status; + private final String reason; + private final int quantity; + private final String platformSku; + private final String localSku; + private final String asin; + private final Money refundAmount; + private final Money refundCost; + private final PlatformTime afterSaleTime; + private final PlatformTime updatedAt; + private final String rmaNumber; + private final String carrier; + private final String trackingNumber; + private final String exchangeOrderId; + private final String buyerNote; + private final Map attributes; + private final ChannelProvider sourceProvider; + + private AfterSale(Builder b) { + this.platform = Objects.requireNonNull(b.platform, "platform"); + this.omsStoreId = Objects.requireNonNull(b.omsStoreId, "omsStoreId"); + this.afterSaleId = Objects.requireNonNull(b.afterSaleId, "afterSaleId"); + this.channelOrderId = b.channelOrderId; + this.type = b.type == null ? AfterSaleType.UNKNOWN : b.type; + this.rawType = b.rawType; + this.status = b.status; + this.reason = b.reason; + this.quantity = b.quantity; + this.platformSku = b.platformSku; + this.localSku = b.localSku; + this.asin = b.asin; + this.refundAmount = b.refundAmount; + this.refundCost = b.refundCost; + this.afterSaleTime = b.afterSaleTime; + this.updatedAt = b.updatedAt; + this.rmaNumber = b.rmaNumber; + this.carrier = b.carrier; + this.trackingNumber = b.trackingNumber; + this.exchangeOrderId = b.exchangeOrderId; + this.buyerNote = b.buyerNote; + this.attributes = Collections.unmodifiableMap(new LinkedHashMap(b.attributes)); + this.sourceProvider = Objects.requireNonNull(b.sourceProvider, "sourceProvider"); + } + + public static Builder builder() { + return new Builder(); + } + + public Platform platform() { + return platform; + } + + public String omsStoreId() { + return omsStoreId; + } + + /** 售后行唯一标识,参与 upsert。 */ + public String afterSaleId() { + return afterSaleId; + } + + /** 原始订单的平台单号。 */ + public String channelOrderId() { + return channelOrderId; + } + + public AfterSaleType type() { + return type; + } + + /** 平台原始售后类型值(如「退款」「退货」或数字)。 */ + public String rawType() { + return rawType; + } + + /** 退货状态等平台原始状态;无则为 null。 */ + public String status() { + return status; + } + + public String reason() { + return reason; + } + + /** 售后数量。 */ + public int quantity() { + return quantity; + } + + /** 平台侧 SKU。 */ + public String platformSku() { + return platformSku; + } + + public String localSku() { + return localSku; + } + + public String asin() { + return asin; + } + + /** 本行退款金额;没有退款时为 null。 */ + public Money refundAmount() { + return refundAmount; + } + + /** 本行退款花费(平台手续费);没有时为 null。 */ + public Money refundCost() { + return refundCost; + } + + /** 售后发生时间。 */ + public PlatformTime afterSaleTime() { + return afterSaleTime; + } + + /** 本行数据更新时间;增量同步用它判断。 */ + public PlatformTime updatedAt() { + return updatedAt; + } + + /** 退货授权号(RMA)。 */ + public String rmaNumber() { + return rmaNumber; + } + + public String carrier() { + return carrier; + } + + public String trackingNumber() { + return trackingNumber; + } + + /** 换货产生的新订单号。 */ + public String exchangeOrderId() { + return exchangeOrderId; + } + + public String buyerNote() { + return buyerNote; + } + + /** 未标准化的原始字段(金额明细、库存属性、多渠道标记等)。 */ + public Map attributes() { + return attributes; + } + + public ChannelProvider sourceProvider() { + return sourceProvider; + } + + public static final class Builder { + + private Platform platform; + private String omsStoreId; + private String afterSaleId; + private String channelOrderId; + private AfterSaleType type; + private String rawType; + private String status; + private String reason; + private int quantity; + private String platformSku; + private String localSku; + private String asin; + private Money refundAmount; + private Money refundCost; + private PlatformTime afterSaleTime; + private PlatformTime updatedAt; + private String rmaNumber; + private String carrier; + private String trackingNumber; + private String exchangeOrderId; + private String buyerNote; + private Map attributes = Collections.emptyMap(); + private ChannelProvider sourceProvider; + + public Builder platform(Platform v) { this.platform = v; return this; } + public Builder omsStoreId(String v) { this.omsStoreId = v; return this; } + public Builder afterSaleId(String v) { this.afterSaleId = v; return this; } + public Builder channelOrderId(String v) { this.channelOrderId = v; return this; } + public Builder type(AfterSaleType v) { this.type = v; return this; } + public Builder rawType(String v) { this.rawType = v; return this; } + public Builder status(String v) { this.status = v; return this; } + public Builder reason(String v) { this.reason = v; return this; } + public Builder quantity(int v) { this.quantity = v; return this; } + public Builder platformSku(String v) { this.platformSku = v; return this; } + public Builder localSku(String v) { this.localSku = v; return this; } + public Builder asin(String v) { this.asin = v; return this; } + public Builder refundAmount(Money v) { this.refundAmount = v; return this; } + public Builder refundCost(Money v) { this.refundCost = v; return this; } + public Builder afterSaleTime(PlatformTime v) { this.afterSaleTime = v; return this; } + public Builder updatedAt(PlatformTime v) { this.updatedAt = v; return this; } + public Builder rmaNumber(String v) { this.rmaNumber = v; return this; } + public Builder carrier(String v) { this.carrier = v; return this; } + public Builder trackingNumber(String v) { this.trackingNumber = v; return this; } + public Builder exchangeOrderId(String v) { this.exchangeOrderId = v; return this; } + public Builder buyerNote(String v) { this.buyerNote = v; return this; } + public Builder attributes(Map v) { + this.attributes = v == null ? Collections.emptyMap() : v; + return this; + } + public Builder sourceProvider(ChannelProvider v) { this.sourceProvider = v; return this; } + + public AfterSale build() { + return new AfterSale(this); + } + } +} diff --git a/core/src/main/java/common/ecommerce/model/aftersale/AfterSaleQuery.java b/core/src/main/java/common/ecommerce/model/aftersale/AfterSaleQuery.java new file mode 100644 index 0000000..5a7a2d8 --- /dev/null +++ b/core/src/main/java/common/ecommerce/model/aftersale/AfterSaleQuery.java @@ -0,0 +1,147 @@ +package common.ecommerce.model.aftersale; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** + * 售后订单查询条件(单次查询,不推进水位线)。 + * + *

时间窗是必填:领星售后接口要求 {@code start_date} / {@code end_date}, + * 左闭右开,精度到天。日期含义由 {@link #dateType()} 决定 + * (售后时间 / 订购时间 / 更新时间)。

+ */ +public final class AfterSaleQuery { + + private final LocalDate startDate; + private final LocalDate endDate; + private final DateType dateType; + private final List types; + private final List channelOrderIds; + private final int pageSize; + private final String cursor; + + private AfterSaleQuery(Builder b) { + this.startDate = Objects.requireNonNull(b.startDate, "startDate"); + this.endDate = Objects.requireNonNull(b.endDate, "endDate"); + if (!startDate.isBefore(endDate)) { + throw new IllegalArgumentException("startDate must be strictly before endDate (left-closed, right-open)"); + } + this.dateType = b.dateType == null ? DateType.AFTER_SALE_TIME : b.dateType; + this.types = Collections.unmodifiableList(new ArrayList(b.types)); + this.channelOrderIds = Collections.unmodifiableList(new ArrayList(b.channelOrderIds)); + this.pageSize = b.pageSize; + this.cursor = b.cursor; + } + + public static Builder builder() { + return new Builder(); + } + + /** 查询起点,含。 */ + public LocalDate startDate() { + return startDate; + } + + /** 查询终点,不含(左闭右开)。 */ + public LocalDate endDate() { + return endDate; + } + + public DateType dateType() { + return dateType; + } + + /** 售后类型过滤;空列表表示不过滤。 */ + public List types() { + return types; + } + + /** 按平台订单号过滤;空列表表示不过滤。 */ + public List channelOrderIds() { + return channelOrderIds; + } + + public int pageSize() { + return pageSize; + } + + public String cursor() { + return cursor; + } + + public Builder toBuilder() { + return builder() + .startDate(startDate) + .endDate(endDate) + .dateType(dateType) + .types(types) + .channelOrderIds(channelOrderIds) + .pageSize(pageSize) + .cursor(cursor); + } + + /** 时间窗按哪个字段过滤。 */ + public enum DateType { + + /** 售后时间(平台默认)。 */ + AFTER_SALE_TIME, + /** 原始订单的订购时间。 */ + PURCHASE_TIME, + /** 数据更新时间。 */ + UPDATE_TIME + } + + public static final class Builder { + + private LocalDate startDate; + private LocalDate endDate; + private DateType dateType; + private List types = Collections.emptyList(); + private List channelOrderIds = Collections.emptyList(); + private int pageSize = 100; + private String cursor; + + public Builder startDate(LocalDate startDate) { + this.startDate = startDate; + return this; + } + + public Builder endDate(LocalDate endDate) { + this.endDate = endDate; + return this; + } + + public Builder dateType(DateType dateType) { + this.dateType = dateType; + return this; + } + + public Builder types(List types) { + this.types = types == null ? Collections.emptyList() : types; + return this; + } + + public Builder channelOrderIds(List channelOrderIds) { + this.channelOrderIds = channelOrderIds == null + ? Collections.emptyList() : channelOrderIds; + return this; + } + + public Builder pageSize(int pageSize) { + this.pageSize = pageSize; + return this; + } + + public Builder cursor(String cursor) { + this.cursor = cursor; + return this; + } + + public AfterSaleQuery build() { + return new AfterSaleQuery(this); + } + } +} diff --git a/core/src/main/java/common/ecommerce/model/aftersale/AfterSaleType.java b/core/src/main/java/common/ecommerce/model/aftersale/AfterSaleType.java new file mode 100644 index 0000000..4b44408 --- /dev/null +++ b/core/src/main/java/common/ecommerce/model/aftersale/AfterSaleType.java @@ -0,0 +1,19 @@ +package common.ecommerce.model.aftersale; + +/** + * 售后类型。 + * + *

平台原始值可能是数字(领星 {@code 1 退款 / 2 退货 / 3 换货})或中文标签 + * ({@code after_type_tag = ["退款","退货","换货"]}),由 Mapper 归一到这里。

+ */ +public enum AfterSaleType { + + /** 仅退款。 */ + REFUND, + /** 退货退款。 */ + RETURN, + /** 换货。 */ + EXCHANGE, + /** 无法识别;原值见 {@link AfterSaleItem#rawAfterType()}。 */ + UNKNOWN +} diff --git a/core/src/main/java/common/ecommerce/sdk/ChannelSdk.java b/core/src/main/java/common/ecommerce/sdk/ChannelSdk.java index 8599d67..47aff82 100644 --- a/core/src/main/java/common/ecommerce/sdk/ChannelSdk.java +++ b/core/src/main/java/common/ecommerce/sdk/ChannelSdk.java @@ -2,6 +2,7 @@ package common.ecommerce.sdk; import common.ecommerce.model.Platform; import common.ecommerce.capability.AdapterCapabilityReport; +import common.ecommerce.capability.AfterSales; import common.ecommerce.capability.AggregatorCapable; import common.ecommerce.error.ChannelException; import common.ecommerce.model.Capability; @@ -141,6 +142,17 @@ public final class ChannelSdk implements ProviderResolver { } /** + * 售后视图:拉取退款 / 退货 / 换货订单(只读)。 + * + *

能力检查发生在 {@code pull()} 调用时;适配器未实现 {@code AfterSaleCapable} + * 或未声明 {@code RETURNS} 能力时抛 {@code UnsupportedCapabilityException}。

+ */ + public AfterSales afterSales(AccountKey key, ChannelConnection connection) { + ChannelAccount account = requireAccount(key); + return new AfterSales(resolve(key), account, newContext(account, connection)); + } + + /** * 履约 / 出库视图。 * *

写操作:会改变平台数据。领星没有测试环境,验证阶段禁止调用。

diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java index 1ba831e..0b6c718 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java @@ -101,6 +101,9 @@ public enum LingxingApi { /** 快速出库结果查询。POST,qps 10,多平台通用。只读,可安全验证。 */ FAST_OUTBOUND_RESULT("/pb/mp/order/v2/getFastOutboundResult", 10), + /** 售后订单列表(退款 / 退货 / 换货)。POST,qps 1,返回 data 数组。 */ + AFTER_SALE_LIST("/erp/sc/routing/amzod/order/afterSaleList", 1), + /** 多平台订单列表;当前实现使用的跨平台接口。 */ ORDER_LIST("/pb/mp/order/v2/list", 10); diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java b/lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java index b7afee9..fdfd530 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java @@ -1,5 +1,6 @@ package common.ecommerce.lingxing.adapter; +import common.ecommerce.capability.AfterSaleCapable; import common.ecommerce.capability.AggregatorCapable; import common.ecommerce.capability.OutboundCapable; import common.ecommerce.capability.ProductCapable; @@ -26,6 +27,8 @@ import common.ecommerce.model.account.ChannelAccount; import common.ecommerce.model.order.SalesOrder; import common.ecommerce.model.order.SalesOrderQuery; import common.ecommerce.model.order.SalesOrderRef; +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleQuery; import common.ecommerce.model.fulfillment.OutboundPackage; import common.ecommerce.model.fulfillment.OutboundResult; import common.ecommerce.model.product.ProductListing; @@ -57,7 +60,7 @@ import java.util.Set; * {@link LingxingSubPlatform}。

*/ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, SettlementCapable, - OutboundCapable, AggregatorCapable { + OutboundCapable, AfterSaleCapable, AggregatorCapable { private final HttpTransport transport; private final JacksonJsonCodec json; @@ -132,7 +135,8 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @Override public EnumSet capabilities() { - return EnumSet.of(Capability.SALES_ORDER, Capability.PRODUCT, Capability.BILLING, Capability.MARK_SHIPPED); + return EnumSet.of(Capability.SALES_ORDER, Capability.PRODUCT, Capability.BILLING, + Capability.MARK_SHIPPED, Capability.RETURNS); } /** @@ -164,6 +168,9 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, if (capability == Capability.MARK_SHIPPED) { return impl.outboundSource() != null; } + if (capability == Capability.RETURNS) { + return impl.afterSaleSource() != null; + } return false; } @@ -243,6 +250,15 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, } @Override + public Page pull(ChannelContext ctx, AfterSaleQuery query) { + LingxingSubPlatform impl = subPlatforms.of(ctx.platform()); + if (impl.afterSaleSource() == null) { + throw new ChannelException.UnsupportedCapabilityException(Capability.RETURNS); + } + return impl.afterSaleSource().pull(call(ctx), query); + } + + @Override public boolean submit(ChannelContext ctx, List packages) { return outboundSource(ctx).submit(call(ctx), packages); } diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingAfterSaleSource.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingAfterSaleSource.java new file mode 100644 index 0000000..55dde9a --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingAfterSaleSource.java @@ -0,0 +1,17 @@ +package common.ecommerce.lingxing.platform; + +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleQuery; +import common.ecommerce.model.support.Page; + +/** + * 子平台的售后能力(只读)。 + * + *

只负责「拼请求体 + 解析响应」;限流、取 token、签名、业务码校验由 + * {@link LingxingCall} 提供。

+ */ +public interface LingxingAfterSaleSource { + + /** 分页拉取售后订单;统一模型按商品行展开。 */ + Page pull(LingxingCall call, AfterSaleQuery query); +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java index f51e01b..8a9bb30 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java @@ -49,6 +49,11 @@ public interface LingxingSubPlatform { return null; } + /** 售后能力(只读);不支持时为 null。 */ + default LingxingAfterSaleSource afterSaleSource() { + return null; + } + /** 快速出库能力;不支持时为 null。多平台通用接口。 */ default LingxingOutboundSource outboundSource() { return null; diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSource.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSource.java new file mode 100644 index 0000000..a389e2a --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSource.java @@ -0,0 +1,145 @@ +package common.ecommerce.lingxing.platform.aftersale; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.HttpResponse; +import common.ecommerce.lingxing.LingxingApi; +import common.ecommerce.lingxing.http.LingxingEnvelope; +import common.ecommerce.lingxing.platform.LingxingAfterSaleSource; +import common.ecommerce.lingxing.platform.LingxingCall; +import common.ecommerce.lingxing.platform.aftersale.dto.AfterSaleDto; +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleQuery; +import common.ecommerce.model.aftersale.AfterSaleType; +import common.ecommerce.model.support.Page; + +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 领星 · 售后订单列表。 + * + *

接口 {@code /erp/sc/routing/amzod/order/afterSaleList}:POST, + * {@code offset}/{@code length} 分页,返回 {@code data} 数组;令牌桶容量 1。

+ * + *

领星按订单聚合返回,这里按 item_list 商品行展开成统一模型。 + * 因此「一页」的条目数可能大于返回的订单记录数——分页游标按领星侧记录数推进, + * 不能用展开后的条目数。

+ */ +public final class LingxingAfterSaleListSource implements LingxingAfterSaleSource { + + /** 文档给的默认分页长度。 */ + private static final int DEFAULT_PAGE_SIZE = 1000; + + /** 单次查询的订单号上限。 */ + private static final int MAX_ORDER_IDS = 50; + + /** 时间窗类型:1 售后时间(默认)/ 2 订购时间 / 3 更新时间。 */ + private static final int DATE_TYPE_AFTER_SALE = 1; + private static final int DATE_TYPE_PURCHASE = 2; + private static final int DATE_TYPE_UPDATE = 3; + + private static final String OP = "afterSales.pull"; + + private final LingxingAfterSaleMapper mapper = new LingxingAfterSaleMapper(); + + @Override + public Page pull(LingxingCall call, AfterSaleQuery query) { + if (query.channelOrderIds().size() > MAX_ORDER_IDS) { + throw new IllegalArgumentException( + "amazon_order_id_list supports at most " + MAX_ORDER_IDS + " ids, got " + + query.channelOrderIds().size()); + } + + int length = query.pageSize() <= 0 ? DEFAULT_PAGE_SIZE : query.pageSize(); + int offset = query.cursor() == null ? 0 : Integer.parseInt(query.cursor()); + + Map body = new LinkedHashMap(); + body.put("offset", offset); + body.put("length", length); + applyAccount(body, call); + applyTimeWindow(body, query); + applyFilters(body, query); + + HttpRequest req = call.signed(LingxingApi.AFTER_SALE_LIST, body, OP); + HttpResponse resp = call.execute(req); + LingxingEnvelope envelope = call.envelope(resp, OP); + + List dtos = call.json().listAt(envelope.body(), "data", AfterSaleDto.class); + List out = new ArrayList(); + ZoneId zone = ZoneId.of(call.ctx().account().marketplaceZone()); + for (AfterSaleDto dto : dtos) { + out.addAll(mapper.toAfterSales(dto, call.ctx().platform(), call.ctx().omsStoreId(), zone)); + } + + // 游标按领星记录数推进,不是展开后的条目数 + int nextOffset = offset + dtos.size(); + boolean hasMore = dtos.size() >= length + && (envelope.total() < 0 || nextOffset < envelope.total()); + return Page.of(out, hasMore ? String.valueOf(nextOffset) : null); + } + + /** sid 非必填:账户配了才传(文档示例支持多个,用英文逗号分隔)。 */ + private static void applyAccount(Map body, LingxingCall call) { + String storeId = call.ctx().account().externalStoreId(); + if (storeId != null && !storeId.trim().isEmpty()) { + body.put("sid", storeId.trim()); + } + } + + /** 时间窗必填:左闭右开,精度到天。 */ + private static void applyTimeWindow(Map body, AfterSaleQuery query) { + body.put("start_date", query.startDate().toString()); + body.put("end_date", query.endDate().toString()); + switch (query.dateType()) { + case PURCHASE_TIME: + body.put("date_type", DATE_TYPE_PURCHASE); + break; + case UPDATE_TIME: + body.put("date_type", DATE_TYPE_UPDATE); + break; + default: + body.put("date_type", DATE_TYPE_AFTER_SALE); + break; + } + } + + /** 售后类型与订单号过滤;空列表表示不过滤。 */ + private static void applyFilters(Map body, AfterSaleQuery query) { + if (!query.types().isEmpty()) { + StringBuilder sb = new StringBuilder(); + for (AfterSaleType type : query.types()) { + int code = codeOf(type); + if (code <= 0) { + continue; + } + if (sb.length() > 0) { + sb.append(','); + } + sb.append(code); + } + if (sb.length() > 0) { + body.put("after_type", sb.toString()); + } + } + if (!query.channelOrderIds().isEmpty()) { + body.put("amazon_order_id_list", new ArrayList(query.channelOrderIds())); + } + } + + /** 统一售后类型 → 领星编码:1 退款 / 2 退货 / 3 换货。 */ + private static int codeOf(AfterSaleType type) { + switch (type) { + case REFUND: + return 1; + case RETURN: + return 2; + case EXCHANGE: + return 3; + default: + return 0; + } + } +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapper.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapper.java new file mode 100644 index 0000000..72eef10 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapper.java @@ -0,0 +1,267 @@ +package common.ecommerce.lingxing.platform.aftersale; + +import common.ecommerce.lingxing.platform.aftersale.dto.AfterSaleDto; +import common.ecommerce.lingxing.platform.aftersale.dto.AfterSaleItemDto; +import common.ecommerce.model.ChannelProvider; +import common.ecommerce.model.Platform; +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleType; +import common.ecommerce.model.support.Money; +import common.ecommerce.model.support.PlatformTime; + +import java.math.BigDecimal; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 领星售后订单 → 统一模型。 + * + *

展开粒度:领星一条记录按订单聚合,商品行在 {@code item_list} 里; + * 统一模型按商品行展开,一行对应一个 {@link AfterSale}。 + * 订单级字段(订单号、店铺、币种)从外层带入每一行。

+ * + *

时间精度:文档明确「同一订单存在多个售后单时, + * 需以 {@code item_list.after_time} / {@code data_update_time} 为准」, + * 所以行级时间优先,缺失时才回落订单级 {@code deal_time} / {@code gmt_modified}。

+ * + *

唯一标识:优先 {@code md5_v2}(文档推荐),其次 {@code item_identifier}, + * 再退化为 {@code msku + after_time + row_index} 组合。{@code id} 非唯一键,不能用。

+ */ +public final class LingxingAfterSaleMapper { + + /** 时间格式:Y-m-d H:i:s(文档未标时区,按北京时间解释,与其它领星接口一致)。 */ + private static final DateTimeFormatter DATE_TIME = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** 领星时间字符串未注明时区,按北京时间解释。 */ + private static final ZoneId BEIJING = PlatformTime.BEIJING_ZONE; + + public List toAfterSales(AfterSaleDto dto, Platform platform, + String omsStoreId, ZoneId marketplaceZone) { + List out = new ArrayList(); + List items = dto.getItemList() == null + ? Collections.emptyList() : dto.getItemList(); + if (items.isEmpty()) { + return out; + } + for (AfterSaleItemDto item : items) { + out.add(toAfterSale(dto, item, platform, omsStoreId, marketplaceZone)); + } + return out; + } + + private AfterSale toAfterSale(AfterSaleDto dto, AfterSaleItemDto item, Platform platform, + String omsStoreId, ZoneId marketplaceZone) { + String currency = orderCurrencyOf(dto, item); + + return AfterSale.builder() + .platform(platform) + .omsStoreId(omsStoreId) + .afterSaleId(resolveAfterSaleId(dto, item)) + .channelOrderId(trimToNull(dto.getAmazonOrderId())) + .type(typeOf(item.getAfterType())) + .rawType(item.getAfterType()) + .status(trimToNull(item.getReturnStatus())) + .reason(trimToNull(item.getAfterReason())) + .quantity(item.getAfterQuantity() == null ? 0 : item.getAfterQuantity()) + .platformSku(firstNonBlank(item.getMsku(), dto.getMsku())) + .localSku(trimToNull(item.getLocalSku())) + .asin(firstNonBlank(item.getAsin(), dto.getAsin())) + .refundAmount(moneyOrNull(item.getRefundAmount(), currency)) + .refundCost(moneyOrNull(item.getRefundCost(), currency)) + .afterSaleTime(localTime(firstNonBlank(item.getAfterTime(), dto.getDealTime()), marketplaceZone)) + .updatedAt(localTime(firstNonBlank(item.getDataUpdateTime(), dto.getGmtModified()), marketplaceZone)) + .rmaNumber(trimToNull(item.getRmaOrderNumber())) + .carrier(trimToNull(item.getCarriers())) + .trackingNumber(trimToNull(item.getWaybillNumber())) + .exchangeOrderId(trimToNull(item.getExchangeOrderNumber())) + .buyerNote(trimToNull(item.getBuyerNote())) + .attributes(attributesOf(dto, item)) + .sourceProvider(ChannelProvider.LINGXING) + .build(); + } + + // ---------------------------------------------------------------- 标识 + + /** + * 售后行唯一标识。优先 md5_v2,其次 item_identifier, + * 再退化为订单号 + msku + after_time + row_index;全空时抛异常,不静默造 key。 + */ + static String resolveAfterSaleId(AfterSaleDto dto, AfterSaleItemDto item) { + String id = firstNonBlank(item.getMd5V2(), item.getItemIdentifier()); + if (id != null) { + return id; + } + String fallback = firstNonBlank(dto.getAmazonOrderId()) + '|' + + firstNonBlank(item.getMsku(), dto.getMsku()) + '|' + + firstNonBlank(item.getAfterTime(), dto.getDealTime()) + '|' + + (item.getRowIndex() == null ? "" : item.getRowIndex()); + if (fallback.contains("null")) { + throw new IllegalArgumentException( + "lingxing after-sale row has neither md5_v2/item_identifier nor usable fallback fields"); + } + return "fallback|" + fallback; + } + + // ---------------------------------------------------------------- 类型与币种 + + /** 领星售后类型是中文标签:退款 / 退货 / 换货。 */ + static AfterSaleType typeOf(String raw) { + if (raw == null) { + return AfterSaleType.UNKNOWN; + } + String s = raw.trim(); + if (s.contains("换货")) { + return AfterSaleType.EXCHANGE; + } + if (s.contains("退货")) { + return AfterSaleType.RETURN; + } + if (s.contains("退款")) { + return AfterSaleType.REFUND; + } + return AfterSaleType.UNKNOWN; + } + + /** + * 币种:领星给的是符号(如 "$"),按约定映射为 ISO 代码。 + * + *

行级 {@code refund_currency_icon} 优先,其次订单级 currency_code。 + * 映射不出时返回 null,金额也置 null(不猜)。

+ */ + private static String orderCurrencyOf(AfterSaleDto dto, AfterSaleItemDto item) { + return currencyOf(firstNonBlank(item.getRefundCurrencyIcon(), + dto.getTotalRefundAmountCurrencyCode(), dto.getOrderTotalAmountCurrencyCode())); + } + + /** 货币符号 → ISO。约定:¥ 视为日元,CNY/RMB 视为人民币。 */ + static String currencyOf(String icon) { + if (icon == null) { + return null; + } + String s = icon.trim(); + if ("$".equals(s) || "US$".equals(s)) { + return "USD"; + } + if ("€".equals(s)) { + return "EUR"; + } + if ("£".equals(s)) { + return "GBP"; + } + if ("¥".equals(s) || "¥".equals(s)) { + return "JPY"; + } + if ("CNY".equalsIgnoreCase(s) || "RMB".equalsIgnoreCase(s)) { + return "CNY"; + } + return null; + } + + // ---------------------------------------------------------------- 工具 + + /** 领星金额带符号(如 "-$28.0200"),只保留数字与符号位。 */ + static Money moneyOrNull(String raw, String currency) { + if (raw == null || raw.trim().isEmpty() || currency == null) { + return null; + } + StringBuilder sb = new StringBuilder(raw.length()); + boolean hasDigit = false; + for (int i = 0; i < raw.length(); i++) { + char c = raw.charAt(i); + if (c >= '0' && c <= '9') { + sb.append(c); + hasDigit = true; + } else if (c == '.' || c == '-' || c == '+') { + sb.append(c); + } + } + if (!hasDigit) { + return null; + } + try { + return Money.of(new BigDecimal(sb.toString()), currency); + } catch (RuntimeException e) { + return null; + } + } + + private static PlatformTime localTime(String raw, ZoneId marketplaceZone) { + if (raw == null || raw.trim().isEmpty()) { + return null; + } + try { + Instant utc = java.time.LocalDateTime.parse(raw.trim(), DATE_TIME) + .atZone(BEIJING).toInstant(); + return PlatformTime.of(utc, marketplaceZone); + } catch (RuntimeException e) { + return null; + } + } + + /** 未标准化的原始字段:订单级与行级都放进来,键名与领星一致。 */ + private static Map attributesOf(AfterSaleDto dto, AfterSaleItemDto item) { + Map attrs = new LinkedHashMap(); + attrs.put("id", dto.getId()); + attrs.put("sid", dto.getSid()); + attrs.put("correlation_id", dto.getCorrelationId()); + attrs.put("purchase_time", dto.getPurchaseTime()); + attrs.put("interval_days", dto.getIntervalDays()); + attrs.put("is_mcf_order", dto.getIsMcfOrder()); + attrs.put("seller_country", dto.getSellerCountry()); + attrs.put("delivery_type", dto.getDeliveryType()); + attrs.put("order_total_amount", dto.getOrderTotalAmount()); + attrs.put("order_total_amount_currency_code", dto.getOrderTotalAmountCurrencyCode()); + attrs.put("order_total_amount_number", dto.getOrderTotalAmountNumber()); + attrs.put("total_refund_amount", dto.getTotalRefundAmount()); + attrs.put("total_refund_amount_number", + firstNonBlank(dto.getTotalRefundAmountNumber(), dto.getTotalRefundAmountNumberLegacy())); + attrs.put("total_refund_cost", dto.getTotalRefundCost()); + attrs.put("total_refund_cost_number", dto.getTotalRefundCostNumber()); + attrs.put("after_type_tag", dto.getAfterTypeTag()); + + attrs.put("small_image_url", item.getSmallImageUrl()); + attrs.put("item_name", item.getItemName()); + attrs.put("local_name", item.getLocalName()); + attrs.put("asin_url", item.getAsinUrl()); + attrs.put("fid", item.getFid()); + attrs.put("after_interval", item.getAfterInterval()); + attrs.put("refund_amount", item.getRefundAmount()); + attrs.put("refund_amount_details", item.getRefundAmountDetails()); + attrs.put("refund_cost", item.getRefundCost()); + attrs.put("refund_cost_details", item.getRefundCostDetails()); + attrs.put("inventory_attributes", item.getInventoryAttributes()); + attrs.put("lpn_number", item.getLpnNumber()); + attrs.put("md5", item.getMd5()); + attrs.put("md5_new", item.getMd5New()); + attrs.put("orderDateYear", item.getOrderDateYear()); + attrs.put("row_index", item.getRowIndex()); + attrs.values().removeAll(Collections.singleton(null)); + return attrs; + } + + private static String firstNonBlank(String... values) { + for (String v : values) { + String trimmed = trimToNull(v); + if (trimmed != null) { + return trimmed; + } + } + return null; + } + + private static String trimToNull(String v) { + if (v == null) { + return null; + } + String trimmed = v.trim(); + return trimmed.isEmpty() ? null : trimmed; + } + +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleDto.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleDto.java new file mode 100644 index 0000000..af152b2 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleDto.java @@ -0,0 +1,129 @@ +package common.ecommerce.lingxing.platform.aftersale.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.List; + +/** + * 领星售后订单({@code /erp/sc/routing/amzod/order/afterSaleList} 的 {@code data[]})。 + * + *

一条记录是按订单聚合的,商品行在 {@code item_list} 里。 + * 统一模型会按商品行展开,所以真正参与映射的是 {@link AfterSaleItemDto}。

+ * + *

金额字段有三组形态:{@code xxx}(带符号字符串)、{@code xxx_currency_code}(币种符号)、 + * {@code xxx_number}(纯数字)。映射时用 currency_code + number,不用带符号的合并串。

+ */ +@Getter +@Setter +@JsonIgnoreProperties(ignoreUnknown = true) +public class AfterSaleDto { + + /** 记录 id,非唯一键。 */ + @JsonProperty("id") + private Long id; + + /** 亚马逊订单号。 */ + @JsonProperty("amazon_order_id") + private String amazonOrderId; + + /** 店铺 id。 */ + @JsonProperty("sid") + private Long sid; + + /** 订单号级 ASIN。 */ + @JsonProperty("asin") + private String asin; + + /** 订单号级 MSKU。 */ + @JsonProperty("msku") + private String msku; + + /** 关联 id。 */ + @JsonProperty("correlation_id") + private Long correlationId; + + /** 订购时间,Y-m-d H:i:s。 */ + @JsonProperty("purchase_time") + private String purchaseTime; + + /** 售后时间;同一订单多个售后单时以 item_list.after_time 为准。 */ + @JsonProperty("deal_time") + private String dealTime; + + /** 更新时间;同一订单多个售后单时以 item_list.data_update_time 为准。 */ + @JsonProperty("gmt_modified") + private String gmtModified; + + /** 售后间隔天数。 */ + @JsonProperty("interval_days") + private Integer intervalDays; + + /** 是否多渠道订单:0 默认 / 1 普通 / 2 多渠道。 */ + @JsonProperty("is_mcf_order") + private Integer isMcfOrder; + + /** 店铺国家信息。 */ + @JsonProperty("seller_country") + private String sellerCountry; + + /** 配送方式,如 FBA / FBM。 */ + @JsonProperty("delivery_type") + private String deliveryType; + + /** 订单总金额(带符号)。 */ + @JsonProperty("order_total_amount") + private String orderTotalAmount; + + /** 订单总金额币种符号。 */ + @JsonProperty("order_total_amount_currency_code") + private String orderTotalAmountCurrencyCode; + + /** 订单总金额数值。 */ + @JsonProperty("order_total_amount_number") + private String orderTotalAmountNumber; + + /** 退款总金额(带符号)。 */ + @JsonProperty("total_refund_amount") + private String totalRefundAmount; + + /** 退款总金额币种符号。 */ + @JsonProperty("total_refund_amount_currency_code") + private String totalRefundAmountCurrencyCode; + + /** + * 退款总金额数值。 + * + *

文档写 {@code total_refund_amount_number},但示例响应里是 + * {@code total_refund_amount__number}(两个下划线)。两个都收,Mapper 优先取正常的。

+ */ + @JsonProperty("total_refund_amount_number") + private String totalRefundAmountNumber; + + /** 兼容示例里的双下划线写法。 */ + @JsonProperty("total_refund_amount__number") + private String totalRefundAmountNumberLegacy; + + /** 退款总费用(带符号)。 */ + @JsonProperty("total_refund_cost") + private String totalRefundCost; + + /** 退款总费用币种符号。 */ + @JsonProperty("total_refund_cost_currency_code") + private String totalRefundCostCurrencyCode; + + /** 退款总费用数值。 */ + @JsonProperty("total_refund_cost_number") + private String totalRefundCostNumber; + + /** 售后类型标签,如 ["退款","退货","换货"]。 */ + @JsonProperty("after_type_tag") + private List afterTypeTag = new ArrayList(); + + /** 商品行。 */ + @JsonProperty("item_list") + private List itemList = new ArrayList(); +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleItemDto.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleItemDto.java new file mode 100644 index 0000000..ef0dac1 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AfterSaleItemDto.java @@ -0,0 +1,153 @@ +package common.ecommerce.lingxing.platform.aftersale.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.List; + +/** + * 领星售后商品行({@code item_list[]})。 + * + *

售后的真正粒度在这里:售后时间、更新时间、售后类型、退款金额都按行给出。 + * 统一模型 一行 = 一个 AfterSale。

+ */ +@Getter +@Setter +@JsonIgnoreProperties(ignoreUnknown = true) +public class AfterSaleItemDto { + + /** 商品缩略图。 */ + @JsonProperty("small_image_url") + private String smallImageUrl; + + /** 商品标题。 */ + @JsonProperty("item_name") + private String itemName; + + /** 本地 SKU。 */ + @JsonProperty("local_sku") + private String localSku; + + /** 本地商品名称。 */ + @JsonProperty("local_name") + private String localName; + + /** ASIN。 */ + @JsonProperty("asin") + private String asin; + + /** ASIN 链接。 */ + @JsonProperty("asin_url") + private String asinUrl; + + /** 平台侧 MSKU。 */ + @JsonProperty("msku") + private String msku; + + /** FBA 订单行标识(部分行有)。 */ + @JsonProperty("fid") + private String fid; + + /** 售后类型(中文),如「退款」「退货」。 */ + @JsonProperty("after_type") + private String afterType; + + /** 售后数量。 */ + @JsonProperty("after_quantity") + private Integer afterQuantity; + + /** 售后原因。 */ + @JsonProperty("after_reason") + private String afterReason; + + /** 售后时间;比订单级 {@code deal_time} 更准确。 */ + @JsonProperty("after_time") + private String afterTime; + + /** 售后间隔,如「10天」。 */ + @JsonProperty("after_interval") + private String afterInterval; + + /** 本行数据更新时间;比订单级 {@code gmt_modified} 更准确。 */ + @JsonProperty("data_update_time") + private String dataUpdateTime; + + /** 退款金额(带符号字符串,如 "-$28.0200")。 */ + @JsonProperty("refund_amount") + private String refundAmount; + + /** 退款金额明细,有退款金额时才返回。 */ + @JsonProperty("refund_amount_details") + private List refundAmountDetails = new ArrayList(); + + /** 退款花费(带符号字符串)。 */ + @JsonProperty("refund_cost") + private String refundCost; + + /** 退款花费明细。 */ + @JsonProperty("refund_cost_details") + private List refundCostDetails = new ArrayList(); + + /** 退款币种符号;部分行有。 */ + @JsonProperty("refund_currency_icon") + private String refundCurrencyIcon; + + /** 退货状态,如 Approved。 */ + @JsonProperty("return_status") + private String returnStatus; + + /** 库存属性。 */ + @JsonProperty("inventory_attributes") + private String inventoryAttributes; + + /** LPN 编号。 */ + @JsonProperty("lpn_number") + private String lpnNumber; + + /** 买家备注。 */ + @JsonProperty("buyers_note") + private String buyerNote; + + /** RMA 单号。 */ + @JsonProperty("rma_order_number") + private String rmaOrderNumber; + + /** 承运商。 */ + @JsonProperty("carriers") + private String carriers; + + /** 运单号。 */ + @JsonProperty("waybill_number") + private String waybillNumber; + + /** 换货产生的新订单号。 */ + @JsonProperty("exchange_order_number") + private String exchangeOrderNumber; + + /** 旧版唯一标识,已废弃。 */ + @JsonProperty("md5") + private String md5; + + /** 旧版唯一标识,已废弃。 */ + @JsonProperty("md5_new") + private String md5New; + + /** 唯一标识(推荐)。 */ + @JsonProperty("item_identifier") + private String itemIdentifier; + + /** 压缩后的唯一标识(推荐)。 */ + @JsonProperty("md5_v2") + private String md5V2; + + /** 订单数据年份。 */ + @JsonProperty("orderDateYear") + private Integer orderDateYear; + + /** 解析数据编号。 */ + @JsonProperty("row_index") + private Long rowIndex; +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AmountDetailDto.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AmountDetailDto.java new file mode 100644 index 0000000..11308aa --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/aftersale/dto/AmountDetailDto.java @@ -0,0 +1,21 @@ +package common.ecommerce.lingxing.platform.aftersale.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.Setter; + +/** 金额明细({@code refund_amount_details[]} / {@code refund_cost_details[]})。 */ +@Getter +@Setter +@JsonIgnoreProperties(ignoreUnknown = true) +public class AmountDetailDto { + + /** 类型,如 goodwill / principal / shippingCharge / commission。 */ + @JsonProperty("type") + private String type; + + /** 金额(带符号字符串,如 "-$2.350")。 */ + @JsonProperty("amount") + private String amount; +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/sc/AmazonScSubPlatform.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/sc/AmazonScSubPlatform.java index 5fd3374..9a4a4b4 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/sc/AmazonScSubPlatform.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/sc/AmazonScSubPlatform.java @@ -2,7 +2,9 @@ package common.ecommerce.lingxing.platform.amazon.sc; import common.ecommerce.http.HttpTransport; import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.lingxing.platform.LingxingAfterSaleSource; import common.ecommerce.lingxing.platform.LingxingSubPlatform; +import common.ecommerce.lingxing.platform.aftersale.LingxingAfterSaleListSource; import common.ecommerce.lingxing.platform.amazon.order.AmazonFbmOrderSource; import common.ecommerce.lingxing.platform.amazon.order.AmazonOrderSource; import common.ecommerce.lingxing.platform.amazon.settlement.AmazonSettlementSource; @@ -29,6 +31,7 @@ public final class AmazonScSubPlatform implements LingxingSubPlatform { private final LingxingProductSource products; private final LingxingShopSource shops; private final LingxingSettlementSource settlements; + private final LingxingAfterSaleSource afterSales; public AmazonScSubPlatform(HttpTransport transport, JacksonJsonCodec json) { this.orders = new AmazonOrderSource(); @@ -36,6 +39,7 @@ public final class AmazonScSubPlatform implements LingxingSubPlatform { this.products = new AmazonScProductSource(); this.shops = new AmazonScShopSource(); this.settlements = new AmazonSettlementSource(); + this.afterSales = new LingxingAfterSaleListSource(); } @Override @@ -69,6 +73,11 @@ public final class AmazonScSubPlatform implements LingxingSubPlatform { } @Override + public LingxingAfterSaleSource afterSaleSource() { + return afterSales; + } + + @Override public LingxingOutboundSource outboundSource() { return OUTBOUND; } diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/SdkCallGuideTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/SdkCallGuideTest.java index d4ec1e3..5775914 100644 --- a/lingxing/src/test/java/common/ecommerce/lingxing/SdkCallGuideTest.java +++ b/lingxing/src/test/java/common/ecommerce/lingxing/SdkCallGuideTest.java @@ -62,8 +62,7 @@ class SdkCallGuideTest { /** ---------------------------------------------------------------- 第 2 步:连接信息 */ private static ChannelConnection connection() { - return ChannelConnection.of(ENDPOINT, - ChannelSecret.builder().appKey(APP_KEY).appSecret(APP_SECRET).build()); + return ChannelConnection.of(ENDPOINT, ChannelSecret.builder().appKey(APP_KEY).appSecret(APP_SECRET).build()); } /** ---------------------------------------------------------------- 第 3 步:构建 SDK */ diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSourceTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSourceTest.java new file mode 100644 index 0000000..eedd592 --- /dev/null +++ b/lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleListSourceTest.java @@ -0,0 +1,134 @@ +package common.ecommerce.lingxing.platform.aftersale; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.HttpResponse; +import common.ecommerce.http.HttpTransport; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.lingxing.LingxingApi; +import common.ecommerce.lingxing.auth.LingxingTokenClient; +import common.ecommerce.lingxing.http.LingxingRateLimiter; +import common.ecommerce.lingxing.http.LingxingRequestFactory; +import common.ecommerce.lingxing.platform.LingxingCall; +import common.ecommerce.model.ChannelProvider; +import common.ecommerce.model.Platform; +import common.ecommerce.model.account.AccountKey; +import common.ecommerce.model.account.ChannelAccount; +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleQuery; +import common.ecommerce.model.aftersale.AfterSaleType; +import common.ecommerce.model.support.Page; +import common.ecommerce.sdk.ChannelConnection; +import common.ecommerce.sdk.ChannelContext; +import common.ecommerce.spi.AccessToken; +import common.ecommerce.spi.ChannelSecret; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 领星售后列表接口的请求构造测试。 + * + *

传输层返回录制报文后直接断言请求体,不联网。

+ */ +class LingxingAfterSaleListSourceTest { + + private static final Clock CLOCK = Clock.fixed(java.time.Instant.parse("2026-11-04T00:00:00Z"), + java.time.ZoneOffset.UTC); + + @Test + void requestCarriesTimeWindowAndFilters() throws Exception { + RecordingTransport transport = new RecordingTransport(); + LingxingAfterSaleListSource source = new LingxingAfterSaleListSource(); + + Page page = source.pull(call(transport, "1105"), AfterSaleQuery.builder() + .startDate(LocalDate.parse("2026-10-01")) + .endDate(LocalDate.parse("2026-11-01")) + .dateType(AfterSaleQuery.DateType.UPDATE_TIME) + .types(Arrays.asList(AfterSaleType.REFUND, AfterSaleType.RETURN)) + .channelOrderIds(Arrays.asList("113-1", "113-2")) + .pageSize(200) + .build()); + + // 两条请求:先换 token,再拉售后 + assertEquals(2, transport.requests.size()); + HttpRequest req = transport.requests.get(1); + assertTrue(req.url().startsWith("https://openapi.lingxing.com" + + LingxingApi.AFTER_SALE_LIST.path()), req.url()); + + String body = req.body(); + assertTrue(body.contains("\"start_date\":\"2026-10-01\""), body); + assertTrue(body.contains("\"end_date\":\"2026-11-01\""), body); + assertTrue(body.contains("\"date_type\":3"), body); + assertTrue(body.contains("\"after_type\":\"1,2\""), body); + assertTrue(body.contains("\"amazon_order_id_list\":[\"113-1\",\"113-2\"]"), body); + assertTrue(body.contains("\"sid\":\"1105\""), body); + assertTrue(body.contains("\"length\":200"), body); + assertTrue(body.contains("\"offset\":0"), body); + + // 一条筛选记录含 2 个商品行 → 2 条统一模型;游标按记录数推进 + assertEquals(2, page.size()); + assertEquals(null, page.nextCursor()); + } + + private static LingxingCall call(HttpTransport transport, String storeId) throws Exception { + JacksonJsonCodec json = new JacksonJsonCodec(); + ChannelAccount account = ChannelAccount.builder() + .key(AccountKey.of(ChannelProvider.LINGXING, Platform.AMAZON_SC, "oms-amz-001")) + .externalStoreId(storeId) + .platformCode(10001) + .credentialRef("test") + .marketplaceZone("America/Los_Angeles") + .currency("USD") + .build(); + ChannelSecret secret = ChannelSecret.builder() + .appKey("test-app-id-1234").appSecret("test-app-secret").build(); + ChannelConnection conn = ChannelConnection.of("https://openapi.lingxing.com", secret); + ChannelContext ctx = ChannelContext.of(account, conn, "req-1", CLOCK); + AccessToken token = new LingxingTokenClient(transport, json, CLOCK) + .fetch("https://openapi.lingxing.com", "test-app-id-1234", "test-app-secret"); + return new LingxingCall(ctx, token, new LingxingRequestFactory(json, CLOCK), + new LingxingRateLimiter(), json, transport); + } + + /** 令牌返回最小成功响应;售后请求返回文档示例夹具。 */ + static final class RecordingTransport implements HttpTransport { + + final List requests = new ArrayList(); + + @Override + public HttpResponse execute(HttpRequest request) { + requests.add(request); + if (request.url().contains("/oauth/access-token")) { + return HttpResponse.of(200, Collections.emptyMap(), + "{\"code\":\"200\",\"msg\":\"OK\",\"data\":{\"access_token\":\"tok\"," + + "\"refresh_token\":\"ref\",\"expires_in\":7199}}", 1); + } + try { + return HttpResponse.of(200, Collections.emptyMap(), + load("fixtures/lingxing/afterSale/success.json"), 1); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String load(String path) throws Exception { + java.io.InputStream in = LingxingAfterSaleListSourceTest.class.getClassLoader() + .getResourceAsStream(path); + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = in.read(buf)) >= 0) { + out.write(buf, 0, n); + } + return new String(out.toByteArray(), "UTF-8"); + } + } +} diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapperTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapperTest.java new file mode 100644 index 0000000..7fba987 --- /dev/null +++ b/lingxing/src/test/java/common/ecommerce/lingxing/platform/aftersale/LingxingAfterSaleMapperTest.java @@ -0,0 +1,146 @@ +package common.ecommerce.lingxing.platform.aftersale; + +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.lingxing.platform.aftersale.dto.AfterSaleDto; +import common.ecommerce.model.ChannelProvider; +import common.ecommerce.model.Platform; +import common.ecommerce.model.aftersale.AfterSale; +import common.ecommerce.model.aftersale.AfterSaleType; +import org.junit.jupiter.api.Test; + +import java.time.ZoneId; +import java.util.List; + +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; + +/** + * 领星售后订单 → 统一模型。 + * + *

夹具来自官方文档示例({@code fixtures/lingxing/afterSale/success.json})。

+ */ +class LingxingAfterSaleMapperTest { + + private final JacksonJsonCodec json = new JacksonJsonCodec(); + private final LingxingAfterSaleMapper mapper = new LingxingAfterSaleMapper(); + + private List rows() throws Exception { + String body = load("fixtures/lingxing/afterSale/success.json"); + List dtos = json.listAt(body, "data", AfterSaleDto.class); + return mapper.toAfterSales(dtos.get(0), Platform.AMAZON_SC, "oms-amz-001", + ZoneId.of("America/Los_Angeles")); + } + + /** 读夹具;Fixtures 已随 FakeTransport 一起移除,这里用最小实现。 */ + private static String load(String path) throws Exception { + java.io.InputStream in = LingxingAfterSaleMapperTest.class.getClassLoader().getResourceAsStream(path); + if (in == null) { + throw new IllegalStateException("fixture not found: " + path); + } + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = in.read(buf)) >= 0) { + out.write(buf, 0, n); + } + return new String(out.toByteArray(), "UTF-8"); + } + + @Test + void expandsOneOrderIntoItemRows() throws Exception { + // 领星一条记录带 2 个商品行 → 统一模型 2 条 + assertEquals(2, rows().size()); + } + + @Test + void mapsReturnRow() throws Exception { + AfterSale row = rows().get(0); + assertEquals(Platform.AMAZON_SC, row.platform()); + assertEquals("oms-amz-001", row.omsStoreId()); + assertEquals("113-9870855-8214638", row.channelOrderId()); + assertEquals(AfterSaleType.RETURN, row.type()); + assertEquals("退货", row.rawType()); + assertEquals("Approved", row.status()); + assertEquals("CR-ORDERED_WRONG_ITEM", row.reason()); + assertEquals(1, row.quantity()); + assertEquals("Pink_Head_Rope_12", row.platformSku()); + assertEquals("auto010", row.localSku()); + assertEquals("B09MT9BKAD", row.asin()); + assertEquals("D5LCqzJZRRMA", row.rmaNumber()); + assertEquals("USPS", row.carrier()); + assertEquals("9202090153540168949151", row.trackingNumber()); + assertEquals("自动化备注", row.buyerNote()); + assertEquals(ChannelProvider.LINGXING, row.sourceProvider()); + } + + @Test + void rowTimePreferredOverOrderTime() throws Exception { + AfterSale row = rows().get(0); + // 行级 after_time 2023-02-17 00:00:00(北京时间)→ UTC 2023-02-16T16:00:00Z + assertEquals("2023-02-16T16:00:00Z", row.afterSaleTime().utc().toString()); + // 行级 data_update_time 优先于订单级 gmt_modified + assertEquals("2023-02-17T08:54:14Z", row.updatedAt().utc().toString()); + } + + @Test + void mapsRefundRowWithAmounts() throws Exception { + AfterSale row = rows().get(1); + assertEquals(AfterSaleType.REFUND, row.type()); + // 币种取订单级 currency_code "$" → USD + assertEquals("USD", row.refundAmount().currencyCode()); + assertEquals("-4.700", row.refundAmount().amount().toPlainString()); + assertEquals("0.300", row.refundCost().amount().toPlainString()); + assertNotNull(row.attributes().get("refund_amount_details")); + assertNotNull(row.attributes().get("refund_cost_details")); + } + + @Test + void emptyRefundAmountBecomesNull() throws Exception { + // 第一个商品行 refund_amount 为空串 + assertNull(rows().get(0).refundAmount()); + assertNull(rows().get(0).refundCost()); + } + + @Test + void uniqueIdPrefersMd5V2() throws Exception { + assertEquals("e3e9ca874381650df28121eb1c74d8a1", rows().get(0).afterSaleId()); + assertEquals("a3f4403419630bb77076eac32bd6276c", rows().get(1).afterSaleId()); + } + + @Test + void typeMappingCoversChineseTags() throws Exception { + assertEquals(AfterSaleType.REFUND, LingxingAfterSaleMapper.typeOf("退款")); + assertEquals(AfterSaleType.RETURN, LingxingAfterSaleMapper.typeOf("退货")); + assertEquals(AfterSaleType.EXCHANGE, LingxingAfterSaleMapper.typeOf("换货")); + assertEquals(AfterSaleType.UNKNOWN, LingxingAfterSaleMapper.typeOf(null)); + } + + @Test + void currencySymbolsMapToIso() throws Exception { + assertEquals("USD", LingxingAfterSaleMapper.currencyOf("$")); + assertEquals("EUR", LingxingAfterSaleMapper.currencyOf("€")); + assertEquals("GBP", LingxingAfterSaleMapper.currencyOf("£")); + assertEquals("JPY", LingxingAfterSaleMapper.currencyOf("¥")); + assertEquals("CNY", LingxingAfterSaleMapper.currencyOf("CNY")); + assertNull(LingxingAfterSaleMapper.currencyOf("?")); + } + + @Test + void signedAmountIsCleaned() throws Exception { + assertEquals("-28.02", + LingxingAfterSaleMapper.moneyOrNull("-$28.0200", "USD").amount().stripTrailingZeros().toPlainString()); + assertNull(LingxingAfterSaleMapper.moneyOrNull("", "USD")); + assertNull(LingxingAfterSaleMapper.moneyOrNull("-$1.00", null), "币种不明时不构造金额"); + } + + @Test + void rowWithoutIdentifierFailsLoudly() throws Exception { + AfterSaleDto dto = new AfterSaleDto(); + common.ecommerce.lingxing.platform.aftersale.dto.AfterSaleItemDto item = + new common.ecommerce.lingxing.platform.aftersale.dto.AfterSaleItemDto(); + assertThrows(IllegalArgumentException.class, + () -> LingxingAfterSaleMapper.resolveAfterSaleId(dto, item)); + } +} diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/probe/SearchFieldProbeTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/probe/SearchFieldProbeTest.java new file mode 100644 index 0000000..d6e49b7 --- /dev/null +++ b/lingxing/src/test/java/common/ecommerce/lingxing/probe/SearchFieldProbeTest.java @@ -0,0 +1,254 @@ +package common.ecommerce.lingxing.probe; + +import common.ecommerce.http.HttpTransport; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.http.OkHttpTransport; +import common.ecommerce.lingxing.LingxingApi; +import common.ecommerce.lingxing.auth.LingxingTokenClient; +import common.ecommerce.lingxing.http.LingxingEnvelope; +import common.ecommerce.lingxing.http.LingxingRateLimiter; +import common.ecommerce.lingxing.http.LingxingRequestFactory; +import common.ecommerce.lingxing.platform.LingxingCall; +import common.ecommerce.model.ChannelProvider; +import common.ecommerce.model.Platform; +import common.ecommerce.model.account.AccountKey; +import common.ecommerce.model.account.ChannelAccount; +import common.ecommerce.sdk.ChannelConnection; +import common.ecommerce.sdk.ChannelContext; +import common.ecommerce.spi.AccessToken; +import common.ecommerce.spi.ChannelSecret; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 只读探针:实测各平台商品列表接口的 {@code searchField} 枚举值含义。 + * + *

只做查询,不创建、不修改任何数据。

+ * + *

用法:填好下面四个常量后运行

+ *
+ * mvn -pl lingxing test -Dtest=SearchFieldProbeTest -DfailIfNoTests=false
+ * 
+ * + *

输出会告诉你:对同一个 SKU 值,哪个 searchField 编码能命中; + * 命中时返回的是 {@code msku} 还是 {@code sku}。 + * 拿到结果后再去写正式的平台映射表。

+ */ +class SearchFieldProbeTest { + + // ==================== 填写这里 ==================== + private static final String APP_KEY = "ak_MWoHJz2tcIwKF"; + private static final String APP_SECRET = "YOUkd5efWJSK71jLvDyz+g=="; + + /** AliExpress 探针开关:该接口不需要店铺 id,只要 app 下有阿里商品就能查。 */ + private static final boolean PROBE_ALIEXPRESS = true; + + /** + * Target 店铺的 storeId。可选——文档里 store_ids 不是必填项, + * 不填就查该 app 下全部店铺的商品。 + */ + private static final String TARGET_STORE_ID = "110593321260223488"; + + /** AliExpress 的领星 platform_code(待实测确认;该码不影响商品接口调用)。 */ + private static final int ALIEXPRESS_PLATFORM_CODE = 0; + // ================================================ + + private static final String BASE_URL = "https://openapi.lingxing.com"; + private static final JacksonJsonCodec JSON = new JacksonJsonCodec(); + + private final HttpTransport transport = new OkHttpTransport("common-ecommerce-probe"); + + /** + * AliExpress 商品列表({@code AliexpressProductSource} 对应的接口)。 + * + *

文档里 1=msku、3=SKU、5=SKU 自相矛盾,逐个实测。 + * 该接口不需要店铺 id,一次返回 app 下全部阿里商品。

+ */ + @Test + void probeAliExpress() { + Assumptions.assumeTrue(PROBE_ALIEXPRESS, "PROBE_ALIEXPRESS=false,跳过"); + requireConfigured(); + + // platformCode 不影响商品接口调用,置 null 避免误导 + ChannelAccount account = account(Platform.ALIEXPRESS, 0, null); + LingxingCall call = call(account); + + // ① 先不带搜索拉两条,拿到真实的 msku / sku 做样本 + List> sample = queryAliExpress(call, new LinkedHashMap(), 2); + if (sample.isEmpty()) { + throw new AssertionError("店铺没有商品,无法做样本;换个有商品的 storeId"); + } + String sampleMsku = str(sample.get(0).get("msku")); + String sampleSku = str(sample.get(0).get("sku")); + System.out.println("[ali] 样本 msku=" + sampleMsku + " sku=" + sampleSku); + if (sampleMsku == null && sampleSku == null) { + throw new AssertionError("样本里 msku 和 sku 都为空,无法判断字段映射"); + } + + // ② 用 msku 和 sku 两个值,分别试 searchField = 1~7 + for (int field = 1; field <= 7; field++) { + int hitByMsku = countBySearch(call, field, sampleMsku, 10); + int hitBySku = countBySearch(call, field, sampleSku, 10); + System.out.println("[ali] searchField=" + field + + " 用msku查命中=" + hitByMsku + + " 用sku查命中=" + hitBySku); + } + } + + /** Target(领星路径 shopify):文档只写「integer 搜索维度」,没给枚举,1~9 全试。store_id 可选。 */ + @Test + void probeShopify() { + requireConfigured(); + + ChannelAccount account = account(Platform.TARGET, 0, TARGET_STORE_ID); + LingxingCall call = call(account); + + Map probe = new LinkedHashMap(); + List> sample = queryShopify(call, probe, 2); + if (sample.isEmpty()) { + throw new AssertionError("店铺没有商品,无法做样本;换个有商品的 store_id"); + } + String sampleMsku = str(sample.get(0).get("msku")); + String sampleSku = str(sample.get(0).get("local_sku")); + System.out.println("[target] 样本 msku=" + sampleMsku + " local_sku=" + sampleSku); + + for (int field = 1; field <= 9; field++) { + int hitByMsku = countBySearch(call, field, sampleMsku, 10, true); + int hitBySku = countBySearch(call, field, sampleSku, 10, true); + System.out.println("[target] search_field=" + field + + " 用msku查命中=" + hitByMsku + + " 用local_sku查命中=" + hitBySku); + } + } + + // ---------------------------------------------------------------- 查询实现 + + /** AliExpress 一页;searchField 为空表示不带搜索。 */ + @SuppressWarnings("unchecked") + private List> queryAliExpress(LingxingCall call, Map body, + int length, Integer searchField, String value) { + body.put("isParent", 0); // 子体维度,与 AliexpressProductSource 一致 + body.put("offset", 0); + body.put("length", length); + if (searchField != null) { + body.put("searchField", searchField); + body.put("searchSingleValue", value); + } + Map payload = new LinkedHashMap(body); + LingxingEnvelope env = execute(call, LingxingApi.LISTING_ALIEXPRESS, payload, "probe.ali"); + return toRows(JSON.listAt(env.body(), "data.list", java.util.LinkedHashMap.class)); + } + + private List> queryAliExpress(LingxingCall call, Map body, + int length) { + return queryAliExpress(call, body, length, null, null); + } + + private int countBySearch(LingxingCall call, int field, String value, int length) { + if (value == null || value.isEmpty()) { + return -1; + } + List> got = queryAliExpress(call, new LinkedHashMap(), + length, field, value); + return got.size(); + } + + @SuppressWarnings("unchecked") + private List> queryShopify(LingxingCall call, Map body, + int length, Integer searchField, String value) { + body.put("offset", 0); + body.put("length", length); + // store_ids 不是必填项;填了才按店铺过滤 + if (!TARGET_STORE_ID.trim().isEmpty()) { + body.put("store_ids", Collections.singletonList(TARGET_STORE_ID.trim())); + } + if (searchField != null) { + body.put("search_field", searchField); + body.put("search_single_value", value); + } + Map payload = new LinkedHashMap(body); + LingxingEnvelope env = execute(call, LingxingApi.LISTING_SHOPIFY, payload, "probe.shopify"); + return toRows(JSON.listAt(env.body(), "data.list", java.util.LinkedHashMap.class)); + } + + private List> queryShopify(LingxingCall call, Map body, + int length) { + return queryShopify(call, body, length, null, null); + } + + private int countBySearch(LingxingCall call, int field, String value, int length, boolean shopify) { + if (value == null || value.isEmpty()) { + return -1; + } + Map body = new LinkedHashMap(); + List> got = queryShopify(call, body, length, field, value); + return got.size(); + } + + /** List<LinkedHashMap> → List<Map<String,Object>>,避开泛型擦除。 */ + private static List> toRows(List raw) { + List> out = new ArrayList>(raw.size()); + for (Object o : raw) { + if (o instanceof Map) { + Map row = new LinkedHashMap(); + for (Map.Entry e : ((Map) o).entrySet()) { + row.put(String.valueOf(e.getKey()), e.getValue()); + } + out.add(row); + } + } + return out; + } + + private LingxingEnvelope execute(LingxingCall call, LingxingApi api, Map body, + String op) { + common.ecommerce.http.HttpRequest req = call.signed(api, body, op); + common.ecommerce.http.HttpResponse resp = call.execute(req); + return call.envelope(resp, op); + } + + // ---------------------------------------------------------------- 公共设施 + + private void requireConfigured() { + Assumptions.assumeTrue(!APP_KEY.startsWith("在这里填") && !APP_SECRET.startsWith("在这里填"), + "请先填写 APP_KEY / APP_SECRET"); + } + + private static void skipIfBlank(String value, String name) { + Assumptions.assumeTrue(value != null && !value.trim().isEmpty(), + "未填写 " + name + ",跳过该平台探针"); + } + + private ChannelAccount account(Platform platform, int platformCode, String storeId) { + return ChannelAccount.builder() + .key(AccountKey.of(ChannelProvider.LINGXING, platform, "oms-probe")) + .externalStoreId(storeId == null || storeId.trim().isEmpty() ? "probe" : storeId) + .platformCode(platformCode == 0 ? null : platformCode) + .credentialRef("probe") + .marketplaceZone("America/Los_Angeles") + .currency("USD") + .build(); + } + + private LingxingCall call(ChannelAccount account) { + Clock clock = Clock.systemUTC(); + ChannelSecret secret = ChannelSecret.builder().appKey(APP_KEY).appSecret(APP_SECRET).build(); + ChannelConnection conn = ChannelConnection.of(BASE_URL, secret); + ChannelContext ctx = ChannelContext.of(account, conn, "probe-" + System.currentTimeMillis(), clock); + AccessToken token = new LingxingTokenClient(transport, JSON, clock) + .fetch(BASE_URL, APP_KEY, APP_SECRET); + return new LingxingCall(ctx, token, new LingxingRequestFactory(JSON, clock), + new LingxingRateLimiter(), JSON, transport); + } + + private static String str(Object v) { + return v == null ? null : String.valueOf(v); + } +} diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/probe/ShopListProbeTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/probe/ShopListProbeTest.java new file mode 100644 index 0000000..a3091a9 --- /dev/null +++ b/lingxing/src/test/java/common/ecommerce/lingxing/probe/ShopListProbeTest.java @@ -0,0 +1,221 @@ +package common.ecommerce.lingxing.probe; + +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.lingxing.LingxingApi; +import common.ecommerce.lingxing.auth.LingxingTokenClient; +import common.ecommerce.lingxing.http.LingxingEnvelope; +import common.ecommerce.lingxing.http.LingxingRateLimiter; +import common.ecommerce.lingxing.http.LingxingRequestFactory; +import common.ecommerce.lingxing.platform.LingxingCall; +import common.ecommerce.model.ChannelProvider; +import common.ecommerce.model.Platform; +import common.ecommerce.model.account.AccountKey; +import common.ecommerce.model.account.ChannelAccount; +import common.ecommerce.sdk.ChannelConnection; +import common.ecommerce.sdk.ChannelContext; +import common.ecommerce.spi.AccessToken; +import common.ecommerce.spi.ChannelSecret; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * 只读探针:列出领星账户下所有店铺,并打印每个平台的 platform_code。 + * + *

用途:文档里没有 AliExpress 的 platform_code, + * 这个测试直接从店铺列表接口读出来。

+ * + *

只做查询,不创建、不修改数据。

+ * + *

用法:填好 APP_KEY / APP_SECRET,然后

+ *
+ * mvn -pl lingxing test -Dtest=ShopListProbeTest -DfailIfNoTests=false
+ * 
+ * + *

输出会按 platform_code 分组,形如:

+ *
+ * [shops] 共 12 家店
+ * [code] 10001  AMAZON_SC   2 家
+ *         - 1099xxx  店铺A
+ *         - 1099xxx  店铺B
+ * [code] 10003  EBAY        1 家
+ * ...
+ * 
+ */ +class ShopListProbeTest { + + // ==================== 填写这里 ==================== + private static final String APP_KEY = "ak_MWoHJz2tcIwKF"; + private static final String APP_SECRET = "YOUkd5efWJSK71jLvDyz+g=="; + + /** 可选:只查某个 platform_code 的店铺。留空查全部。 */ + private static final Integer ONLY_PLATFORM_CODE = null; + // ================================================ + + private static final String BASE_URL = "https://openapi.lingxing.com"; + private static final JacksonJsonCodec JSON = new JacksonJsonCodec(); + + /** 多平台店铺列表分页上限(LingxingConstants.MULTI_PLATFORM_MAX_PAGE_SIZE)。 */ + private static final int PAGE_SIZE = 200; + + private final HttpTransport transport = new OkHttpTransport("common-ecommerce-probe"); + + @Test + void listAllShops() { + requireConfigured(); + + // 这个接口不带平台维度,账户的 platformCode / externalStoreId 只是占位 + ChannelAccount placeholder = ChannelAccount.builder() + .key(AccountKey.of(ChannelProvider.LINGXING, Platform.CUSTOM, "oms-probe")) + .externalStoreId("probe") + .platformCode(ONLY_PLATFORM_CODE) + .credentialRef("probe") + .marketplaceZone("America/Los_Angeles") + .currency("USD") + .build(); + LingxingCall call = call(placeholder); + + List> shops = fetchAllShops(call); + System.out.println("[shops] 共 " + shops.size() + " 家店"); + + // 按 platform_code 分组,排序输出 + Map>> byCode = + new TreeMap>>(); + for (Map shop : shops) { + Integer code = toInt(shop.get("platform_code")); + if (code == null) { + continue; + } + List> group = byCode.get(code); + if (group == null) { + group = new ArrayList>(); + byCode.put(code, group); + } + group.add(shop); + } + + for (Map.Entry>> e : byCode.entrySet()) { + System.out.println("[code] " + e.getKey() + + " " + describePlatform(e.getKey()) + + " " + e.getValue().size() + " 家"); + for (Map shop : e.getValue()) { + System.out.println(" - " + shop.get("store_id") + + " " + shop.get("store_name")); + } + } + } + + // ---------------------------------------------------------------- 查询实现 + + private List> fetchAllShops(LingxingCall call) { + List> all = new ArrayList>(); + int offset = 0; + while (true) { + Map body = new LinkedHashMap(); + body.put("offset", offset); + body.put("length", PAGE_SIZE); + // 不过滤 is_sync / status:要把「授权异常」「暂停同步」的店也看到 + if (ONLY_PLATFORM_CODE != null) { + body.put("platform_code", Collections.singletonList(ONLY_PLATFORM_CODE)); + } + + HttpRequest req = call.signed(LingxingApi.SHOP_LIST_MULTI_PLATFORM, body, "probe.shops"); + HttpResponse resp = call.execute(req); + LingxingEnvelope env = call.envelope(resp, "probe.shops"); + + List> page = toRows( + JSON.listAt(env.body(), "data.list", java.util.LinkedHashMap.class)); + all.addAll(page); + + offset += page.size(); + boolean exhausted = page.size() < PAGE_SIZE + || (env.total() >= 0 && offset >= env.total()); + if (exhausted) { + break; + } + } + return all; + } + + /** List<LinkedHashMap> → List<Map<String,Object>>。 */ + private static List> toRows(List raw) { + List> out = new ArrayList>(raw.size()); + for (Object o : raw) { + if (o instanceof Map) { + Map row = new LinkedHashMap(); + for (Map.Entry e : ((Map) o).entrySet()) { + row.put(String.valueOf(e.getKey()), e.getValue()); + } + out.add(row); + } + } + return out; + } + + /** platform_code → 已知平台名;未登记时提示去补映射。 */ + private static String describePlatform(int code) { + switch (code) { + case 10001: + return "AMAZON_SC"; + case 10035: + return "AMAZON_VC"; + case 10008: + return "WALMART_SC"; + case 10011: + return "TIKTOK"; + case 10022: + case 10024: + return "TEMU"; + case 10003: + return "EBAY"; + case 10021: + case 10027: + case 10028: + return "SHEIN"; + case 10034: + return "MIRAKL"; + default: + return "未登记(需要补 LingxingConstants.toPlatform)"; + } + } + + // ---------------------------------------------------------------- 公共设施 + + private void requireConfigured() { + Assumptions.assumeTrue(!APP_KEY.startsWith("在这里填") && !APP_SECRET.startsWith("在这里填"), + "请先填写 APP_KEY / APP_SECRET"); + } + + private LingxingCall call(ChannelAccount account) { + Clock clock = Clock.systemUTC(); + ChannelSecret secret = ChannelSecret.builder().appKey(APP_KEY).appSecret(APP_SECRET).build(); + ChannelConnection conn = ChannelConnection.of(BASE_URL, secret); + ChannelContext ctx = ChannelContext.of(account, conn, "probe-" + System.currentTimeMillis(), clock); + AccessToken token = new LingxingTokenClient(transport, JSON, clock) + .fetch(BASE_URL, APP_KEY, APP_SECRET); + return new LingxingCall(ctx, token, new LingxingRequestFactory(JSON, clock), + new LingxingRateLimiter(), JSON, transport); + } + + private static Integer toInt(Object v) { + if (v == null) { + return null; + } + try { + return Integer.valueOf(String.valueOf(v).trim()); + } catch (NumberFormatException e) { + return null; + } + } +} diff --git a/lingxing/src/test/resources/fixtures/lingxing/afterSale/success.json b/lingxing/src/test/resources/fixtures/lingxing/afterSale/success.json new file mode 100644 index 0000000..933f2b9 --- /dev/null +++ b/lingxing/src/test/resources/fixtures/lingxing/afterSale/success.json @@ -0,0 +1,89 @@ +{ + "code": 0, + "message": "success", + "error_details": [], + "request_id": "TEST-REQ", + "response_time": "2023-02-18 17:12:37", + "data": [ + { + "id": 33, + "asin": "B09MT9BKAD", + "msku": "Pink_Head_Rope_12", + "amazon_order_id": "113-9870855-8214638", + "sid": 101, + "purchase_time": "2023-02-07 23:41:08", + "deal_time": "2023-02-16 23:50:50", + "gmt_modified": "2023-02-17 11:36:17", + "correlation_id": 3, + "interval_days": 10, + "is_mcf_order": 1, + "seller_country": "8p-US 美国", + "delivery_type": "FBM", + "order_total_amount": "$2.35", + "order_total_amount_currency_code": "$", + "order_total_amount_number": "2.35", + "total_refund_amount": "-$4.700", + "total_refund_amount_currency_code": "$", + "total_refund_amount__number": "-4.700", + "total_refund_cost": "$0.300", + "total_refund_cost_currency_code": "$", + "total_refund_cost_number": "0.300", + "after_type_tag": ["退款", "退货"], + "item_list": [ + { + "small_image_url": "https://xxxx/xxx.jpg", + "item_name": "Love Pearl Bottom Hair Circle", + "local_sku": "auto010", + "local_name": "自动010", + "asin": "B09MT9BKAD", + "asin_url": "https://www.amazon.com/dp/B09MT9BKAD", + "msku": "Pink_Head_Rope_12", + "after_type": "退货", + "after_time": "2023-02-17 00:00:00", + "data_update_time": "2023-02-17 16:54:14", + "after_interval": "10天", + "refund_amount": "", + "refund_cost": "", + "refund_currency_icon": "", + "after_quantity": 1, + "after_reason": "CR-ORDERED_WRONG_ITEM", + "return_status": "Approved", + "buyers_note": "自动化备注", + "rma_order_number": "D5LCqzJZRRMA", + "carriers": "USPS", + "waybill_number": "9202090153540168949151", + "exchange_order_number": "", + "md5_v2": "e3e9ca874381650df28121eb1c74d8a1" + }, + { + "small_image_url": "https://xxxx/xxx.jpg", + "item_name": "Love Pearl Bottom Hair Circle", + "local_sku": "auto010", + "local_name": "自动010", + "asin": "", + "msku": "Pink_Head_Rope_12", + "fid": "1PBCVYGW03FZY", + "after_type": "退款", + "after_time": "2023-02-16 23:50:50", + "data_update_time": "2023-02-17 11:36:17", + "after_interval": "10天", + "refund_amount": "-$4.700", + "refund_amount_details": [ + {"type": "Goodwill", "amount": "-$2.350"}, + {"type": "Principal", "amount": "-$2.000"} + ], + "refund_cost": "$0.300", + "refund_cost_details": [ + {"type": "Commission", "amount": "$0.260"} + ], + "after_quantity": 1, + "after_reason": "", + "return_status": "", + "md5_v2": "a3f4403419630bb77076eac32bd6276c", + "row_index": 11 + } + ] + } + ], + "total": 1 +}