From 20d6bbe975078eb86fd1bc4f5bc846686604fa1e Mon Sep 17 00:00:00 2001 From: chenchuchuan <13554600537@163.com> Date: Mon, 2 Nov 2026 16:57:57 +0800 Subject: [PATCH] =?UTF-8?q?refactor(lingxing):=20=E6=90=AD=E5=AD=90?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=88=86=E6=B4=BE=E9=AA=A8=E6=9E=B6=EF=BC=8C?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=85=A8=E9=83=A8=E5=81=87=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 结构: - 新增 LingxingApi 枚举:路径 + 限流,一条路径只写一次 - 新增 platform/ 包:LingxingSubPlatform 接口、LingxingSubPlatforms 注册表、 LingxingCall 调用上下文、walmart/WalmartSubPlatform 首个实现 - LingxingAdapter.pull 改为按 Platform 分派,supports 委托子平台 删除假数据: - LingxingApi 里凭空猜测的 SHOP_LIST_* / PRODUCT_LIST_* 路径 - LingxingAdapter.listSubChannels 由账户拼出的假子渠道,改为显式抛异常 - LingxingConstants 中与 LingxingApi 重复的路径与限流常量 - README / GUIDE 中已删除的 FakeTransport、Fixtures 相关内容 Co-Authored-By: Claude --- GUIDE.md | 79 +++------------ README.md | 14 +-- .../common/ecommerce/lingxing/LingxingApi.java | 42 ++++++++ .../ecommerce/lingxing/LingxingConstants.java | 14 +-- .../lingxing/adapter/LingxingAdapter.java | 77 ++++----------- .../lingxing/auth/LingxingTokenClient.java | 3 +- .../ecommerce/lingxing/platform/LingxingCall.java | 70 +++++++++++++ .../lingxing/platform/LingxingSubPlatform.java | 56 +++++++++++ .../lingxing/platform/LingxingSubPlatforms.java | 69 +++++++++++++ .../platform/walmart/WalmartSubPlatform.java | 108 +++++++++++++++++++++ 10 files changed, 390 insertions(+), 142 deletions(-) create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingCall.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatforms.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/platform/walmart/WalmartSubPlatform.java diff --git a/GUIDE.md b/GUIDE.md index 8c1bd09..d380f6e 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -770,80 +770,33 @@ assertEquals(md5Hex("secretapp_keyk1"), AcmeSigner.sign(params, "secret")); 时间相关的用 DST 边界:2026-03-08 美国太平洋时区进入夏令时,前后各测一次。 -### 第 2 层:契约测试(主力,不碰网络) +### 第 2 层:真实环境冒烟(主力) -这是整个项目最核心的测试方式。**不用 Mockito,不用 WireMock**:`FakeTransport` 按 URL 子串直接返回磁盘上的录制 JSON。 +当前只保留真实环境冒烟(`LingxingLiveSmokeTest`),不再使用录制报文。 -夹具路径约定: - -``` -acme/src/test/resources/fixtures/acme/orderList/success.json -acme/src/test/resources/fixtures/acme/orderList/page2.json -acme/src/test/resources/fixtures/acme/orderList/empty.json -acme/src/test/resources/fixtures/acme/token/success.json -``` - -读法: +做法:在测试类顶部写常量(本地联调时填真实值,不提交),用真实的 +`OkHttpTransport` 直接打平台接口;未填常量时用 `Assumptions` 跳过, +避免占位串打到线上。 ```java -String orderJson = Fixtures.load(AcmeAdapterTest.class, "acme", "orderList", "success"); -``` +class AcmeLiveSmokeTest { -测试骨架: + private static final String APP_KEY = "在这里填 AppID"; + private static final String APP_SECRET = "在这里填 AppSecret"; -```java -class AcmeAdapterTest { - - private FakeTransport transport; - private AcmeAdapter adapter; - private ChannelContext ctx; - - @BeforeEach - void setUp() { - transport = FakeTransport.create(); - transport.route(AcmeConstants.PATH_TOKEN, "POST", r -> Responses.ok(tokenJson)); - transport.route(AcmeConstants.PATH_ORDERS, "POST", r -> Responses.ok(orderJson)); - - Clock clock = Clock.fixed(Instant.parse("2026-10-29T00:00:00Z"), ZoneOffset.UTC); - adapter = new AcmeAdapter(BASE_URL, transport, new JacksonJsonCodec(), - accounts, tokenStore, locks, clock); - ctx = ChannelContext.of(account, "req-1", clock); - } + private final HttpTransport transport = new OkHttpTransport("common-ecommerce-smoke"); @Test - void requestIsBuiltCorrectly() { - adapter.pull(ctx, query); - - HttpRequest last = transport.lastRequest(); - assertTrue(last.url().contains("sign=")); - assertEquals("Bearer acme-token", last.headers().get("Authorization")); - assertEquals("req-1", last.headers().get("X-Request-Id")); - assertTrue(last.body().contains("\"page_size\":100")); - assertTrue(last.body().contains("\"store_id\":\"store-1\"")); - } - - @Test - void responseIsParsedCorrectly() { - Page page = adapter.pull(ctx, query); - - assertEquals(3, page.size()); - assertEquals("ACME-1001", page.items().get(0).channelOrderId()); - assertNull(page.nextCursor()); // total 已到,应该结束 + void tokenCanBeFetched() { + AccessToken token = new AcmeTokenClient(transport, json, Clock.systemUTC()) + .fetch(BASE_URL, APP_KEY, APP_SECRET); + assertNotNull(token.value()); } } ``` -**为什么拆成「请求对不对」和「解析对不对」两个测试?** -出问题时:请求错 → 平台报错但看不到为什么;解析错 → 请求成功但字段全是 null。分开测,一眼定位。 - -**必测的错误路径**(各一个夹具 + 一个断言): - -| 夹具 | 断言 | -|:---|:---| -| `401.json` | `AuthException` | -| `429.json`(带 `Retry-After: 3`) | `RateLimitException.retryAfterMillis() == 3000` | -| `500.json` | `TransientException.retryable() == true` | -| `400.json` | `ValidationException` | +联调时把请求和响应打出来(token 打码),签名或字段名不对时靠日志定位。 +**凭证不要提交到仓库**,联调完重置。 ### 第 3 层:分页与水位线 @@ -958,7 +911,7 @@ class AcmeLiveSmokeTest { |:---|:---| | core | 模型、能力接口、门面、SyncEngine、幂等守卫、SPI 全部可用 | | http | OkHttp 传输、Jackson 编解码、签名接口、TokenManager 模板可用 | -| testkit | FakeTransport、InMemory SPI、FakeDirectAdapter、MutableClock、夹具加载可用 | +| testkit | InMemory SPI、FakeDirectAdapter、MutableClock 可用 | | lingxing | 订单列表拉取可用;商品、履约、面单、账单、售后未实现 | | 其它平台 | 未开始 | diff --git a/README.md b/README.md index f80fdbd..2fa5895 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ |:---|:---| | `common-ecommerce-core` | 领域模型、能力接口、门面、管道、SPI。**零第三方运行时依赖** | | `common-ecommerce-http` | HTTP 传输、签名、令牌管理、JSON 编解码 | -| `common-ecommerce-testkit` | InMemory SPI、FakeTransport、夹具加载、断言工具 | +| `common-ecommerce-testkit` | InMemory SPI 与测试替身 | | `common-ecommerce-lingxing` | 领星聚合适配器(多子平台)。DTO 用 Lombok 生成访问器 | **Lombok 使用范围**:仅 `lingxing` 模块的 `dto/*`,`scope=provided`,不进宿主运行时。 @@ -175,7 +175,7 @@ common.ecommerce | 类 | 职责 | |:---|:---| -| `HttpTransport` | 传输接口,默认 `OkHttpTransport`(连接 5s / 读 30s),测试用 `FakeTransport` | +| `HttpTransport` | 传输接口,默认 `OkHttpTransport`(连接 5s / 读 30s) | | `HttpRequest` / `HttpResponse` | 统一请求响应,保留原始 header/body 供留痕 | | `JsonCodec` | JSON 抽象,`JacksonJsonCodec` 提供点路径取值 `nodeAt("data.list")` | | `Signer` | 签名接口,各平台实现 | @@ -186,13 +186,11 @@ common.ecommerce | 类 | 职责 | |:---|:---| -| `FakeTransport` | 按 URL 子串 + 方法路由,直接返回录制响应,记录全部请求 | | `FakeDirectAdapter` | 直连假适配器:游标分页、能力并集即账户能力、记录写调用 | | `InMemoryAccounts` | 内存版账户仓库 + 密钥提供者 | | `InMemoryTokenStore` / `InMemoryCursorStore` / `InMemorySink` / `InMemoryLockProvider` / `InMemoryIdempotencyStore` | 全套内存 SPI | | `MutableClock` | 可推进时钟,验证 TTL / 续期 / 水位线边界 | -| `Fixtures` | 夹具加载,约定 `fixtures/{platform}/{operation}/{case}.json` | -| `Responses` / `TestData` | 响应与同步测试的快捷构造 | +| `TestData` | 同步测试的快捷构造 | ### `lingxing` —— 领星适配器 @@ -519,7 +517,7 @@ public final class MyAggregatorAdapter implements SalesOrderCapable, AggregatorC |:---|:---|:---| | 单元测试 | 签名、canonicalKey、时间三轴/DST、错误映射 | 纯计算,毫秒级 | | **契约测试**(核心) | 请求是否构造对、响应是否解析对 | 录制夹具 | -| 集成测试 | 重试、限流、401 刷新 | `FakeTransport` | +| 集成测试 | 重试、限流、401 刷新 | 真实环境冒烟(`LingxingLiveSmokeTest`) | | 沙箱联调 | 端到端 | 手动,不进 CI | 适配器测试**不依赖网络、数据库、Spring**。 @@ -537,9 +535,7 @@ src/test/resources/fixtures/{platform}/{operation}/{case}.json ### 写法 ```java -FakeTransport transport = FakeTransport.create() - .route(LingxingConstants.PATH_ACCESS_TOKEN, "POST", r -> Responses.ok(tokenJson)) - .route(LingxingConstants.PATH_ORDER_LIST, "POST", r -> Responses.ok(orderJson)); +// 联调直接用真实接口,见 LingxingLiveSmokeTest LingxingAdapter adapter = new LingxingAdapter(LingxingConstants.DEFAULT_BASE_URL, transport, new JacksonJsonCodec(), accounts, tokenStore, locks, diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java new file mode 100644 index 0000000..ed3aaa2 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java @@ -0,0 +1,42 @@ +package common.ecommerce.lingxing; + +/** + * 领星开放接口目录:路径 + 限流值。 + * + *

一条路径只写一次。子平台通过 {@code LingxingSubPlatforms} 引用需要的条目, + * 不在平台枚举里重复写字符串。

+ * + *

路径按领星侧的子平台分组(如 {@code /pb/mp/amazon/...} 与 {@code /pb/mp/walmart/...}), + * 若某天两个子平台共用一个路径,让两个平台引用同一个枚举值即可,不必新增条目。

+ * + *

名字里的 AMAZON / WALMART 指领星侧的子平台,与业务枚举 {@code Platform} 的对应关系 + * 见 {@code LingxingSubPlatforms}。

+ */ +public enum LingxingApi { + + /** 换取令牌;所有子平台共用。 */ + TOKEN("/api/auth-server/oauth/access-token", 100), + + // 店铺列表、商品列表的路径尚未核对,不预置占位值; + // 拿到官方文档后在此追加,一条路径只写一次。 + + /** 多平台订单列表;当前实现使用的跨平台接口。 */ + ORDER_LIST("/pb/mp/order/v2/list", 10); + + private final String path; + private final int permitsPerSecond; + + LingxingApi(String path, int permitsPerSecond) { + this.path = path; + this.permitsPerSecond = permitsPerSecond; + } + + public String path() { + return path; + } + + /** 该接口的令牌桶容量(req/s),限流器按 path 维度使用。 */ + public int permitsPerSecond() { + return permitsPerSecond; + } +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java index 3ed001d..2445161 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java @@ -19,19 +19,11 @@ public final class LingxingConstants { public static final String ADAPTER_ID = "lingxing"; - /** 获取令牌。 */ - public static final String PATH_ACCESS_TOKEN = "/api/auth-server/oauth/access-token"; - /** 多平台订单列表(各平台自发货)。 */ - public static final String PATH_ORDER_LIST = "/pb/mp/order/v2/list"; - /** 店铺列表。 */ - public static final String PATH_SELLER_LIST = "/pb/mp/shop/v2/getSellerList"; + // 接口路径与限流值统一放在 LingxingApi 枚举里,这里不再重复。 - /** 多平台订单列表令牌桶:10 req/s(亚马逊/VC/Walmart 接口是 1 req/s)。 */ - public static final int ORDER_LIST_PER_SECOND = 10; - - /** 订单查询时间跨度上限:31 天。 */ + /** 订单查询时间跨度上限:31 天(领星统一订单接口的限制)。 */ public static final int MAX_QUERY_DAYS = 31; - /** 分页 length 上限。 */ + /** 分页 length 上限(领星统一订单接口的限制)。 */ public static final int MAX_PAGE_SIZE = 500; private LingxingConstants() { 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 f853883..bf778c0 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java @@ -1,18 +1,16 @@ package common.ecommerce.lingxing.adapter; import common.ecommerce.lingxing.LingxingConstants; -import common.ecommerce.lingxing.http.LingxingEnvelope; -import common.ecommerce.lingxing.dto.LingxingOrderDto; import common.ecommerce.lingxing.mapper.LingxingOrderMapper; import common.ecommerce.lingxing.http.LingxingRateLimiter; import common.ecommerce.lingxing.http.LingxingRequestFactory; import common.ecommerce.lingxing.auth.LingxingTokenClient; +import common.ecommerce.lingxing.platform.LingxingCall; +import common.ecommerce.lingxing.platform.LingxingSubPlatforms; import common.ecommerce.capability.AggregatorCapable; import common.ecommerce.capability.SalesOrderCapable; import common.ecommerce.error.ChannelException; -import common.ecommerce.error.ValidationException; import common.ecommerce.http.HttpRequest; -import common.ecommerce.http.HttpResponse; import common.ecommerce.http.HttpTransport; import common.ecommerce.http.JacksonJsonCodec; import common.ecommerce.http.TokenManager; @@ -112,69 +110,32 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab return false; } Platform p = LingxingConstants.toPlatform(account.platformCode()); - if (p == Platform.EBAY || p == Platform.SHEIN || p == Platform.MIRAKL || p == Platform.CUSTOM) { - return capability == Capability.SALES_ORDER; - } - return true; + return LingxingSubPlatforms.isRegistered(p) && LingxingSubPlatforms.of(p).supports(capability); } + /** + * 店铺(子渠道)列表尚未接入:当前签名拿不到 {@code ChannelConnection}, + * 无法调用领星接口。改为显式失败,不再返回由账户拼出来的假子渠道。 + */ @Override public List listSubChannels(ChannelAccount account) { - // 首期一个账户对应一个子渠道;店铺列表接口待接入 - SubChannel ch = new SubChannel( - account.platformCode() == null ? 0 : account.platformCode(), - account.externalStoreId(), - LingxingConstants.toPlatform(account.platformCode()), - account.externalStoreId()); - return Collections.singletonList(ch); + throw ChannelException.builder() + .message("lingxing shop list is not implemented yet") + .operation("listSubChannels") + .provider(provider().name()) + .omsStoreId(account.omsStoreId()) + .platform(LingxingConstants.toPlatform(account.platformCode())) + .retryable(false) + .build(); } @Override public Page pull(ChannelContext ctx, SalesOrderQuery query) { requireCapability(); - ChannelAccount account = ctx.account(); - ZoneId zone = ZoneId.of(account.marketplaceZone()); - - Instant from = query.updatedAfter(); - Instant to = query.updatedBefore() != null ? query.updatedBefore() : Instant.now(clock); - // 领星时间窗 ≤31 天:超出时截断到最近 31 天,由 SyncEngine 分段推进 - if (Duration.between(from, to).toDays() > LingxingConstants.MAX_QUERY_DAYS) { - from = to.minus(Duration.ofDays(LingxingConstants.MAX_QUERY_DAYS)); - } - - int length = Math.min(query.pageSize() <= 0 ? 100 : query.pageSize(), LingxingConstants.MAX_PAGE_SIZE); - int offset = query.cursor() == null ? 0 : Integer.parseInt(query.cursor()); - Map body = buildOrderListBody(account, from, to, offset, length); - - rateLimiter.acquire(LingxingConstants.PATH_ORDER_LIST, LingxingConstants.ORDER_LIST_PER_SECOND); - HttpRequest req = signedRequest(ctx, LingxingConstants.PATH_ORDER_LIST, body, "salesOrders.pull"); - HttpResponse resp = transport.execute(req); - - LingxingEnvelope envelope = LingxingEnvelope.of(resp, json, "salesOrders.pull", - ctx.omsStoreId(), ctx.requestId()); - - List dtos = mapper.parseList(envelope.body()); - List orders = new ArrayList(dtos.size()); - for (LingxingOrderDto dto : dtos) { - try { - orders.add(mapper.toSalesOrder(dto, account.omsStoreId(), zone)); - } catch (RuntimeException e) { - // 映射失败保留原始报文,交给人工修映射;不要让它以 NPE 形式冒出去 - throw new ValidationException(ChannelException.builder() - .message("lingxing order mapping failed: " + e.getMessage()) - .operation("salesOrders.pull") - .provider(provider().name()) - .omsStoreId(ctx.omsStoreId()) - .requestId(ctx.requestId()) - .rawResponse(envelope.body()), e); - } - } - - // 满页才可能有下一页;total 存在时再用它兜底,避免最后一页多发一次请求 - int nextOffset = offset + dtos.size(); - boolean hasMore = dtos.size() >= length - && (envelope.total() < 0 || nextOffset < envelope.total()); - return Page.of(orders, hasMore ? String.valueOf(nextOffset) : null); + ChannelSecret secret = ctx.secret(); + AccessToken token = tokenManager.getOrRefresh(tokenKey(secret), secret); + LingxingCall call = new LingxingCall(ctx, token, requestFactory, rateLimiter, json); + return LingxingSubPlatforms.of(ctx.platform()).orders(call, query); } /** 单订单详情接口待核对(领星以列表接口为主),先显式拒绝而不是返回 null。 */ diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/auth/LingxingTokenClient.java b/lingxing/src/main/java/common/ecommerce/lingxing/auth/LingxingTokenClient.java index 6246ade..c3bc1ca 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/auth/LingxingTokenClient.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/auth/LingxingTokenClient.java @@ -1,4 +1,5 @@ package common.ecommerce.lingxing.auth; +import common.ecommerce.lingxing.LingxingApi; import common.ecommerce.lingxing.LingxingConstants; import common.ecommerce.error.AuthException; @@ -54,7 +55,7 @@ public final class LingxingTokenClient { HttpRequest req = HttpRequest.builder() .method("POST") - .url(trimTrailingSlash(baseUrl) + LingxingConstants.PATH_ACCESS_TOKEN) + .url(trimTrailingSlash(baseUrl) + LingxingApi.TOKEN.path()) .contentType(MULTIPART_CONTENT_TYPE) .body(multipartBody(form)) .operation("token.refresh") diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingCall.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingCall.java new file mode 100644 index 0000000..2d5b4d8 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingCall.java @@ -0,0 +1,70 @@ +package common.ecommerce.lingxing.platform; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.HttpResponse; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.lingxing.LingxingApi; +import common.ecommerce.lingxing.http.LingxingEnvelope; +import common.ecommerce.lingxing.http.LingxingRateLimiter; +import common.ecommerce.lingxing.http.LingxingRequestFactory; +import common.ecommerce.sdk.ChannelContext; +import common.ecommerce.spi.AccessToken; +import common.ecommerce.spi.ChannelSecret; + +import java.util.Map; + +/** + * 一次调用所需的公共设施,交给子平台实现使用。 + * + *

把「取 token、限流、签名、校验信封」这些每个子平台都要做的事收在一处, + * 子平台实现只需要关心拼请求体和解析响应。

+ */ +public final class LingxingCall { + + private final ChannelContext ctx; + private final AccessToken token; + private final LingxingRequestFactory requestFactory; + private final LingxingRateLimiter rateLimiter; + private final JacksonJsonCodec json; + + public LingxingCall(ChannelContext ctx, AccessToken token, LingxingRequestFactory requestFactory, + LingxingRateLimiter rateLimiter, JacksonJsonCodec json) { + this.ctx = ctx; + this.token = token; + this.requestFactory = requestFactory; + this.rateLimiter = rateLimiter; + this.json = json; + } + + public ChannelContext ctx() { + return ctx; + } + + public ChannelSecret secret() { + return ctx.secret(); + } + + public AccessToken token() { + return token; + } + + public JacksonJsonCodec json() { + return json; + } + + /** 按接口自己的令牌桶限流,然后构造已签名的请求。 */ + public HttpRequest signed(LingxingApi api, Map body, String operation) { + rateLimiter.acquire(api.path(), api.permitsPerSecond()); + return requestFactory.post(ctx.endpointBaseUrl(), api.path(), body, ctx.secret(), token, ctx, operation); + } + + /** 校验 HTTP 状态与业务码,返回原始 body 供子平台解析。 */ + public String body(HttpResponse response, String operation) { + return LingxingEnvelope.of(response, json, operation, ctx.omsStoreId(), ctx.requestId()).body(); + } + + /** 同上,同时给出 data.total;接口没有 total 时为负数。 */ + public LingxingEnvelope envelope(HttpResponse response, String operation) { + return LingxingEnvelope.of(response, json, operation, ctx.omsStoreId(), ctx.requestId()); + } +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java new file mode 100644 index 0000000..b7c3621 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java @@ -0,0 +1,56 @@ +package common.ecommerce.lingxing.platform; + +import common.ecommerce.capability.AggregatorCapable; +import common.ecommerce.model.Capability; +import common.ecommerce.model.Platform; +import common.ecommerce.model.order.SalesOrder; +import common.ecommerce.model.order.SalesOrderQuery; +import common.ecommerce.model.product.ProductListing; +import common.ecommerce.model.product.ProductQuery; +import common.ecommerce.model.support.Page; + +import java.util.List; + +/** + * 领星侧的一个子平台(亚马逊、沃尔玛、eBay……)。 + * + *

同一个聚合器下各子平台的接口路径、请求体、响应字段都不同,差异全部收敛到实现里; + * {@code LingxingAdapter} 只做分派。

+ * + *

不支持的能力不覆写即可,默认实现直接抛 + * {@code ChannelException.UnsupportedCapabilityException}——不静默返回空。

+ */ +public interface LingxingSubPlatform { + + /** 对应的业务平台,用于注册表与日志。 */ + Platform platform(); + + /** 这个子平台实际支持哪些能力;{@code LingxingAdapter.supports} 据此细化。 */ + boolean supports(Capability capability); + + /** 销售订单分页拉取。 */ + default Page orders(LingxingCall call, SalesOrderQuery query) { + throw unsupported(Capability.SALES_ORDER); + } + + /** 单订单详情。 */ + default SalesOrder order(LingxingCall call, String channelOrderId) { + throw unsupported(Capability.SALES_ORDER); + } + + /** 商品 / Listing 分页拉取。 */ + default Page products(LingxingCall call, ProductQuery query) { + throw unsupported(Capability.PRODUCT); + } + + /** 店铺(子渠道)列表。 */ + default List shops(LingxingCall call) { + throw unsupported(Capability.SALES_ORDER); + } + + /** 缺失能力的统一异常,避免各实现各写一遍。 */ + static common.ecommerce.error.ChannelException.UnsupportedCapabilityException unsupported( + Capability capability) { + return new common.ecommerce.error.ChannelException.UnsupportedCapabilityException(capability); + } +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatforms.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatforms.java new file mode 100644 index 0000000..58ecdb3 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatforms.java @@ -0,0 +1,69 @@ +package common.ecommerce.lingxing.platform; + +import common.ecommerce.error.ChannelException; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.http.OkHttpTransport; +import common.ecommerce.model.Platform; +import common.ecommerce.lingxing.platform.walmart.WalmartSubPlatform; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.Map; +import java.util.Set; + +/** + * 子平台注册表:业务平台 → 领星侧实现。 + * + *

新增一个子平台 = 写一个 {@link LingxingSubPlatform} 实现 + 在这里登记一行。 + * 未登记的平台在调用时显式失败,不静默返回空。

+ */ +public final class LingxingSubPlatforms { + + private static final Map BY_PLATFORM; + + /** + * 子平台实现共享同一套传输与编解码;端点与凭据不在这里,随每次调用传入。 + */ + private static final OkHttpTransport SHARED_TRANSPORT = new OkHttpTransport("common-ecommerce/1.0.0 (lingxing)"); + private static final JacksonJsonCodec SHARED_JSON = new JacksonJsonCodec(); + + static { + Map map = new EnumMap(Platform.class); + register(map, new WalmartSubPlatform(SHARED_TRANSPORT, SHARED_JSON)); + // 亚马逊、eBay、SHEIN… 落地后继续 register(...) + BY_PLATFORM = Collections.unmodifiableMap(map); + } + + private static void register(Map map, LingxingSubPlatform impl) { + map.put(impl.platform(), impl); + } + + private LingxingSubPlatforms() { + } + + /** + * 按业务平台取实现;未登记时抛带平台信息的异常,便于定位是哪个子平台还没接。 + */ + public static LingxingSubPlatform of(Platform platform) { + LingxingSubPlatform impl = BY_PLATFORM.get(platform); + if (impl == null) { + throw ChannelException.builder() + .message("lingxing sub platform not implemented: " + platform) + .operation("subPlatform.resolve") + .provider("lingxing") + .platform(platform) + .retryable(false) + .build(); + } + return impl; + } + + public static boolean isRegistered(Platform platform) { + return BY_PLATFORM.containsKey(platform); + } + + /** 已登记的平台,便于能力报告与日志。 */ + public static Set registered() { + return BY_PLATFORM.keySet(); + } +} diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/platform/walmart/WalmartSubPlatform.java b/lingxing/src/main/java/common/ecommerce/lingxing/platform/walmart/WalmartSubPlatform.java new file mode 100644 index 0000000..c441415 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/platform/walmart/WalmartSubPlatform.java @@ -0,0 +1,108 @@ +package common.ecommerce.lingxing.platform.walmart; + +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.LingxingConstants; +import common.ecommerce.lingxing.dto.LingxingOrderDto; +import common.ecommerce.lingxing.http.LingxingEnvelope; +import common.ecommerce.lingxing.mapper.LingxingOrderMapper; +import common.ecommerce.lingxing.platform.LingxingCall; +import common.ecommerce.lingxing.platform.LingxingSubPlatform; +import common.ecommerce.model.Capability; +import common.ecommerce.model.Platform; +import common.ecommerce.model.account.ChannelAccount; +import common.ecommerce.model.order.SalesOrder; +import common.ecommerce.model.order.SalesOrderQuery; +import common.ecommerce.model.support.Page; + +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 领星 · 沃尔玛子平台。 + * + *

当前复用领星跨平台的订单列表接口 {@link LingxingApi#ORDER_LIST}; + * 沃尔玛若确认为独立订单接口,只需把 {@link #orderApi()} 换成对应枚举值。

+ */ +public final class WalmartSubPlatform implements LingxingSubPlatform { + + private final HttpTransport transport; + private final LingxingOrderMapper mapper; + + public WalmartSubPlatform(HttpTransport transport, JacksonJsonCodec json) { + this.transport = transport; + this.mapper = new LingxingOrderMapper(json); + } + + /** 该子平台使用的订单接口;当前为领星统一接口。 */ + protected LingxingApi orderApi() { + return LingxingApi.ORDER_LIST; + } + + @Override + public Platform platform() { + return Platform.WALMART_SC; + } + + @Override + public boolean supports(Capability capability) { + return capability == Capability.SALES_ORDER; + } + + @Override + public Page orders(LingxingCall call, SalesOrderQuery query) { + ChannelAccount account = call.ctx().account(); + ZoneId zone = ZoneId.of(account.marketplaceZone()); + + Instant from = query.updatedAfter(); + Instant to = query.updatedBefore() != null ? query.updatedBefore() : Instant.now(call.ctx().clock()); + if (Duration.between(from, to).toDays() > LingxingConstants.MAX_QUERY_DAYS) { + from = to.minus(Duration.ofDays(LingxingConstants.MAX_QUERY_DAYS)); + } + + int length = Math.min(query.pageSize() <= 0 ? 100 : query.pageSize(), LingxingConstants.MAX_PAGE_SIZE); + int offset = query.cursor() == null ? 0 : Integer.parseInt(query.cursor()); + Map body = orderBody(account, from, to, offset, length); + + HttpRequest req = call.signed(orderApi(), body, "salesOrders.pull"); + HttpResponse resp = transport.execute(req); + LingxingEnvelope envelope = call.envelope(resp, "salesOrders.pull"); + + List dtos = mapper.parseList(envelope.body()); + List orders = new ArrayList(dtos.size()); + for (LingxingOrderDto dto : dtos) { + orders.add(mapper.toSalesOrder(dto, account.omsStoreId(), zone)); + } + + int nextOffset = offset + dtos.size(); + boolean hasMore = dtos.size() >= length + && (envelope.total() < 0 || nextOffset < envelope.total()); + return Page.of(orders, hasMore ? String.valueOf(nextOffset) : null); + } + + private Map orderBody(ChannelAccount account, Instant from, Instant to, + int offset, int length) { + Map body = new LinkedHashMap(); + body.put("offset", offset); + body.put("length", length); + body.put("date_type", "update_time"); + body.put("start_time", from.getEpochSecond()); + body.put("end_time", to.getEpochSecond()); + if (account.platformCode() != null) { + body.put("platform_code", Collections.singletonList(account.platformCode())); + } + if (account.externalStoreId() != null) { + body.put("store_id", Collections.singletonList(account.externalStoreId())); + } + return body; + } +}