Browse Source

feat(lingxing): 接入亚马逊订单、FBM 与结算交易明细

- 亚马逊 SC 标准订单:platform_code=10001 走 /erp/sc/data/mws/orders,
  date_type=3(平台更新时间 UTC),窗口 ≤1 年,分页 ≤5000,1 req/s
- 亚马逊订单详情:/erp/sc/data/mws/orderDetail,返回单价/税额/折扣;
  get() 按子平台分派,不再统一抛未实现
- 亚马逊店铺列表:GET /erp/sc/data/seller/lists,
  返回的 sid 可直接作为 externalStoreId
- 亚马逊 FBM:getOrderList/getOrderDetail 单独成一路,主键是领星系统单号
  order_number,列表 page 从 1 开始,详情 data 是对象
- 结算交易明细:新增 SettlementCapable / Settlements 门面与结算模型,
  接口 /bd/sp/api/open/settlement/transaction/detail/list,
  结算窗口 ≤7 天,修改时间按北京时间
- LingxingSubPlatform 增加 fbmOrderSource / settlementSource
- LingxingApi 统一登记接口路径与令牌桶
- 金额清洗复用 LingxingOrderMapper.cleanAmount
- smoke 测试覆盖店铺 → 订单 → 详情 → FBM → 结算链路

说明:
- FBM purchase_time 文档未标时区,暂按北京时间解析,待真实报文核对
- 结算 eventType=ServiceFeeEventList 时 uniqueKey 会变,需先删后写
feature/supplier-lingxing
lml 3 weeks ago
parent
commit
4f7f9c88a5
  1. 17
      core/src/main/java/common/ecommerce/capability/SettlementCapable.java
  2. 36
      core/src/main/java/common/ecommerce/capability/Settlements.java
  3. 183
      core/src/main/java/common/ecommerce/model/settlement/SettlementQuery.java
  4. 281
      core/src/main/java/common/ecommerce/model/settlement/SettlementTransaction.java
  5. 7
      core/src/main/java/common/ecommerce/sdk/ChannelSdk.java
  6. 23
      lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java
  7. 29
      lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java
  8. 130
      lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java
  9. 3
      lingxing/src/main/java/common/ecommerce/lingxing/http/LingxingRequestFactory.java
  10. 4
      lingxing/src/main/java/common/ecommerce/lingxing/mapper/LingxingOrderMapper.java
  11. 46
      lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java
  12. 25
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/AmazonScSubPlatform.java
  13. 6
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/AmazonShopSource.java
  14. 77
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderDetailDto.java
  15. 72
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderDetailItemDto.java
  16. 100
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderDto.java
  17. 38
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderItemDto.java
  18. 134
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonSettlementTransactionDto.java
  19. 111
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/FbmOrderDetailDto.java
  20. 66
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/FbmOrderDto.java
  21. 55
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/FbmOrderItemDto.java
  22. 298
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/order/AmazonFbmOrderSource.java
  23. 370
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/order/AmazonOrderSource.java
  24. 259
      lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/settlement/AmazonSettlementSource.java
  25. 18
      lingxing/src/main/java/common/ecommerce/lingxing/platform/settlement/LingxingSettlementSource.java
  26. 216
      lingxing/src/test/java/common/ecommerce/lingxing/adapter/LingxingLiveSmokeTest.java

17
core/src/main/java/common/ecommerce/capability/SettlementCapable.java

@ -0,0 +1,17 @@ @@ -0,0 +1,17 @@
package common.ecommerce.capability;
import common.ecommerce.model.settlement.SettlementQuery;
import common.ecommerce.model.settlement.SettlementTransaction;
import common.ecommerce.model.support.Page;
import common.ecommerce.sdk.ChannelContext;
/**
* 结算 / 账单能力:拉取平台结算交易明细。
*
* <p>一行代表一笔费用(佣金、配送费、退款、广告费等),平台可能按
* 结算周期或修改时间分页给出。重复同步按 {@code transactionKey} upsert。</p>
*/
public interface SettlementCapable extends PlatformAdapter {
Page<SettlementTransaction> pull(ChannelContext ctx, SettlementQuery query);
}

36
core/src/main/java/common/ecommerce/capability/Settlements.java

@ -0,0 +1,36 @@ @@ -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.settlement.SettlementQuery;
import common.ecommerce.model.settlement.SettlementTransaction;
import common.ecommerce.model.support.Page;
import common.ecommerce.sdk.ChannelContext;
/**
* 门面持有的结算视图。调用前做能力检查,缺失时显式拒绝。
*/
public final class Settlements {
private final PlatformAdapter adapter;
private final ChannelAccount account;
private final ChannelContext ctx;
public Settlements(PlatformAdapter adapter, ChannelAccount account, ChannelContext ctx) {
this.adapter = adapter;
this.account = account;
this.ctx = ctx;
}
public Page<SettlementTransaction> pull(SettlementQuery query) {
requireSettlementCapable();
return ((SettlementCapable) adapter).pull(ctx, query);
}
private void requireSettlementCapable() {
if (!adapter.supports(account, Capability.BILLING) || !(adapter instanceof SettlementCapable)) {
throw new ChannelException.UnsupportedCapabilityException(Capability.BILLING);
}
}
}

183
core/src/main/java/common/ecommerce/model/settlement/SettlementQuery.java

@ -0,0 +1,183 @@ @@ -0,0 +1,183 @@
package common.ecommerce.model.settlement;
import java.time.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 结算交易明细查询条件(单次查询,不推进水位线)。
*
* <p>平台通常要求「结算时间」与「修改时间」二选一,或给出精确搜索值;
* 具体校验在适配器里做,core 只承载条件。</p>
*/
public final class SettlementQuery {
private final LocalDate settledAfter;
private final LocalDate settledBefore;
private final Instant modifiedAfter;
private final Instant modifiedBefore;
private final String eventType;
private final String transactionType;
private final String searchField;
private final List<String> searchValues;
private final int pageSize;
private final String cursor;
private SettlementQuery(Builder b) {
this.settledAfter = b.settledAfter;
this.settledBefore = b.settledBefore;
this.modifiedAfter = b.modifiedAfter;
this.modifiedBefore = b.modifiedBefore;
this.eventType = b.eventType;
this.transactionType = b.transactionType;
this.searchField = b.searchField;
this.searchValues = Collections.unmodifiableList(new ArrayList<String>(b.searchValues));
this.pageSize = b.pageSize;
this.cursor = b.cursor;
}
public static Builder builder() {
return new Builder();
}
/** 结算时间起(含),按平台站点日期。 */
public LocalDate settledAfter() {
return settledAfter;
}
/** 结算时间止(含)。 */
public LocalDate settledBefore() {
return settledBefore;
}
/** 修改时间起(含)。时区语义由适配器解释。 */
public Instant modifiedAfter() {
return modifiedAfter;
}
/** 修改时间止(含)。 */
public Instant modifiedBefore() {
return modifiedBefore;
}
/** 来源事件,多个用逗号分隔,如 {@code ShipmentEventList,RefundEventList}。 */
public String eventType() {
return eventType;
}
/** 交易类型,如 Commission / Tax。 */
public String transactionType() {
return transactionType;
}
/** 精确搜索字段,如 {@code id} / {@code amazon_order_id} / {@code settlement_id}。 */
public String searchField() {
return searchField;
}
public List<String> searchValues() {
return searchValues;
}
public int pageSize() {
return pageSize;
}
public String cursor() {
return cursor;
}
public Builder toBuilder() {
return builder()
.settledAfter(settledAfter)
.settledBefore(settledBefore)
.modifiedAfter(modifiedAfter)
.modifiedBefore(modifiedBefore)
.eventType(eventType)
.transactionType(transactionType)
.searchField(searchField)
.searchValues(searchValues)
.pageSize(pageSize)
.cursor(cursor);
}
public static final class Builder {
private LocalDate settledAfter;
private LocalDate settledBefore;
private Instant modifiedAfter;
private Instant modifiedBefore;
private String eventType;
private String transactionType;
private String searchField;
private List<String> searchValues = Collections.emptyList();
private int pageSize = 100;
private String cursor;
public Builder settledAfter(LocalDate settledAfter) {
this.settledAfter = settledAfter;
return this;
}
public Builder settledBefore(LocalDate settledBefore) {
this.settledBefore = settledBefore;
return this;
}
public Builder modifiedAfter(Instant modifiedAfter) {
this.modifiedAfter = modifiedAfter;
return this;
}
public Builder modifiedBefore(Instant modifiedBefore) {
this.modifiedBefore = modifiedBefore;
return this;
}
public Builder eventType(String eventType) {
this.eventType = eventType;
return this;
}
public Builder transactionType(String transactionType) {
this.transactionType = transactionType;
return this;
}
public Builder searchField(String searchField) {
this.searchField = searchField;
return this;
}
public Builder searchValues(List<String> searchValues) {
this.searchValues = searchValues == null
? Collections.<String>emptyList() : searchValues;
return this;
}
public Builder searchValues(String... searchValues) {
List<String> values = new ArrayList<String>();
if (searchValues != null) {
Collections.addAll(values, searchValues);
}
this.searchValues = values;
return this;
}
public Builder pageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public Builder cursor(String cursor) {
this.cursor = cursor;
return this;
}
public SettlementQuery build() {
return new SettlementQuery(this);
}
}
}

281
core/src/main/java/common/ecommerce/model/settlement/SettlementTransaction.java

@ -0,0 +1,281 @@ @@ -0,0 +1,281 @@
package common.ecommerce.model.settlement;
import common.ecommerce.model.ChannelProvider;
import common.ecommerce.model.support.Money;
import common.ecommerce.model.support.PlatformTime;
import java.util.Objects;
/**
* 平台结算交易明细(一行费用)。
*
* <p>用于对账:一笔订单可能拆成佣金、配送费、退款、广告费等多行,
* 每行由 {@code transactionKey} 唯一标识。{@code transactionKey} 必须稳定,
* 否则重复同步会产生重复账单;平台在未结算阶段可能变更 key 的,
* 由适配器文档单独说明。</p>
*/
public final class SettlementTransaction {
private final String omsStoreId;
private final String transactionKey;
private final ChannelProvider sourceProvider;
private final String sourceAccountId;
private final String channelOrderId;
private final String storeName;
private final String countryCode;
private final String fulfillment;
private final String eventType;
private final String transactionType;
private final String sellerSku;
private final String localSku;
private final String asin;
private final Money amount;
private final int quantity;
private final String processingStatus;
private final String fundTransferStatus;
private final String settlementId;
private final PlatformTime postedAt;
private final String marketplaceName;
private SettlementTransaction(Builder b) {
this.omsStoreId = Objects.requireNonNull(b.omsStoreId, "omsStoreId");
this.transactionKey = Objects.requireNonNull(b.transactionKey, "transactionKey");
this.sourceProvider = Objects.requireNonNull(b.sourceProvider, "sourceProvider");
this.sourceAccountId = b.sourceAccountId;
this.channelOrderId = b.channelOrderId;
this.storeName = b.storeName;
this.countryCode = b.countryCode;
this.fulfillment = b.fulfillment;
this.eventType = b.eventType;
this.transactionType = b.transactionType;
this.sellerSku = b.sellerSku;
this.localSku = b.localSku;
this.asin = b.asin;
this.amount = b.amount;
this.quantity = b.quantity;
this.processingStatus = b.processingStatus;
this.fundTransferStatus = b.fundTransferStatus;
this.settlementId = b.settlementId;
this.postedAt = b.postedAt;
this.marketplaceName = b.marketplaceName;
}
public static Builder builder() {
return new Builder();
}
public String omsStoreId() {
return omsStoreId;
}
/** 交易明细唯一标识,重复同步按它 upsert。 */
public String transactionKey() {
return transactionKey;
}
public ChannelProvider sourceProvider() {
return sourceProvider;
}
public String sourceAccountId() {
return sourceAccountId;
}
public String channelOrderId() {
return channelOrderId;
}
public String storeName() {
return storeName;
}
public String countryCode() {
return countryCode;
}
public String fulfillment() {
return fulfillment;
}
/** 来源事件,如 Shipment / Refund / ServiceFee。 */
public String eventType() {
return eventType;
}
/** 交易类型,如 Commission / Tax / Refund。 */
public String transactionType() {
return transactionType;
}
public String sellerSku() {
return sellerSku;
}
public String localSku() {
return localSku;
}
public String asin() {
return asin;
}
/** 金额;平台未给币种时为 null。 */
public Money amount() {
return amount;
}
public int quantity() {
return quantity;
}
/** 结算状态:Open / Closed / Reconciled。 */
public String processingStatus() {
return processingStatus;
}
/** 转账状态:Succeeded / Processing / Failed / Unknown。 */
public String fundTransferStatus() {
return fundTransferStatus;
}
public String settlementId() {
return settlementId;
}
/** 结算时间;平台未给可解析时间时为 null。 */
public PlatformTime postedAt() {
return postedAt;
}
public String marketplaceName() {
return marketplaceName;
}
public static final class Builder {
private String omsStoreId;
private String transactionKey;
private ChannelProvider sourceProvider;
private String sourceAccountId;
private String channelOrderId;
private String storeName;
private String countryCode;
private String fulfillment;
private String eventType;
private String transactionType;
private String sellerSku;
private String localSku;
private String asin;
private Money amount;
private int quantity;
private String processingStatus;
private String fundTransferStatus;
private String settlementId;
private PlatformTime postedAt;
private String marketplaceName;
public Builder omsStoreId(String omsStoreId) {
this.omsStoreId = omsStoreId;
return this;
}
public Builder transactionKey(String transactionKey) {
this.transactionKey = transactionKey;
return this;
}
public Builder sourceProvider(ChannelProvider sourceProvider) {
this.sourceProvider = sourceProvider;
return this;
}
public Builder sourceAccountId(String sourceAccountId) {
this.sourceAccountId = sourceAccountId;
return this;
}
public Builder channelOrderId(String channelOrderId) {
this.channelOrderId = channelOrderId;
return this;
}
public Builder storeName(String storeName) {
this.storeName = storeName;
return this;
}
public Builder countryCode(String countryCode) {
this.countryCode = countryCode;
return this;
}
public Builder fulfillment(String fulfillment) {
this.fulfillment = fulfillment;
return this;
}
public Builder eventType(String eventType) {
this.eventType = eventType;
return this;
}
public Builder transactionType(String transactionType) {
this.transactionType = transactionType;
return this;
}
public Builder sellerSku(String sellerSku) {
this.sellerSku = sellerSku;
return this;
}
public Builder localSku(String localSku) {
this.localSku = localSku;
return this;
}
public Builder asin(String asin) {
this.asin = asin;
return this;
}
public Builder amount(Money amount) {
this.amount = amount;
return this;
}
public Builder quantity(int quantity) {
this.quantity = quantity;
return this;
}
public Builder processingStatus(String processingStatus) {
this.processingStatus = processingStatus;
return this;
}
public Builder fundTransferStatus(String fundTransferStatus) {
this.fundTransferStatus = fundTransferStatus;
return this;
}
public Builder settlementId(String settlementId) {
this.settlementId = settlementId;
return this;
}
public Builder postedAt(PlatformTime postedAt) {
this.postedAt = postedAt;
return this;
}
public Builder marketplaceName(String marketplaceName) {
this.marketplaceName = marketplaceName;
return this;
}
public SettlementTransaction build() {
return new SettlementTransaction(this);
}
}
}

7
core/src/main/java/common/ecommerce/sdk/ChannelSdk.java

@ -9,6 +9,7 @@ import common.ecommerce.capability.CapabilityReport; @@ -9,6 +9,7 @@ import common.ecommerce.capability.CapabilityReport;
import common.ecommerce.capability.PlatformAdapter;
import common.ecommerce.capability.Products;
import common.ecommerce.capability.SalesOrders;
import common.ecommerce.capability.Settlements;
import common.ecommerce.idempotency.IdempotencyGuard;
import common.ecommerce.model.account.AccountKey;
import common.ecommerce.model.account.ChannelAccount;
@ -79,6 +80,12 @@ public final class ChannelSdk implements ProviderResolver { @@ -79,6 +80,12 @@ public final class ChannelSdk implements ProviderResolver {
return new Products(resolve(key), account, newContext(account, connection));
}
/** 结算 / 账单交易明细视图。 */
public Settlements settlements(AccountKey key, ChannelConnection connection) {
ChannelAccount account = requireAccount(key);
return new Settlements(resolve(key), account, newContext(account, connection));
}
/**
* 聚合器的子店铺列表(如领星下已授权的亚马逊 / 沃尔玛店铺)。
*

23
lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java

@ -26,6 +26,29 @@ public enum LingxingApi { @@ -26,6 +26,29 @@ public enum LingxingApi {
/** 亚马逊 SC Listing 列表。POST,offset/length 分页,上限 1000。 */
LISTING_AMAZON_SC("/erp/sc/data/mws/listing", 1),
/**
* 亚马逊 SC 订单列表。POST,offset/length 分页,length 上限 5000;
* 查询时间窗不超过 1 年。
*/
ORDER_LIST_AMAZON_SC("/erp/sc/data/mws/orders", 1),
/** 亚马逊 SC 订单详情。POST,{@code order_id} 支持逗号分隔多个(上限 200)。 */
ORDER_DETAIL_AMAZON_SC("/erp/sc/data/mws/orderDetail", 1),
/**
* 亚马逊自发货(FBM)订单列表。POST,{@code page} 从 1 开始,{@code length} 默认 100。
*
* <p>与 {@link #ORDER_LIST_AMAZON_SC} 不同:主键是领星系统单号 {@code order_number},
* 不是平台订单号。</p>
*/
ORDER_LIST_FBM_AMAZON_SC("/erp/sc/routing/order/Order/getOrderList", 1),
/** 亚马逊自发货(FBM)订单详情。POST,入参是领星系统单号 {@code order_number}。 */
ORDER_DETAIL_FBM_AMAZON_SC("/erp/sc/routing/order/Order/getOrderDetail", 1),
/** 亚马逊结算中心交易明细。POST,offset/length 分页,上限 10000。 */
SETTLEMENT_TRANSACTION_LIST("/bd/sp/api/open/settlement/transaction/detail/list", 10),
/** 多平台订单列表;当前实现使用的跨平台接口。 */
ORDER_LIST("/pb/mp/order/v2/list", 10);

29
lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java

@ -19,12 +19,35 @@ public final class LingxingConstants { @@ -19,12 +19,35 @@ public final class LingxingConstants {
public static final String ADAPTER_ID = "lingxing";
// 接口路径与限流值统一放在 LingxingApi 枚举里,这里不再重复。
/** 获取令牌。 */
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";
/** 订单查询时间跨度上限:31 天(领星统一订单接口的限制)。 */
/** 亚马逊 SC 的领星 platform_code。 */
public static final int PLATFORM_CODE_AMAZON = 10001;
/** 多平台订单列表令牌桶:10 req/s(亚马逊/VC/Walmart 接口是 1 req/s)。 */
public static final int ORDER_LIST_PER_SECOND = 10;
/** 订单查询时间跨度上限:31 天。 */
public static final int MAX_QUERY_DAYS = 31;
/** 分页 length 上限(领星统一订单接口的限制)。 */
/** 亚马逊订单查询时间跨度上限:1 年。 */
public static final int AMAZON_MAX_QUERY_DAYS = 365;
/** 多平台分页 length 上限(领星统一订单接口的限制)。 */
public static final int MAX_PAGE_SIZE = 500;
/** 亚马逊订单分页 length 上限。 */
public static final int AMAZON_MAX_PAGE_SIZE = 5000;
/** 亚马逊 FBM 订单分页 length:文档默认 100,未给上限,按默认值取。 */
public static final int FBM_MAX_PAGE_SIZE = 100;
/** 结算交易明细分页 length 上限。 */
public static final int SETTLEMENT_MAX_PAGE_SIZE = 10000;
/** 结算时间查询跨度上限:7 天(双闭区间)。 */
public static final int SETTLEMENT_MAX_QUERY_DAYS = 7;
private LingxingConstants() {
}

130
lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java

@ -1,26 +1,25 @@ @@ -1,26 +1,25 @@
package common.ecommerce.lingxing.adapter;
import common.ecommerce.lingxing.LingxingConstants;
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.LingxingSubPlatform;
import common.ecommerce.lingxing.platform.LingxingSubPlatforms;
import common.ecommerce.capability.AggregatorCapable;
import common.ecommerce.capability.ProductCapable;
import common.ecommerce.capability.SalesOrderCapable;
import common.ecommerce.capability.SettlementCapable;
import common.ecommerce.error.AuthException;
import common.ecommerce.error.ChannelException;
import common.ecommerce.http.HttpTransport;
import common.ecommerce.http.JacksonJsonCodec;
import common.ecommerce.http.TokenManager;
import common.ecommerce.lingxing.LingxingConstants;
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.lingxing.platform.LingxingSubPlatform;
import common.ecommerce.lingxing.platform.LingxingSubPlatforms;
import common.ecommerce.model.Capability;
import common.ecommerce.model.account.ChannelAccount;
import common.ecommerce.model.ChannelProvider;
import common.ecommerce.model.support.Page;
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.order.SalesOrderRef;
@ -28,6 +27,9 @@ import common.ecommerce.model.product.ProductListing; @@ -28,6 +27,9 @@ import common.ecommerce.model.product.ProductListing;
import common.ecommerce.model.product.ProductQuery;
import common.ecommerce.model.product.ProductRef;
import common.ecommerce.model.product.ProductSyncStrategy;
import common.ecommerce.model.settlement.SettlementQuery;
import common.ecommerce.model.settlement.SettlementTransaction;
import common.ecommerce.model.support.Page;
import common.ecommerce.sdk.ChannelContext;
import common.ecommerce.spi.AccessToken;
import common.ecommerce.spi.ChannelSecret;
@ -35,8 +37,6 @@ import common.ecommerce.spi.LockProvider; @@ -35,8 +37,6 @@ import common.ecommerce.spi.LockProvider;
import common.ecommerce.spi.TokenStore;
import java.time.Clock;
import java.time.Duration;
import java.time.ZoneId;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
@ -45,14 +45,17 @@ import java.util.Set; @@ -45,14 +45,17 @@ import java.util.Set;
* 领星聚合适配器。
*
* <p>一个适配器服务多个子平台,子平台由 {@code ChannelAccount.platformCode} 决定,
* 能力按子平台细化({@link #supports})。首期只实现订单列表拉取。</p>
* 能力按子平台细化({@link #supports})。</p>
*
* <p>适配器只做三件事:取 token、把公共设施装进 {@link LingxingCall}、按子平台分派。
* 具体的「拼请求体 + 解析响应」由各子平台的 Source 实现,见
* {@link LingxingSubPlatform}。</p>
*/
public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, AggregatorCapable {
public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, SettlementCapable,
AggregatorCapable {
private final HttpTransport transport;
private final JacksonJsonCodec json;
private final Clock clock;
private final LingxingOrderMapper mapper;
private final TokenManager tokenManager;
private final LingxingRateLimiter rateLimiter;
private final LingxingRequestFactory requestFactory;
@ -64,8 +67,6 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -64,8 +67,6 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
TokenStore tokenStore, LockProvider lockProvider, Clock clock) {
this.transport = transport;
this.json = json;
this.clock = clock;
this.mapper = new LingxingOrderMapper(json);
final LingxingTokenClient tokenClient = new LingxingTokenClient(transport, json, clock);
// 领星 access_token 约 2h,提前 10 分钟续期。
//
@ -109,14 +110,14 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -109,14 +110,14 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
@Override
public EnumSet<Capability> capabilities() {
return EnumSet.of(Capability.SALES_ORDER, Capability.PRODUCT);
return EnumSet.of(Capability.SALES_ORDER, Capability.PRODUCT, Capability.BILLING);
}
/**
* 聚合器按子平台细化能力。
*
* <p>eBay / SHEIN / Mirakl / 自定义平台在领星侧只有订单,未见账单与售后接口,
* 因此只声明 SALES_ORDER,缺口由能力报告显式暴露,不假装支持。</p>
* <p>能力以子平台实际装配的 Source 为准:没有 orderSource 就不声明订单,
* 缺口由能力报告显式暴露,不假装支持。</p>
*/
@Override
public boolean supports(ChannelAccount account, Capability capability) {
@ -124,7 +125,7 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -124,7 +125,7 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
return false;
}
Platform p = LingxingConstants.toPlatform(account.platformCode());
if (!LingxingSubPlatforms.isRegistered(p)) {
if (p == null || !LingxingSubPlatforms.isRegistered(p)) {
return false;
}
LingxingSubPlatform impl = LingxingSubPlatforms.of(p);
@ -134,6 +135,9 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -134,6 +135,9 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
if (capability == Capability.PRODUCT) {
return impl.productSource() != null;
}
if (capability == Capability.BILLING) {
return impl.settlementSource() != null;
}
return false;
}
@ -142,9 +146,6 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -142,9 +146,6 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
*/
@Override
public List<SubChannel> listSubChannels(ChannelContext ctx) {
ChannelSecret secret = ctx.secret();
AccessToken token = tokenManager.getOrRefresh(tokenKey(secret), secret);
LingxingCall call = new LingxingCall(ctx, token, requestFactory, rateLimiter, json, transport);
LingxingSubPlatform impl = LingxingSubPlatforms.of(ctx.platform());
if (impl.shopSource() == null) {
throw ChannelException.builder()
@ -156,20 +157,63 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -156,20 +157,63 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
.retryable(false)
.build();
}
return impl.shopSource().shops(call);
return impl.shopSource().shops(call(ctx));
}
@Override
public Page<SalesOrder> pull(ChannelContext ctx, SalesOrderQuery query) {
requireCapability();
ChannelSecret secret = ctx.secret();
AccessToken token = tokenManager.getOrRefresh(tokenKey(secret), secret);
LingxingCall call = new LingxingCall(ctx, token, requestFactory, rateLimiter, json, transport);
LingxingSubPlatform impl = LingxingSubPlatforms.of(ctx.platform());
if (impl.orderSource() == null) {
throw new ChannelException.UnsupportedCapabilityException(Capability.SALES_ORDER);
}
return impl.orderSource().orders(call, query);
return impl.orderSource().orders(call(ctx), query);
}
@Override
public SalesOrder get(ChannelContext ctx, SalesOrderRef ref) {
LingxingSubPlatform impl = LingxingSubPlatforms.of(ctx.platform());
if (impl.orderSource() == null) {
throw new ChannelException.UnsupportedCapabilityException(Capability.SALES_ORDER);
}
return impl.orderSource().order(call(ctx), ref.channelOrderId());
}
/**
* 亚马逊 FBM(自发货)订单列表。
*
* <p>与 {@link #pull(ChannelContext, SalesOrderQuery)} 不是同一条路由:
* 这套接口的主键是领星系统单号 {@code order_number},用于「订单管理」视角;
* 跨渠道同步仍用标准订单路由。</p>
*/
public Page<SalesOrder> pullFbmOrders(ChannelContext ctx, SalesOrderQuery query) {
LingxingSubPlatform impl = LingxingSubPlatforms.of(ctx.platform());
if (impl.fbmOrderSource() == null) {
throw new ChannelException.UnsupportedCapabilityException(Capability.SALES_ORDER);
}
return impl.fbmOrderSource().orders(call(ctx), query);
}
/**
* 亚马逊 FBM 订单详情。
*
* @param orderNumber 领星系统单号,不是平台订单号
*/
public SalesOrder getFbmOrder(ChannelContext ctx, String orderNumber) {
LingxingSubPlatform impl = LingxingSubPlatforms.of(ctx.platform());
if (impl.fbmOrderSource() == null) {
throw new ChannelException.UnsupportedCapabilityException(Capability.SALES_ORDER);
}
return impl.fbmOrderSource().order(call(ctx), orderNumber);
}
@Override
public Page<SettlementTransaction> pull(ChannelContext ctx, SettlementQuery query) {
LingxingSubPlatform impl = LingxingSubPlatforms.of(ctx.platform());
if (impl.settlementSource() == null) {
throw new ChannelException.UnsupportedCapabilityException(Capability.BILLING);
}
return impl.settlementSource().transactions(call(ctx), query);
}
@Override
@ -180,14 +224,11 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -180,14 +224,11 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
@Override
public Page<ProductListing> pull(ChannelContext ctx, ProductQuery query) {
ChannelSecret secret = ctx.secret();
AccessToken token = tokenManager.getOrRefresh(tokenKey(secret), secret);
LingxingCall call = new LingxingCall(ctx, token, requestFactory, rateLimiter, json, transport);
LingxingSubPlatform impl = LingxingSubPlatforms.of(ctx.platform());
if (impl.productSource() == null) {
throw new ChannelException.UnsupportedCapabilityException(Capability.PRODUCT);
}
return impl.productSource().products(call, query);
return impl.productSource().products(call(ctx), query);
}
/** 商品详情接口未接入,显式拒绝。 */
@ -204,22 +245,15 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable, @@ -204,22 +245,15 @@ public final class LingxingAdapter implements SalesOrderCapable, ProductCapable,
.build();
}
/** 单订单详情接口待核对(领星以列表接口为主),先显式拒绝而不是返回 null。 */
@Override
public SalesOrder get(ChannelContext ctx, SalesOrderRef ref) {
String channelOrderId = ref.channelOrderId();
throw ChannelException.builder()
.message("lingxing order detail is not implemented yet")
.operation("salesOrders.get")
.provider(provider().name())
.omsStoreId(ctx.omsStoreId())
.requestId(ctx.requestId())
.platformCode(channelOrderId)
.build();
}
// ---------------------------------------------------------------- internals
/** 取 token 并装配本次调用所需的公共设施。 */
private LingxingCall call(ChannelContext ctx) {
ChannelSecret secret = ctx.secret();
AccessToken token = tokenManager.getOrRefresh(tokenKey(secret), secret);
return new LingxingCall(ctx, token, requestFactory, rateLimiter, json, transport);
}
/**
* 令牌缓存维度:领星 token 按 app 发放(appId + appSecret 换),
* 同一 app 下的多家店铺共用一个 token。用 appKey 而不是 store_id,

3
lingxing/src/main/java/common/ecommerce/lingxing/http/LingxingRequestFactory.java

@ -33,6 +33,7 @@ public final class LingxingRequestFactory { @@ -33,6 +33,7 @@ public final class LingxingRequestFactory {
this.clock = clock;
}
/** POST:业务参数放 JSON 请求体,同时参与签名。 */
public HttpRequest post(String baseUrl, String path, Map<String, Object> body, ChannelSecret secret,
AccessToken token, ChannelContext ctx, String operation) {
Map<String, Object> payload = withoutNulls(body);
@ -65,7 +66,7 @@ public final class LingxingRequestFactory { @@ -65,7 +66,7 @@ public final class LingxingRequestFactory {
}
/**
* GET 请求:参数放在 query 并参与签名。
* GET:参数放在 query 并参与签名。
*
* <p>领星部分接口(如亚马逊店铺列表)是 GET 且无业务参数,
* 此时 query 里只有 {@code app_key} / {@code timestamp} / {@code sign}。</p>

4
lingxing/src/main/java/common/ecommerce/lingxing/mapper/LingxingOrderMapper.java

@ -131,8 +131,10 @@ public final class LingxingOrderMapper { @@ -131,8 +131,10 @@ public final class LingxingOrderMapper {
/**
* 领星金额可能带币种符号或千分位({@code "¥49.16"}、{@code "-¥0.98"}、{@code "1,234.56"}),
* 只保留数字、小数点与符号位;没有数字时视为缺失。
*
* <p>亚马逊订单与多平台订单共用这套清洗规则,故对外暴露。</p>
*/
static String cleanAmount(String raw) {
public static String cleanAmount(String raw) {
if (raw == null) {
return null;
}

46
lingxing/src/main/java/common/ecommerce/lingxing/platform/LingxingSubPlatform.java

@ -1,42 +1,50 @@ @@ -1,42 +1,50 @@
package common.ecommerce.lingxing.platform;
import common.ecommerce.capability.AggregatorCapable.SubChannel;
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;
import common.ecommerce.lingxing.platform.order.LingxingOrderSource;
import common.ecommerce.lingxing.platform.product.LingxingProductSource;
import common.ecommerce.lingxing.platform.settlement.LingxingSettlementSource;
import common.ecommerce.lingxing.platform.shop.LingxingShopSource;
/**
* 领星子平台的<b>能力分派入口</b>:只做组合,不写业务逻辑。
*
* <p>各能力由独立的 Source 实现({@link common.ecommerce.lingxing.platform.order.LingxingOrderSource}、
* {@link common.ecommerce.lingxing.platform.product.LingxingProductSource}、
* {@link common.ecommerce.lingxing.platform.shop.LingxingShopSource})提供,
* 子平台不支持的 Source 传 {@code null} 即可,调用时统一抛
* {@code UnsupportedCapabilityException}。</p>
*
* <p>这样单个平台类不会随能力增长而膨胀,能力之间也互不干扰。</p>
* <p>各能力由独立的 Source 实现({@link LingxingOrderSource}、
* {@link LingxingProductSource}、{@link LingxingShopSource}、
* {@link LingxingSettlementSource})提供,子平台不支持的 Source 传 {@code null} 即可,
* 调用时统一抛 {@code UnsupportedCapabilityException}。</p>
*/
public interface LingxingSubPlatform {
/** 对应的业务平台,用于注册表与日志。 */
common.ecommerce.model.Platform platform();
/** 订单能力;不支持时为 null。 */
default common.ecommerce.lingxing.platform.order.LingxingOrderSource orderSource() {
/** 订单能力(领星标准订单接口);不支持时为 null。 */
default LingxingOrderSource orderSource() {
return null;
}
/**
* 亚马逊 FBM(自发货)路由订单能力;不支持时为 null。
*
* <p>这套接口的主键是领星系统单号 {@code order_number},与
* {@link #orderSource()} 的平台订单号不同,因此单独成一路,不混用。</p>
*/
default LingxingOrderSource fbmOrderSource() {
return null;
}
/** 商品能力;不支持时为 null。 */
default common.ecommerce.lingxing.platform.product.LingxingProductSource productSource() {
default LingxingProductSource productSource() {
return null;
}
/** 店铺能力;不支持时为 null。 */
default common.ecommerce.lingxing.platform.shop.LingxingShopSource shopSource() {
default LingxingShopSource shopSource() {
return null;
}
/** 结算 / 账单能力;不支持时为 null。 */
default LingxingSettlementSource settlementSource() {
return null;
}
}

25
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/AmazonScSubPlatform.java

@ -3,8 +3,12 @@ package common.ecommerce.lingxing.platform.amazon; @@ -3,8 +3,12 @@ package common.ecommerce.lingxing.platform.amazon;
import common.ecommerce.http.HttpTransport;
import common.ecommerce.http.JacksonJsonCodec;
import common.ecommerce.lingxing.platform.LingxingSubPlatform;
import common.ecommerce.lingxing.platform.amazon.order.AmazonFbmOrderSource;
import common.ecommerce.lingxing.platform.amazon.order.AmazonOrderSource;
import common.ecommerce.lingxing.platform.amazon.settlement.AmazonSettlementSource;
import common.ecommerce.lingxing.platform.order.LingxingOrderSource;
import common.ecommerce.lingxing.platform.product.LingxingProductSource;
import common.ecommerce.lingxing.platform.settlement.LingxingSettlementSource;
import common.ecommerce.lingxing.platform.shop.LingxingShopSource;
import common.ecommerce.model.Platform;
@ -13,12 +17,18 @@ import common.ecommerce.model.Platform; @@ -13,12 +17,18 @@ import common.ecommerce.model.Platform;
*/
public final class AmazonScSubPlatform implements LingxingSubPlatform {
private final LingxingOrderSource orders;
private final LingxingOrderSource fbmOrders;
private final LingxingProductSource products;
private final LingxingShopSource shops;
private final LingxingSettlementSource settlements;
public AmazonScSubPlatform(HttpTransport transport, JacksonJsonCodec json) {
this.orders = new AmazonOrderSource();
this.fbmOrders = new AmazonFbmOrderSource();
this.products = new AmazonProductSource();
this.shops = new AmazonShopSource();
this.settlements = new AmazonSettlementSource();
}
@Override
@ -27,6 +37,16 @@ public final class AmazonScSubPlatform implements LingxingSubPlatform { @@ -27,6 +37,16 @@ public final class AmazonScSubPlatform implements LingxingSubPlatform {
}
@Override
public LingxingOrderSource orderSource() {
return orders;
}
@Override
public LingxingOrderSource fbmOrderSource() {
return fbmOrders;
}
@Override
public LingxingProductSource productSource() {
return products;
}
@ -36,9 +56,8 @@ public final class AmazonScSubPlatform implements LingxingSubPlatform { @@ -36,9 +56,8 @@ public final class AmazonScSubPlatform implements LingxingSubPlatform {
return shops;
}
/** 亚马逊 SC 的订单接口暂未核对,接入前不声明订单能力。 */
@Override
public LingxingOrderSource orderSource() {
return null;
public LingxingSettlementSource settlementSource() {
return settlements;
}
}

6
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/AmazonShopSource.java

@ -4,6 +4,7 @@ import common.ecommerce.capability.AggregatorCapable.SubChannel; @@ -4,6 +4,7 @@ import common.ecommerce.capability.AggregatorCapable.SubChannel;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpResponse;
import common.ecommerce.lingxing.LingxingApi;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.lingxing.http.LingxingEnvelope;
import common.ecommerce.lingxing.platform.LingxingCall;
import common.ecommerce.lingxing.platform.amazon.dto.AmazonShopDto;
@ -22,9 +23,6 @@ import java.util.List; @@ -22,9 +23,6 @@ import java.util.List;
*/
public final class AmazonShopSource implements LingxingShopSource {
/** 领星侧 Amazon SC 的 platform_code。 */
private static final int AMAZON_SC_PLATFORM_CODE = 10001;
/** 店铺状态:1 = 正常同步。 */
private static final int STATUS_ACTIVE = 1;
@ -42,7 +40,7 @@ public final class AmazonShopSource implements LingxingShopSource { @@ -42,7 +40,7 @@ public final class AmazonShopSource implements LingxingShopSource {
}
// platformCode 取领星侧 Amazon SC 的平台码 10001;externalStoreId 用领星店铺 id(sid)
out.add(new SubChannel(
AMAZON_SC_PLATFORM_CODE,
LingxingConstants.PLATFORM_CODE_AMAZON,
String.valueOf(shop.getSid()),
Platform.AMAZON_SC,
shop.getName() == null ? shop.getSellerId() : shop.getName()));

77
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderDetailDto.java

@ -0,0 +1,77 @@ @@ -0,0 +1,77 @@
package common.ecommerce.lingxing.platform.amazon.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;
/**
* 领星 · 亚马逊 SC 订单详情({@code /erp/sc/data/mws/orderDetail} 的 {@code data[]})。
*
* <p>与列表的差异:</p>
* <ul>
* <li>币种字段叫 {@code currency}(不是 {@code order_total_currency_code})</li>
* <li>商品行带完整金额</li>
* <li>没有原始 ISO 的 {@code purchase_date},只有
* {@code purchase_date_local} 与 {@code purchase_date_local_utc}</li>
* </ul>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class AmazonOrderDetailDto {
@JsonProperty("sid")
private Long sid;
@JsonProperty("amazon_order_id")
private String amazonOrderId;
/** 配送方式:AFN / MFN。 */
@JsonProperty("fulfillment_channel")
private String fulfillmentChannel;
@JsonProperty("order_status")
private String orderStatus;
/** 订单总金额;文档类型是 number。 */
@JsonProperty("order_total_amount")
private String orderTotalAmount;
/** 订单金额币种。 */
@JsonProperty("currency")
private String currency;
/** 币种符号。 */
@JsonProperty("icon")
private String icon;
/** 订购时间(站点时间)。 */
@JsonProperty("purchase_date_local")
private String purchaseDateLocal;
/** 订购时间(UTC);字段名就是 local_utc,不是笔误。 */
@JsonProperty("purchase_date_local_utc")
private String purchaseDateLocalUtc;
/** 订单更新时间(站点时间)。 */
@JsonProperty("last_update_date")
private String lastUpdateDate;
/** 订单更新时间(UTC)。 */
@JsonProperty("last_update_date_utc")
private String lastUpdateDateUtc;
/** 发货时间(站点时间);未发货为空串。 */
@JsonProperty("shipment_date")
private String shipmentDate;
@JsonProperty("sales_channel")
private String salesChannel;
@JsonProperty("item_list")
private List<AmazonOrderDetailItemDto> itemList = new ArrayList<AmazonOrderDetailItemDto>();
}

72
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderDetailItemDto.java

@ -0,0 +1,72 @@ @@ -0,0 +1,72 @@
package common.ecommerce.lingxing.platform.amazon.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
/**
* 领星 · 亚马逊 SC 订单详情的商品行({@code data[].item_list[]})。
*
* <p>金额字段文档写 string,真实响应里 {@code unit_price_amount} /
* {@code item_discount} 是 number,用 String 接收两种都能读,
* 由 Source 统一清洗。</p>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class AmazonOrderDetailItemDto {
/** 订单商品自增 id。 */
@JsonProperty("id")
private Long id;
/** 订单商品编码;亚马逊可能变更,不能当稳定主键。 */
@JsonProperty("order_item_id")
private String orderItemId;
@JsonProperty("title")
private String title;
/** 平台 MSKU。 */
@JsonProperty("seller_sku")
private String sellerSku;
@JsonProperty("asin")
private String asin;
/** 本地 SKU。 */
@JsonProperty("sku")
private String sku;
@JsonProperty("product_name")
private String productName;
/** 下单量。 */
@JsonProperty("quantity_ordered")
private Integer quantityOrdered;
/** 已配送量。 */
@JsonProperty("quantity_shipped")
private Integer quantityShipped;
/** 商品支付金额(含税)。 */
@JsonProperty("item_price_amount")
private String itemPriceAmount;
/** 商品税。 */
@JsonProperty("item_tax_amount")
private String itemTaxAmount;
/** 单价。 */
@JsonProperty("unit_price_amount")
private String unitPriceAmount;
/** 商品促销折扣。 */
@JsonProperty("promotion_discount_amount")
private String promotionDiscountAmount;
/** 商品折扣。 */
@JsonProperty("item_discount")
private String itemDiscount;
}

100
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderDto.java

@ -0,0 +1,100 @@ @@ -0,0 +1,100 @@
package common.ecommerce.lingxing.platform.amazon.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;
/**
* 领星 · 亚马逊 SC 订单列表条目({@code /erp/sc/data/mws/orders} 的 {@code data[]})。
*
* <p>与多平台订单的差异:</p>
* <ul>
* <li>{@code data} 直接是数组,不是 {@code data.list}</li>
* <li>{@code total} 在<b>顶层</b></li>
* <li>状态是字符串枚举({@code Unshipped} / {@code Shipped} …),不是整数</li>
* <li>时间是字符串,不是 epoch 秒</li>
* </ul>
*
* <p>列表接口<b>不返回</b>单价/税额/折扣,这些字段只在订单详情里。</p>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class AmazonOrderDto {
/** 领星店铺 id。 */
@JsonProperty("sid")
private Long sid;
/** 店铺名称。 */
@JsonProperty("seller_name")
private String sellerName;
/** 亚马逊订单号,即 channelOrderId。 */
@JsonProperty("amazon_order_id")
private String amazonOrderId;
/** 订单状态:Pending / Unshipped / PartiallyShipped / Shipped / Canceled 等。 */
@JsonProperty("order_status")
private String orderStatus;
/** 订单金额;文档类型是 number。 */
@JsonProperty("order_total_amount")
private String orderTotalAmount;
/** 订单金额币种;金额为 0 时该字段可能为空。 */
@JsonProperty("order_total_currency_code")
private String orderTotalCurrencyCode;
/** 配送方式:AFN(亚马逊)/ MFN(自发货)。 */
@JsonProperty("fulfillment_channel")
private String fulfillmentChannel;
/** 邮编。 */
@JsonProperty("postal_code")
private String postalCode;
/** 销售渠道,如 Amazon.com。 */
@JsonProperty("sales_channel")
private String salesChannel;
/** 订购时间,亚马逊原始格式,如 {@code 2020-11-07T03:25:38Z}。 */
@JsonProperty("purchase_date")
private String purchaseDate;
/** 订购时间(UTC),{@code yyyy-MM-dd HH:mm:ss}。 */
@JsonProperty("purchase_date_utc")
private String purchaseDateUtc;
/** 订购时间(站点时间),{@code yyyy-MM-dd HH:mm:ss}。 */
@JsonProperty("purchase_date_local")
private String purchaseDateLocal;
/** 订单更新时间(站点时间)。 */
@JsonProperty("last_update_date")
private String lastUpdateDate;
/** 订单更新时间(UTC)。 */
@JsonProperty("last_update_date_utc")
private String lastUpdateDateUtc;
/** 订单修改时间(北京时间)。 */
@JsonProperty("gmt_modified")
private String gmtModified;
/** 订单修改时间(UTC)。 */
@JsonProperty("gmt_modified_utc")
private String gmtModifiedUtc;
/** 退款金额;文档类型是 number。 */
@JsonProperty("refund_amount")
private String refundAmount;
/** 商品明细。 */
@JsonProperty("item_list")
private List<AmazonOrderItemDto> itemList = new ArrayList<AmazonOrderItemDto>();
}

38
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonOrderItemDto.java

@ -0,0 +1,38 @@ @@ -0,0 +1,38 @@
package common.ecommerce.lingxing.platform.amazon.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
/**
* 领星 · 亚马逊 SC 订单列表的商品行({@code data[].item_list[]})。
*
* <p>只有 SKU / ASIN / 数量,金额字段在订单详情接口里。文档写
* {@code quantity_ordered} 是 string,但真实响应可能是 number,
* 用 String 接收两种都能读。</p>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class AmazonOrderItemDto {
@JsonProperty("asin")
private String asin;
/** 数量;文档类型是 string,真实响应可能是 number。 */
@JsonProperty("quantity_ordered")
private String quantityOrdered;
/** 平台 MSKU。 */
@JsonProperty("seller_sku")
private String sellerSku;
/** 领星本地 SKU。 */
@JsonProperty("local_sku")
private String localSku;
/** 本地品名。 */
@JsonProperty("local_name")
private String localName;
}

134
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/AmazonSettlementTransactionDto.java

@ -0,0 +1,134 @@ @@ -0,0 +1,134 @@
package common.ecommerce.lingxing.platform.amazon.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
/**
* 领星 · 亚马逊结算中心交易明细({@code data.records[]})。
*
* <p>一行是一笔费用(佣金、配送费、退款、广告费……),不是订单合计。
* 金额为负数表示扣款。</p>
*
* <p>这里只保留对账需要的主干字段,其余字段(税费模型、促销 ID 等)
* 在需要时再补,避免 DTO 跟着文档无限膨胀。</p>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class AmazonSettlementTransactionDto {
/** 交易明细唯一标识;未结算时可能为空。 */
@JsonProperty("uniqueKey")
private String uniqueKey;
/** 主键编号,非唯一键。 */
@JsonProperty("id")
private String id;
/** 记录 MD5,兜底标识。 */
@JsonProperty("md5")
private String md5;
/** 亚马逊订单号。 */
@JsonProperty("amazonOrderId")
private String amazonOrderId;
/** 领星店铺 id。 */
@JsonProperty("sid")
private Long sid;
@JsonProperty("storeName")
private String storeName;
/** 亚马逊店铺 id。 */
@JsonProperty("sellerId")
private String sellerId;
/** 国家。 */
@JsonProperty("countryCode")
private String countryCode;
/** 报告类型,如 Standard。 */
@JsonProperty("accountType")
private String accountType;
/** 配送方式,如 FBA / FBM。 */
@JsonProperty("fulfillment")
private String fulfillment;
/** 来源事件,如 Shipment / Refund / ServiceFee。 */
@JsonProperty("eventType")
private String eventType;
/** 平台 MSKU。 */
@JsonProperty("sellerSku")
private String sellerSku;
/** 交易类型,如 Commission / Tax / Refund。 */
@JsonProperty("type")
private String type;
/** 结算时间(站点时间,带偏移),如 {@code 2022-09-10T23:55:12+01:00}。 */
@JsonProperty("postedDateLocale")
private String postedDateLocale;
/** 结算日期,0 时区,如 {@code 2024-06-06T08:29:00Z}。 */
@JsonProperty("postedDate")
private String postedDate;
/** 币种。 */
@JsonProperty("currencyCode")
private String currencyCode;
/** 金额;文档类型是 number,用 String 兼容。 */
@JsonProperty("currencyAmount")
private String currencyAmount;
@JsonProperty("quantity")
private Integer quantity;
/** 结算状态:Open 未结算 / Closed 已结算 / Reconciled 已对账。 */
@JsonProperty("processingStatus")
private String processingStatus;
/** 转账状态:Succeeded / Processing / Failed / Unknown。 */
@JsonProperty("fundTransferStatus")
private String fundTransferStatus;
/** 结算编号。 */
@JsonProperty("fid")
private String fid;
@JsonProperty("settlementId")
private String settlementId;
/** 领星本地 SKU。 */
@JsonProperty("localSku")
private String localSku;
/** 领星本地品名。 */
@JsonProperty("localName")
private String localName;
/** 修改时间(领星系统时间)。 */
@JsonProperty("gmtModified")
private String gmtModified;
/** 商家订单 ID。 */
@JsonProperty("merchantOrderId")
private String merchantOrderId;
@JsonProperty("marketplaceName")
private String marketplaceName;
@JsonProperty("asin")
private String asin;
@JsonProperty("fnsku")
private String fnsku;
@JsonProperty("orderItemId")
private String orderItemId;
}

111
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/FbmOrderDetailDto.java

@ -0,0 +1,111 @@ @@ -0,0 +1,111 @@
package common.ecommerce.lingxing.platform.amazon.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;
/**
* 领星 · 亚马逊 FBM 订单详情
* ({@code /erp/sc/routing/order/Order/getOrderDetail} 的 {@code data})。
*
* <p>注意 {@code data} 是对象,不是数组。</p>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FbmOrderDetailDto {
/** 领星系统单号。 */
@JsonProperty("order_number")
private String orderNumber;
/** 订单状态(中文原值)。 */
@JsonProperty("order_status")
private String orderStatus;
@JsonProperty("order_from_name")
private String orderFromName;
/** 订购时间。 */
@JsonProperty("purchase_time")
private String purchaseTime;
/** 平台,如 AMAZON。 */
@JsonProperty("platform")
private String platform;
@JsonProperty("shop_name")
private String shopName;
@JsonProperty("buyer_choose_express")
private String buyerChooseExpress;
/** 客付运费。 */
@JsonProperty("total_shipping_price")
private String totalShippingPrice;
@JsonProperty("buyer_message")
private String buyerMessage;
@JsonProperty("customer_comment")
private String customerComment;
@JsonProperty("warehouse_name")
private String warehouseName;
@JsonProperty("wid")
private Long wid;
@JsonProperty("tracking_number")
private String trackingNumber;
@JsonProperty("logistics_type_name")
private String logisticsTypeName;
@JsonProperty("logistics_provider_name")
private String logisticsProviderName;
@JsonProperty("logistics_type_id")
private Long logisticsTypeId;
@JsonProperty("logistics_provider_id")
private Long logisticsProviderId;
@JsonProperty("logistics_pre_weight")
private String logisticsPreWeight;
@JsonProperty("logistics_pre_weight_unit")
private String logisticsPreWeightUnit;
@JsonProperty("logistics_pre_price")
private String logisticsPrePrice;
/** 物流运费。 */
@JsonProperty("logistics_freight")
private String logisticsFreight;
@JsonProperty("logistics_freight_currency_code")
private String logisticsFreightCurrencyCode;
@JsonProperty("pkg_real_weight")
private String pkgRealWeight;
@JsonProperty("pkg_real_weight_unit")
private String pkgRealWeightUnit;
/** 订单总金额;文档没给币种,按商品行币种解释。 */
@JsonProperty("order_price_amount")
private String orderPriceAmount;
/** 订单毛利润。 */
@JsonProperty("gross_profit_amount")
private String grossProfitAmount;
/** 订单商品行。 */
@JsonProperty("order_item")
private List<FbmOrderItemDto> orderItem = new ArrayList<FbmOrderItemDto>();
}

66
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/FbmOrderDto.java

@ -0,0 +1,66 @@ @@ -0,0 +1,66 @@
package common.ecommerce.lingxing.platform.amazon.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
/**
* 领星 · 亚马逊 FBM 订单列表条目
* ({@code /erp/sc/routing/order/Order/getOrderList} 的 {@code data[]})。
*
* <p>这是领星 ERP「销售 &gt; 订单管理」的自发货订单视图,主键是系统单号
* {@code order_number},不是亚马逊订单号;平台单号在 {@code platform_list} 里,
* 当前不解析(避免数组元素类型不一致导致整页解析失败)。</p>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FbmOrderDto {
/** 领星系统单号,详情接口的入参。 */
@JsonProperty("order_number")
private String orderNumber;
/** 订单状态(中文原值,如 待发货 / 已发货 / 已取消)。 */
@JsonProperty("status")
private String status;
/** 订单类型,如 线上订单 / 手工订单。 */
@JsonProperty("order_from")
private String orderFrom;
/** 目的国代码。 */
@JsonProperty("country_code")
private String countryCode;
/** 订购时间。 */
@JsonProperty("purchase_time")
private String purchaseTime;
/** 付款时间。 */
@JsonProperty("payment_time")
private String paymentTime;
@JsonProperty("logistics_type_id")
private String logisticsTypeId;
@JsonProperty("logistics_provider_id")
private String logisticsProviderId;
@JsonProperty("logistics_type_name")
private String logisticsTypeName;
@JsonProperty("logistics_provider_name")
private String logisticsProviderName;
/** 发货仓库 id。 */
@JsonProperty("wid")
private Long wid;
@JsonProperty("warehouse_name")
private String warehouseName;
@JsonProperty("customer_comment")
private String customerComment;
}

55
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/dto/FbmOrderItemDto.java

@ -0,0 +1,55 @@ @@ -0,0 +1,55 @@
package common.ecommerce.lingxing.platform.amazon.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
/**
* 领星 · 亚马逊 FBM 订单详情的商品行({@code data.order_item[]})。
*
* <p>字段名 {@code MSKU} 是全大写,Jackson 按注解原样匹配;数量字段文档写作
* {@code quality}(不是 quantity),照文档保留。</p>
*/
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FbmOrderItemDto {
/** 平台订单号。 */
@JsonProperty("platform_order_id")
private String platformOrderId;
/** 平台 MSKU。 */
@JsonProperty("MSKU")
private String msku;
/** 订单明细单号。 */
@JsonProperty("order_item_no")
private String orderItemNo;
@JsonProperty("pic_url")
private String picUrl;
/** 领星本地 SKU。 */
@JsonProperty("sku")
private String sku;
@JsonProperty("product_name")
private String productName;
/** 数量;文档字段名是 {@code quality}。 */
@JsonProperty("quality")
private Integer quality;
/** 单价。 */
@JsonProperty("item_unit_price")
private String itemUnitPrice;
/** 单价币种。 */
@JsonProperty("currency_code")
private String currencyCode;
@JsonProperty("customization")
private String customization;
}

298
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/order/AmazonFbmOrderSource.java

@ -0,0 +1,298 @@ @@ -0,0 +1,298 @@
package common.ecommerce.lingxing.platform.amazon.order;
import com.fasterxml.jackson.databind.JsonNode;
import common.ecommerce.error.ChannelException;
import common.ecommerce.error.ValidationException;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpResponse;
import common.ecommerce.lingxing.LingxingApi;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.lingxing.http.LingxingEnvelope;
import common.ecommerce.lingxing.mapper.LingxingOrderMapper;
import common.ecommerce.lingxing.platform.LingxingCall;
import common.ecommerce.lingxing.platform.amazon.dto.FbmOrderDetailDto;
import common.ecommerce.lingxing.platform.amazon.dto.FbmOrderDto;
import common.ecommerce.lingxing.platform.amazon.dto.FbmOrderItemDto;
import common.ecommerce.lingxing.platform.order.LingxingOrderSource;
import common.ecommerce.model.ChannelProvider;
import common.ecommerce.model.account.ChannelAccount;
import common.ecommerce.model.order.OrderLine;
import common.ecommerce.model.order.SalesOrder;
import common.ecommerce.model.order.SalesOrderQuery;
import common.ecommerce.model.support.Money;
import common.ecommerce.model.support.Page;
import common.ecommerce.model.support.PlatformTime;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 领星 · 亚马逊 FBM(自发货)路由订单。
*
* <p>对应领星 ERP「销售 &gt; 订单管理」,与 {@link AmazonOrderSource}
* ({@code /erp/sc/data/mws/orders})是两个不同视角:</p>
* <ul>
* <li>本类的主键是<b>领星系统单号</b> {@code order_number},详情接口也按它查;
* 平台订单号在 {@code platform_list} 里</li>
* <li>{@link AmazonOrderSource} 的主键是亚马逊订单号,字段更全(币种、金额、UTC 时间)</li>
* </ul>
*
* <p>两者不要混用同一个 canonicalKey 存储:需要跨渠道去重时用
* {@link AmazonOrderSource},需要按领星系统单号查 FBM 作业数据时用本类。</p>
*
* <p><b>时区待核对</b>:文档没有标注 {@code purchase_time} 的时区,
* 这里按领星 ERP 系统时间(北京时间)解析。首次真实联调时应打印报文确认。</p>
*/
public final class AmazonFbmOrderSource implements LingxingOrderSource {
/** 接口时间格式。 */
private static final DateTimeFormatter DATE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/** 文档未注明时区,按 ERP 系统时间(北京时间)解释,待真实报文核对。 */
private static final ZoneId SYSTEM_ZONE = PlatformTime.BEIJING_ZONE;
private static final String OP_PULL = "salesOrders.pull.fbm";
private static final String OP_GET = "salesOrders.get.fbm";
@Override
public Page<SalesOrder> orders(LingxingCall call, SalesOrderQuery query) {
ChannelAccount account = call.ctx().account();
ZoneId zone = ZoneId.of(account.marketplaceZone());
String sid = requireSid(account, call);
int length = Math.min(query.pageSize() <= 0 ? 100 : query.pageSize(),
LingxingConstants.FBM_MAX_PAGE_SIZE);
int page = query.cursor() == null ? 1 : Integer.parseInt(query.cursor());
Instant from = query.updatedAfter();
Instant to = query.updatedBefore() != null ? query.updatedBefore() : Instant.now(call.ctx().clock());
Map<String, Object> body = new LinkedHashMap<String, Object>();
body.put("sid", sid);
body.put("page", page);
body.put("length", length);
body.put("start_time", systemTime(from));
body.put("end_time", systemTime(to));
HttpRequest req = call.signed(LingxingApi.ORDER_LIST_FBM_AMAZON_SC, body, OP_PULL);
HttpResponse resp = call.execute(req);
LingxingEnvelope envelope = call.envelope(resp, OP_PULL);
List<FbmOrderDto> dtos = call.json().listAt(envelope.body(), "data", FbmOrderDto.class);
List<SalesOrder> orders = new ArrayList<SalesOrder>(dtos.size());
for (FbmOrderDto dto : dtos) {
try {
orders.add(toSalesOrder(dto, account, zone));
} catch (RuntimeException e) {
throw mappingFailure(e, envelope, call, OP_PULL);
}
}
// page 从 1 开始;满页才可能有下一页,total 存在时再用它兜底
int nextPage = page + 1;
boolean hasMore = dtos.size() >= length
&& (envelope.total() < 0 || (long) page * length < envelope.total());
return Page.of(orders, hasMore ? String.valueOf(nextPage) : null);
}
@Override
public SalesOrder order(LingxingCall call, String channelOrderId) {
ChannelAccount account = call.ctx().account();
ZoneId zone = ZoneId.of(account.marketplaceZone());
Map<String, Object> body = new LinkedHashMap<String, Object>();
// 详情接口按领星系统单号查,不是平台订单号
body.put("order_number", channelOrderId);
HttpRequest req = call.signed(LingxingApi.ORDER_DETAIL_FBM_AMAZON_SC, body, OP_GET);
HttpResponse resp = call.execute(req);
LingxingEnvelope envelope = call.envelope(resp, OP_GET);
// data 是对象,不是数组
JsonNode data = call.json().nodeAt(envelope.body(), "data");
if (data == null || data.isNull()) {
throw ChannelException.builder()
.message("lingxing fbm order not found: " + channelOrderId)
.operation(OP_GET)
.provider(ChannelProvider.LINGXING.name())
.omsStoreId(call.ctx().omsStoreId())
.requestId(call.ctx().requestId())
.platformCode(channelOrderId)
.retryable(false)
.rawResponse(envelope.body())
.build();
}
FbmOrderDetailDto dto = call.json().mapper().convertValue(data, FbmOrderDetailDto.class);
try {
return toSalesOrder(dto, account, zone);
} catch (RuntimeException e) {
throw mappingFailure(e, envelope, call, OP_GET);
}
}
// ---------------------------------------------------------------- mapping
/** 列表条目:没有商品行与金额,商品明细要再调详情。 */
private SalesOrder toSalesOrder(FbmOrderDto dto, ChannelAccount account, ZoneId zone) {
String orderNumber = requireOrderNumber(dto.getOrderNumber());
Instant occur = systemTime(dto.getPurchaseTime());
return SalesOrder.builder()
.omsStoreId(account.omsStoreId())
.channelOrderId(orderNumber)
.status(dto.getStatus())
// FBM 列表不返回买家姓名;国家有
.buyerName(null)
.shipToCountryCode(trimToNull(dto.getCountryCode()))
.lines(Collections.<OrderLine>emptyList())
// 列表接口不返回订单金额
.totalAmount(null)
.occurredAt(requireOccurredAt(occur, orderNumber, zone))
.sourceProvider(ChannelProvider.LINGXING)
.sourceAccountId(null)
.build();
}
/** 详情条目:带商品行与金额。 */
private SalesOrder toSalesOrder(FbmOrderDetailDto dto, ChannelAccount account, ZoneId zone) {
String orderNumber = requireOrderNumber(dto.getOrderNumber());
Instant occur = systemTime(dto.getPurchaseTime());
List<FbmOrderItemDto> items = safe(dto.getOrderItem());
List<OrderLine> lines = new ArrayList<OrderLine>(items.size());
String firstCurrency = null;
for (int i = 0; i < items.size(); i++) {
FbmOrderItemDto item = items.get(i);
String currency = trimToNull(item.getCurrencyCode());
if (firstCurrency == null) {
firstCurrency = currency;
}
String sku = firstNonBlank(item.getMsku(), item.getSku(), item.getPlatformOrderId());
lines.add(OrderLine.builder()
.lineId(firstNonBlank(item.getOrderItemNo(), item.getPlatformOrderId(),
item.getSku(), "line-" + i))
.platformSku(sku == null ? "" : sku)
.quantity(item.getQuality() == null ? 0 : item.getQuality())
.unitPrice(moneyOrNull(item.getItemUnitPrice(), currency))
.build());
}
// 订单总金额没有独立币种,按商品行币种解释;没有商品行时用账户币种
String totalCurrency = firstNonBlank(firstCurrency, account.currency());
return SalesOrder.builder()
.omsStoreId(account.omsStoreId())
.channelOrderId(orderNumber)
.status(dto.getOrderStatus())
.buyerName(null)
.shipToCountryCode(null)
.lines(lines)
.totalAmount(moneyOrNull(dto.getOrderPriceAmount(), totalCurrency))
.occurredAt(requireOccurredAt(occur, orderNumber, zone))
.sourceProvider(ChannelProvider.LINGXING)
.sourceAccountId(null)
.build();
}
// ---------------------------------------------------------------- internals
/** 文档没写时区,按 {@link #SYSTEM_ZONE} 解释;缺失或格式不对返回 null。 */
private static Instant systemTime(String value) {
String text = trimToNull(value);
if (text == null) {
return null;
}
try {
return LocalDateTime.parse(text, DATE_TIME).atZone(SYSTEM_ZONE).toInstant();
} catch (DateTimeParseException e) {
return null;
}
}
private static String systemTime(Instant instant) {
return DATE_TIME.format(LocalDateTime.ofInstant(instant, SYSTEM_ZONE));
}
private static PlatformTime requireOccurredAt(Instant occur, String orderNumber, ZoneId zone) {
if (occur == null) {
throw new IllegalArgumentException(
"lingxing fbm order has no parseable purchase_time: " + orderNumber);
}
return PlatformTime.of(occur, zone);
}
private static String requireOrderNumber(String value) {
String orderNumber = trimToNull(value);
if (orderNumber == null) {
throw new IllegalArgumentException("lingxing fbm order has no order_number");
}
return orderNumber;
}
/** FBM 列表必填 sid,且是领星店铺 id;缺失时直接拒绝,不发注定失败的请求。 */
private static String requireSid(ChannelAccount account, LingxingCall call) {
String sid = trimToNull(account.externalStoreId());
if (sid != null) {
return sid;
}
throw new ValidationException(ChannelException.builder()
.message("lingxing fbm order query requires externalStoreId (sid)")
.operation(OP_PULL)
.provider(ChannelProvider.LINGXING.name())
.omsStoreId(call.ctx().omsStoreId())
.requestId(call.ctx().requestId())
.retryable(false));
}
private static ValidationException mappingFailure(RuntimeException e, LingxingEnvelope envelope,
LingxingCall call, String operation) {
return new ValidationException(ChannelException.builder()
.message("lingxing fbm order mapping failed: " + e.getMessage())
.operation(operation)
.provider(ChannelProvider.LINGXING.name())
.omsStoreId(call.ctx().omsStoreId())
.requestId(call.ctx().requestId())
.rawResponse(envelope.body()), e);
}
private static Money moneyOrNull(String value, String currency) {
String cleaned = LingxingOrderMapper.cleanAmount(value);
if (cleaned == null || trimToNull(currency) == null) {
return null;
}
return Money.of(cleaned, currency.trim().toUpperCase());
}
private static <T> List<T> safe(List<T> in) {
return in == null ? Collections.<T>emptyList() : in;
}
private static String firstNonBlank(String... values) {
for (String value : values) {
String trimmed = trimToNull(value);
if (trimmed != null) {
return trimmed;
}
}
return null;
}
private static String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
}

370
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/order/AmazonOrderSource.java

@ -0,0 +1,370 @@ @@ -0,0 +1,370 @@
package common.ecommerce.lingxing.platform.amazon.order;
import common.ecommerce.error.ChannelException;
import common.ecommerce.error.ValidationException;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpResponse;
import common.ecommerce.lingxing.LingxingApi;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.lingxing.http.LingxingEnvelope;
import common.ecommerce.lingxing.mapper.LingxingOrderMapper;
import common.ecommerce.lingxing.platform.LingxingCall;
import common.ecommerce.lingxing.platform.amazon.dto.AmazonOrderDetailDto;
import common.ecommerce.lingxing.platform.amazon.dto.AmazonOrderDetailItemDto;
import common.ecommerce.lingxing.platform.amazon.dto.AmazonOrderDto;
import common.ecommerce.lingxing.platform.amazon.dto.AmazonOrderItemDto;
import common.ecommerce.lingxing.platform.order.LingxingOrderSource;
import common.ecommerce.model.ChannelProvider;
import common.ecommerce.model.account.ChannelAccount;
import common.ecommerce.model.order.OrderLine;
import common.ecommerce.model.order.SalesOrder;
import common.ecommerce.model.order.SalesOrderQuery;
import common.ecommerce.model.support.Money;
import common.ecommerce.model.support.Page;
import common.ecommerce.model.support.PlatformTime;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 领星 · 亚马逊 SC 订单。
*
* <p>列表 {@link LingxingApi#ORDER_LIST_AMAZON_SC}:POST,{@code offset}/{@code length}
* 分页(上限 5000),查询窗口不超过 1 年,{@code total} 在<b>顶层</b>。</p>
*
* <p>详情 {@link LingxingApi#ORDER_DETAIL_AMAZON_SC}:只有详情返回单价/税额/折扣,
* 列表接口没有这些字段。</p>
*
* <p>与多平台订单的区别:状态是字符串枚举、时间是字符串、{@code data} 直接是数组。
* 因此不复用 {@link LingxingOrderMapper},只复用它的金额清洗规则。</p>
*/
public final class AmazonOrderSource implements LingxingOrderSource {
/** 亚马逊接口时间参数格式:{@code yyyy-MM-dd HH:mm:ss}(UTC)。 */
private static final DateTimeFormatter DATE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/** {@code date_type=3}:平台更新时间(UTC),与 updatedAfter/updatedBefore 语义一致。 */
private static final int DATE_TYPE_PLATFORM_UPDATE_UTC = 3;
private static final String OP_PULL = "salesOrders.pull.amazon";
private static final String OP_GET = "salesOrders.get.amazon";
@Override
public Page<SalesOrder> 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());
// 亚马逊查询窗口 ≤1 年;超出时截断,由 SyncEngine 分段推进
if (Duration.between(from, to).toDays() > LingxingConstants.AMAZON_MAX_QUERY_DAYS) {
from = to.minus(Duration.ofDays(LingxingConstants.AMAZON_MAX_QUERY_DAYS));
}
int length = Math.min(query.pageSize() <= 0 ? 100 : query.pageSize(),
LingxingConstants.AMAZON_MAX_PAGE_SIZE);
int offset = query.cursor() == null ? 0 : Integer.parseInt(query.cursor());
Map<String, Object> body = new LinkedHashMap<String, Object>();
body.put("start_date", utc(from));
body.put("end_date", utc(to));
body.put("date_type", DATE_TYPE_PLATFORM_UPDATE_UTC);
body.put("offset", offset);
body.put("length", length);
Long sid = parseSid(account.externalStoreId());
if (sid != null) {
body.put("sid", sid);
}
HttpRequest req = call.signed(LingxingApi.ORDER_LIST_AMAZON_SC, body, OP_PULL);
HttpResponse resp = call.execute(req);
LingxingEnvelope envelope = call.envelope(resp, OP_PULL);
List<AmazonOrderDto> dtos = call.json().listAt(envelope.body(), "data", AmazonOrderDto.class);
List<SalesOrder> orders = new ArrayList<SalesOrder>(dtos.size());
for (AmazonOrderDto dto : dtos) {
try {
orders.add(toSalesOrder(dto, account, zone));
} catch (RuntimeException e) {
throw mappingFailure(e, envelope, call, OP_PULL);
}
}
// 满页才可能有下一页;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);
}
@Override
public SalesOrder order(LingxingCall call, String channelOrderId) {
ChannelAccount account = call.ctx().account();
ZoneId zone = ZoneId.of(account.marketplaceZone());
Map<String, Object> body = new LinkedHashMap<String, Object>();
body.put("order_id", channelOrderId);
HttpRequest req = call.signed(LingxingApi.ORDER_DETAIL_AMAZON_SC, body, OP_GET);
HttpResponse resp = call.execute(req);
LingxingEnvelope envelope = call.envelope(resp, OP_GET);
List<AmazonOrderDetailDto> dtos =
call.json().listAt(envelope.body(), "data", AmazonOrderDetailDto.class);
if (dtos.isEmpty()) {
throw ChannelException.builder()
.message("lingxing amazon order not found: " + channelOrderId)
.operation(OP_GET)
.provider(ChannelProvider.LINGXING.name())
.omsStoreId(call.ctx().omsStoreId())
.requestId(call.ctx().requestId())
.platformCode(channelOrderId)
.retryable(false)
.rawResponse(envelope.body())
.build();
}
try {
return toSalesOrder(dtos.get(0), account, zone);
} catch (RuntimeException e) {
throw mappingFailure(e, envelope, call, OP_GET);
}
}
// ---------------------------------------------------------------- mapping
/** 列表条目:只有 SKU / ASIN / 数量,金额与税额需要再调详情。 */
private SalesOrder toSalesOrder(AmazonOrderDto dto, ChannelAccount account, ZoneId zone) {
String channelOrderId = requireOrderId(dto.getAmazonOrderId());
String currency = firstNonBlank(dto.getOrderTotalCurrencyCode(), account.currency());
List<OrderLine> lines = new ArrayList<OrderLine>();
List<AmazonOrderItemDto> items = safe(dto.getItemList());
for (int i = 0; i < items.size(); i++) {
AmazonOrderItemDto item = items.get(i);
String sku = firstNonBlank(item.getSellerSku(), item.getLocalSku(), item.getAsin());
lines.add(OrderLine.builder()
.lineId(firstNonBlank(item.getSellerSku(), item.getAsin(),
item.getLocalSku(), "line-" + i))
.platformSku(sku == null ? "" : sku)
.quantity(parseInt(item.getQuantityOrdered()))
.build());
}
Instant occur = parsePurchase(dto.getPurchaseDate(), dto.getPurchaseDateUtc(),
dto.getPurchaseDateLocal(), zone);
return SalesOrder.builder()
.omsStoreId(account.omsStoreId())
.channelOrderId(channelOrderId)
.status(dto.getOrderStatus())
// 亚马逊订单列表不返回买家姓名与收货国家
.buyerName(null)
.shipToCountryCode(null)
.lines(lines)
.totalAmount(moneyOrNull(dto.getOrderTotalAmount(), currency))
.occurredAt(requireOccurredAt(occur, channelOrderId, zone))
.sourceProvider(ChannelProvider.LINGXING)
.sourceAccountId(dto.getSid() == null ? null : String.valueOf(dto.getSid()))
.build();
}
/** 详情条目:带完整金额。 */
private SalesOrder toSalesOrder(AmazonOrderDetailDto dto, ChannelAccount account, ZoneId zone) {
String channelOrderId = requireOrderId(dto.getAmazonOrderId());
String currency = firstNonBlank(dto.getCurrency(), account.currency());
List<OrderLine> lines = new ArrayList<OrderLine>();
List<AmazonOrderDetailItemDto> items = safe(dto.getItemList());
for (int i = 0; i < items.size(); i++) {
AmazonOrderDetailItemDto item = items.get(i);
String sku = firstNonBlank(item.getSellerSku(), item.getSku(), item.getAsin());
lines.add(OrderLine.builder()
// order_item_id 亚马逊可能变更,不能当稳定主键;仅作展示用
.lineId(firstNonBlank(item.getOrderItemId(), item.getAsin(),
item.getSellerSku(), "line-" + i))
.platformSku(sku == null ? "" : sku)
.quantity(item.getQuantityOrdered() == null ? 0 : item.getQuantityOrdered())
.unitPrice(moneyOrNull(item.getUnitPriceAmount(), currency))
.tax(moneyOrNull(item.getItemTaxAmount(), currency))
.discount(moneyOrNull(item.getPromotionDiscountAmount(), currency))
.build());
}
// 详情没有原始 ISO 的 purchase_date,优先用 UTC 的 local_utc 字段
Instant occur = parsePurchase(null, dto.getPurchaseDateLocalUtc(),
dto.getPurchaseDateLocal(), zone);
return SalesOrder.builder()
.omsStoreId(account.omsStoreId())
.channelOrderId(channelOrderId)
.status(dto.getOrderStatus())
.buyerName(null)
.shipToCountryCode(null)
.lines(lines)
.totalAmount(moneyOrNull(dto.getOrderTotalAmount(), currency))
.occurredAt(requireOccurredAt(occur, channelOrderId, zone))
.sourceProvider(ChannelProvider.LINGXING)
.sourceAccountId(dto.getSid() == null ? null : String.valueOf(dto.getSid()))
.build();
}
// ---------------------------------------------------------------- internals
/**
* 订购时间按精度回落:亚马逊原始 ISO(带 Z)→ UTC 字符串 → 站点时间字符串。
*/
static Instant parsePurchase(String iso, String utc, String local, ZoneId marketplaceZone) {
Instant instant = parseIso(iso);
if (instant != null) {
return instant;
}
instant = parseUtc(utc);
if (instant != null) {
return instant;
}
return parseLocal(local, marketplaceZone);
}
static Instant parseIso(String value) {
String text = trimToNull(value);
if (text == null) {
return null;
}
try {
return Instant.parse(text);
} catch (DateTimeParseException ignored) {
// 回落 OffsetDateTime,兼容 +00:00 形式
}
try {
return OffsetDateTime.parse(text).toInstant();
} catch (DateTimeParseException e) {
return null;
}
}
static Instant parseUtc(String value) {
String text = trimToNull(value);
if (text == null) {
return null;
}
try {
return LocalDateTime.parse(text, DATE_TIME).toInstant(ZoneOffset.UTC);
} catch (DateTimeParseException ignored) {
// 兼容 ISO 形式
return parseIso(text);
}
}
static Instant parseLocal(String value, ZoneId marketplaceZone) {
String text = trimToNull(value);
if (text == null || marketplaceZone == null) {
return null;
}
try {
return LocalDateTime.parse(text, DATE_TIME).atZone(marketplaceZone).toInstant();
} catch (DateTimeParseException e) {
return null;
}
}
/** {@code occurredAt} 是 SalesOrder 的必填项,缺失时带单号报错,不伪造 1970。 */
private static PlatformTime requireOccurredAt(Instant occur, String channelOrderId, ZoneId zone) {
if (occur == null) {
throw new IllegalArgumentException(
"lingxing amazon order has no purchase time: " + channelOrderId);
}
return PlatformTime.of(occur, zone);
}
private static String requireOrderId(String value) {
String id = trimToNull(value);
if (id == null) {
throw new IllegalArgumentException("lingxing amazon order has no amazon_order_id");
}
return id;
}
private static ValidationException mappingFailure(RuntimeException e, LingxingEnvelope envelope,
LingxingCall call, String operation) {
return new ValidationException(ChannelException.builder()
.message("lingxing amazon order mapping failed: " + e.getMessage())
.operation(operation)
.provider(ChannelProvider.LINGXING.name())
.omsStoreId(call.ctx().omsStoreId())
.requestId(call.ctx().requestId())
.rawResponse(envelope.body()), e);
}
/** 金额为 0 时领星可能不返回币种,此时无法构造 Money,保留 null 而不是造零。 */
private static Money moneyOrNull(String value, String currency) {
String cleaned = LingxingOrderMapper.cleanAmount(value);
if (cleaned == null || currency == null) {
return null;
}
return Money.of(cleaned, currency.toUpperCase());
}
private static int parseInt(String value) {
String text = trimToNull(value);
if (text == null) {
return 0;
}
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return 0;
}
}
/** 亚马逊接口的 {@code sid} 是数字;配置里填了非数字时退化为不按店铺过滤。 */
private static Long parseSid(String externalStoreId) {
String value = trimToNull(externalStoreId);
if (value == null) {
return null;
}
try {
return Long.valueOf(value);
} catch (NumberFormatException e) {
return null;
}
}
private static String utc(Instant instant) {
return DATE_TIME.format(LocalDateTime.ofInstant(instant, ZoneOffset.UTC));
}
private static <T> List<T> safe(List<T> in) {
return in == null ? Collections.<T>emptyList() : in;
}
private static String firstNonBlank(String... values) {
for (String value : values) {
String trimmed = trimToNull(value);
if (trimmed != null) {
return trimmed;
}
}
return null;
}
private static String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
}

259
lingxing/src/main/java/common/ecommerce/lingxing/platform/amazon/settlement/AmazonSettlementSource.java

@ -0,0 +1,259 @@ @@ -0,0 +1,259 @@
package common.ecommerce.lingxing.platform.amazon.settlement;
import common.ecommerce.error.ChannelException;
import common.ecommerce.error.ValidationException;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpResponse;
import common.ecommerce.lingxing.LingxingApi;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.lingxing.http.LingxingEnvelope;
import common.ecommerce.lingxing.mapper.LingxingOrderMapper;
import common.ecommerce.lingxing.platform.LingxingCall;
import common.ecommerce.lingxing.platform.amazon.dto.AmazonSettlementTransactionDto;
import common.ecommerce.lingxing.platform.settlement.LingxingSettlementSource;
import common.ecommerce.model.ChannelProvider;
import common.ecommerce.model.account.ChannelAccount;
import common.ecommerce.model.settlement.SettlementQuery;
import common.ecommerce.model.settlement.SettlementTransaction;
import common.ecommerce.model.support.Money;
import common.ecommerce.model.support.Page;
import common.ecommerce.model.support.PlatformTime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 领星 · 亚马逊结算中心交易明细。
*
* <p>接口 {@link LingxingApi#SETTLEMENT_TRANSACTION_LIST}:POST,{@code offset}/{@code length}
* 分页(上限 10000),令牌桶 10 req/s。</p>
*
* <p>查询窗口规则(官方文档):结算时间 {@code startDate/endDate} 双闭区间、
* 间隔不得超过 7 天;没有搜索值时,结算时间与修改时间二选一必填。
* 修改时间按<b>北京时间</b>传。</p>
*/
public final class AmazonSettlementSource implements LingxingSettlementSource {
/** 结算日期格式。 */
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/** 修改时间格式(北京时间)。 */
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final String OP = "settlements.pull.amazon";
@Override
public Page<SettlementTransaction> transactions(LingxingCall call, SettlementQuery query) {
ChannelAccount account = call.ctx().account();
ZoneId zone = ZoneId.of(account.marketplaceZone());
requireQueryWindow(query, call);
int length = Math.min(query.pageSize() <= 0 ? 100 : query.pageSize(),
LingxingConstants.SETTLEMENT_MAX_PAGE_SIZE);
int offset = query.cursor() == null ? 0 : Integer.parseInt(query.cursor());
Map<String, Object> body = new LinkedHashMap<String, Object>();
body.put("offset", offset);
body.put("length", length);
Long sid = parseSid(account.externalStoreId());
if (sid != null) {
body.put("sids", Collections.singletonList(sid));
}
LocalDate settledStart = query.settledAfter();
LocalDate settledEnd = query.settledBefore();
if (settledStart != null && settledEnd != null) {
// 双闭区间,最长 7 天:起点早于 end-6 时截断
LocalDate earliest = settledEnd.minusDays(LingxingConstants.SETTLEMENT_MAX_QUERY_DAYS - 1L);
if (settledStart.isBefore(earliest)) {
settledStart = earliest;
}
}
if (settledStart != null) {
body.put("startDate", DATE.format(settledStart));
}
if (settledEnd != null) {
body.put("endDate", DATE.format(settledEnd));
}
// 请求字段明确是北京时间,不能用 UTC 或站点时区
if (query.modifiedAfter() != null) {
body.put("gmtModifiedStart", DATE_TIME.format(
LocalDateTime.ofInstant(query.modifiedAfter(), PlatformTime.BEIJING_ZONE)));
}
if (query.modifiedBefore() != null) {
body.put("gmtModifiedEnd", DATE_TIME.format(
LocalDateTime.ofInstant(query.modifiedBefore(), PlatformTime.BEIJING_ZONE)));
}
if (query.eventType() != null) {
body.put("eventType", query.eventType());
}
if (query.transactionType() != null) {
body.put("type", query.transactionType());
}
if (query.searchField() != null) {
body.put("searchField", query.searchField());
}
if (!query.searchValues().isEmpty()) {
body.put("searchValue", query.searchValues());
}
HttpRequest req = call.signed(LingxingApi.SETTLEMENT_TRANSACTION_LIST, body, OP);
HttpResponse resp = call.execute(req);
LingxingEnvelope envelope = call.envelope(resp, OP);
List<AmazonSettlementTransactionDto> records =
call.json().listAt(envelope.body(), "data.records", AmazonSettlementTransactionDto.class);
List<SettlementTransaction> out = new ArrayList<SettlementTransaction>(records.size());
for (AmazonSettlementTransactionDto dto : records) {
try {
out.add(toTransaction(dto, account, zone));
} catch (RuntimeException e) {
throw new ValidationException(ChannelException.builder()
.message("lingxing settlement mapping failed: " + e.getMessage())
.operation(OP)
.provider(ChannelProvider.LINGXING.name())
.omsStoreId(call.ctx().omsStoreId())
.requestId(call.ctx().requestId())
.rawResponse(envelope.body()), e);
}
}
int nextOffset = offset + records.size();
boolean hasMore = records.size() >= length
&& (envelope.total() < 0 || nextOffset < envelope.total());
return Page.of(out, hasMore ? String.valueOf(nextOffset) : null);
}
// ---------------------------------------------------------------- mapping
private SettlementTransaction toTransaction(AmazonSettlementTransactionDto dto,
ChannelAccount account, ZoneId zone) {
String key = firstNonBlank(dto.getUniqueKey(), dto.getMd5(), dto.getId());
if (key == null) {
throw new IllegalArgumentException(
"settlement record has neither uniqueKey, md5 nor id: " + dto.getAmazonOrderId());
}
return SettlementTransaction.builder()
.omsStoreId(account.omsStoreId())
.transactionKey(key)
.sourceProvider(ChannelProvider.LINGXING)
.sourceAccountId(dto.getSid() == null ? null : String.valueOf(dto.getSid()))
.channelOrderId(trimToNull(dto.getAmazonOrderId()))
.storeName(trimToNull(dto.getStoreName()))
.countryCode(trimToNull(dto.getCountryCode()))
.fulfillment(trimToNull(dto.getFulfillment()))
.eventType(trimToNull(dto.getEventType()))
.transactionType(trimToNull(dto.getType()))
.sellerSku(trimToNull(dto.getSellerSku()))
.localSku(trimToNull(dto.getLocalSku()))
.asin(trimToNull(dto.getAsin()))
.amount(moneyOrNull(dto.getCurrencyAmount(), dto.getCurrencyCode()))
.quantity(dto.getQuantity() == null ? 0 : dto.getQuantity())
.processingStatus(trimToNull(dto.getProcessingStatus()))
.fundTransferStatus(trimToNull(dto.getFundTransferStatus()))
.settlementId(firstNonBlank(dto.getSettlementId(), dto.getFid()))
.postedAt(postedAt(dto.getPostedDate(), dto.getPostedDateLocale(), zone))
.marketplaceName(trimToNull(dto.getMarketplaceName()))
.build();
}
/** 结算时间优先用 0 时区的 postedDate,缺失时回落站点时间 postedDateLocale。 */
static PlatformTime postedAt(String utc, String locale, ZoneId zone) {
Instant instant = parseInstant(utc);
if (instant == null) {
instant = parseInstant(locale);
}
return instant == null ? null : PlatformTime.of(instant, zone);
}
private static Instant parseInstant(String value) {
String text = trimToNull(value);
if (text == null) {
return null;
}
try {
// postedDate: 2024-06-06T08:29:00Z
return Instant.parse(text);
} catch (DateTimeParseException ignored) {
// postedDateLocale: 2022-09-10T23:55:12+01:00
}
try {
return OffsetDateTime.parse(text).toInstant();
} catch (DateTimeParseException e) {
return null;
}
}
private static Money moneyOrNull(String amount, String currency) {
String cleaned = LingxingOrderMapper.cleanAmount(amount);
if (cleaned == null || trimToNull(currency) == null) {
return null;
}
return Money.of(cleaned, currency.trim().toUpperCase());
}
// ---------------------------------------------------------------- internals
/**
* 文档要求:没有搜索值时,「结算时间」与「修改时间」二选一必填。
* 在发请求前显式校验,避免拿一个必然失败的请求去烧配额。
*/
private static void requireQueryWindow(SettlementQuery query, LingxingCall call) {
boolean hasSettled = query.settledAfter() != null || query.settledBefore() != null;
boolean hasModified = query.modifiedAfter() != null || query.modifiedBefore() != null;
if (hasSettled || hasModified || !query.searchValues().isEmpty()) {
return;
}
throw new ValidationException(ChannelException.builder()
.message("lingxing settlement query requires settled window, modified window or searchValues")
.operation(OP)
.provider(ChannelProvider.LINGXING.name())
.omsStoreId(call.ctx().omsStoreId())
.requestId(call.ctx().requestId())
.retryable(false));
}
private static Long parseSid(String externalStoreId) {
String value = trimToNull(externalStoreId);
if (value == null) {
return null;
}
try {
return Long.valueOf(value);
} catch (NumberFormatException e) {
return null;
}
}
private static String firstNonBlank(String... values) {
for (String value : values) {
String trimmed = trimToNull(value);
if (trimmed != null) {
return trimmed;
}
}
return null;
}
private static String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
}

18
lingxing/src/main/java/common/ecommerce/lingxing/platform/settlement/LingxingSettlementSource.java

@ -0,0 +1,18 @@ @@ -0,0 +1,18 @@
package common.ecommerce.lingxing.platform.settlement;
import common.ecommerce.lingxing.platform.LingxingCall;
import common.ecommerce.model.settlement.SettlementQuery;
import common.ecommerce.model.settlement.SettlementTransaction;
import common.ecommerce.model.support.Page;
/**
* 子平台的结算 / 账单能力。
*
* <p>只负责「拼请求体 + 解析响应」;限流、取 token、签名、业务码校验由
* {@link LingxingCall} 提供。</p>
*/
public interface LingxingSettlementSource {
/** 分页拉取结算交易明细。 */
Page<SettlementTransaction> transactions(LingxingCall call, SettlementQuery query);
}

216
lingxing/src/test/java/common/ecommerce/lingxing/adapter/LingxingLiveSmokeTest.java

@ -1,19 +1,23 @@ @@ -1,19 +1,23 @@
package common.ecommerce.lingxing.adapter;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.lingxing.auth.LingxingTokenClient;
import common.ecommerce.capability.AggregatorCapable.SubChannel;
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.model.account.AccountKey;
import common.ecommerce.model.account.ChannelAccount;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.lingxing.auth.LingxingTokenClient;
import common.ecommerce.model.ChannelProvider;
import common.ecommerce.model.support.Page;
import common.ecommerce.model.Platform;
import common.ecommerce.model.account.AccountKey;
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.settlement.SettlementQuery;
import common.ecommerce.model.settlement.SettlementTransaction;
import common.ecommerce.model.support.Page;
import common.ecommerce.sdk.ChannelConnection;
import common.ecommerce.sdk.ChannelContext;
import common.ecommerce.spi.AccessToken;
@ -25,11 +29,11 @@ import org.junit.jupiter.api.Test; @@ -25,11 +29,11 @@ import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.LocalDate;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 领星真实环境冒烟测试。
@ -54,7 +58,7 @@ class LingxingLiveSmokeTest { @@ -54,7 +58,7 @@ class LingxingLiveSmokeTest {
private static final String STORE_ID = "在这里填 store_id";
// ================================================
/** 10008 = Walmart;TikTok 10011、eBay 10003、Amazon 10001,按需改。 */
/** 10008 = Walmart;TikTok 10011、eBay 10003、Amazon SC 10001,按需改。 */
private static final int PLATFORM_CODE = 10008;
private static final String BASE_URL = LingxingConstants.PRODUCTION_BASE_URL;
@ -66,20 +70,19 @@ class LingxingLiveSmokeTest { @@ -66,20 +70,19 @@ class LingxingLiveSmokeTest {
/** 第 1 步:只验证认证。失败说明 AppID/AppSecret 不对,或 IP 不在白名单。 */
@Test
void tokenCanBeFetched() {
requireConfigured();
requireCredentials();
AccessToken token = new LingxingTokenClient(transport, json, Clock.systemUTC())
.fetch(BASE_URL, APP_KEY, APP_SECRET);
System.out.println("[token] " + token.fingerprint() + " expiresAt=" + token.expiresAt());
assertNotNull(token.value());
}
/** 第 2 步:拉一页订单,打印请求与解析结果,人工核对字段映射。 */
/** 第 2 步(多平台):拉一页订单,打印请求与解析结果,人工核对字段映射。 */
@Test
void pullsOnePageOfOrders() {
requireConfigured();
LingxingAdapter adapter = adapter();
ChannelContext ctx = ChannelContext.of(account(), connection(),
"smoke-" + System.currentTimeMillis(), Clock.systemUTC());
ChannelContext ctx = context(account(), "smoke-");
Instant to = Instant.now();
Instant from = to.minus(Duration.ofDays(2));
@ -103,32 +106,203 @@ class LingxingLiveSmokeTest { @@ -103,32 +106,203 @@ class LingxingLiveSmokeTest {
assertFalse(page.size() > 20, "pageSize 未被平台遵守");
}
/**
* 第 3 步(亚马逊 SC):先列店铺拿 sid,再拉订单列表,最后取一单详情核对金额。
*
* <p>不依赖 STORE_ID:sid 来自 {@code /erp/sc/data/seller/lists}。</p>
*/
@Test
void listsAmazonShopsAndPullsOrders() {
requireCredentials();
LingxingAdapter adapter = adapter();
String sid = firstAmazonShopSid(adapter);
if (sid == null) {
return;
}
ChannelContext ctx = context(amazonAccount(sid), "smoke-amazon-orders-");
Instant to = Instant.now();
Instant from = to.minus(Duration.ofDays(2));
Page<SalesOrder> page = adapter.pull(ctx, SalesOrderQuery.builder()
.updatedAfter(from)
.updatedBefore(to)
.pageSize(20)
.build());
System.out.println("[amazon orders] sid=" + sid
+ " window=" + from + " .. " + to
+ " items=" + page.size() + " nextCursor=" + page.nextCursor());
for (SalesOrder o : page.items()) {
System.out.println(" " + o.channelOrderId()
+ " status=" + o.status()
+ " total=" + o.totalAmount()
+ " lines=" + o.lines().size()
+ " utc=" + o.occurredAt().utc());
}
if (page.items().isEmpty()) {
System.out.println("[amazon orders] 窗口内没有订单,跳过详情核验");
return;
}
SalesOrder first = page.items().get(0);
SalesOrder detail = adapter.get(ctx, SalesOrderRef.of(first.channelOrderId()));
System.out.println("[amazon detail] " + detail.channelOrderId()
+ " total=" + detail.totalAmount() + " lines=" + detail.lines().size());
for (common.ecommerce.model.order.OrderLine line : detail.lines()) {
System.out.println(" sku=" + line.platformSku()
+ " qty=" + line.quantity()
+ " unit=" + line.unitPrice()
+ " tax=" + line.tax()
+ " discount=" + line.discount());
}
}
/**
* 第 3 步补充(亚马逊 FBM):拉一页「订单管理」视角的自发货订单,再取一单详情。
*
* <p>这条路由的主键是领星系统单号 {@code order_number},不是平台订单号。</p>
*/
@Test
void pullsAmazonFbmOrders() {
requireCredentials();
LingxingAdapter adapter = adapter();
String sid = firstAmazonShopSid(adapter);
if (sid == null) {
return;
}
ChannelContext ctx = context(amazonAccount(sid), "smoke-fbm-");
Instant to = Instant.now();
Instant from = to.minus(Duration.ofDays(2));
Page<SalesOrder> page = adapter.pullFbmOrders(ctx, SalesOrderQuery.builder()
.updatedAfter(from)
.updatedBefore(to)
.pageSize(20)
.build());
System.out.println("[fbm orders] sid=" + sid
+ " window=" + from + " .. " + to
+ " items=" + page.size() + " nextCursor=" + page.nextCursor());
for (SalesOrder o : page.items()) {
System.out.println(" order_number=" + o.channelOrderId()
+ " status=" + o.status()
+ " country=" + o.shipToCountryCode()
+ " utc=" + o.occurredAt().utc());
}
if (page.items().isEmpty()) {
System.out.println("[fbm orders] 窗口内没有订单,跳过详情核验");
return;
}
SalesOrder first = page.items().get(0);
SalesOrder detail = adapter.getFbmOrder(ctx, first.channelOrderId());
System.out.println("[fbm detail] " + detail.channelOrderId()
+ " status=" + detail.status()
+ " total=" + detail.totalAmount()
+ " lines=" + detail.lines().size());
for (common.ecommerce.model.order.OrderLine line : detail.lines()) {
System.out.println(" sku=" + line.platformSku()
+ " qty=" + line.quantity()
+ " unit=" + line.unitPrice());
}
}
/** 第 6 步(结算):拉一页亚马逊结算交易明细。 */
@Test
void pullsAmazonSettlements() {
requireCredentials();
LingxingAdapter adapter = adapter();
String sid = firstAmazonShopSid(adapter);
if (sid == null) {
return;
}
ChannelContext ctx = context(amazonAccount(sid), "smoke-settlement-");
LocalDate today = LocalDate.now();
Page<SettlementTransaction> page = adapter.pull(ctx, SettlementQuery.builder()
// 文档:结算时间双闭区间,最长 7 天
.settledAfter(today.minusDays(6))
.settledBefore(today)
.pageSize(20)
.build());
System.out.println("[settlements] sid=" + sid
+ " window=" + today.minusDays(6) + " .. " + today
+ " items=" + page.size() + " nextCursor=" + page.nextCursor());
for (SettlementTransaction t : page.items()) {
System.out.println(" key=" + t.transactionKey()
+ " order=" + t.channelOrderId()
+ " event=" + t.eventType()
+ " type=" + t.transactionType()
+ " amount=" + t.amount()
+ " status=" + t.processingStatus()
+ " postedAt=" + t.postedAt());
}
}
// ---------------------------------------------------------------- helpers
/** 常量没填时跳过,避免占位字符串去打真实接口;填上后自动执行。 */
/** 认证只需要 AppID/AppSecret。 */
private static void requireCredentials() {
org.junit.jupiter.api.Assumptions.assumeTrue(
!APP_KEY.startsWith("在这里填") && !APP_SECRET.startsWith("在这里填"),
"请先填写 LingxingLiveSmokeTest 顶部的 APP_KEY / APP_SECRET");
}
/** 拉多平台订单还需要 store_id / sid。 */
private static void requireConfigured() {
requireCredentials();
org.junit.jupiter.api.Assumptions.assumeTrue(
!APP_KEY.startsWith("在这里填")
&& !APP_SECRET.startsWith("在这里填")
&& !STORE_ID.startsWith("在这里填"),
"请先填写 LingxingLiveSmokeTest 顶部的 APP_KEY / APP_SECRET / STORE_ID");
!STORE_ID.startsWith("在这里填"),
"请先填写 LingxingLiveSmokeTest 顶部的 STORE_ID");
}
private LingxingAdapter adapter() {
return new LingxingAdapter(transport, json, tokenStore, locks, Clock.systemUTC());
}
/** 端点与凭据由调用方传入;冒烟测试里来自环境变量。 */
/** 列出亚马逊店铺并返回第一家 sid;没有授权店铺时返回 null。 */
private String firstAmazonShopSid(LingxingAdapter adapter) {
ChannelAccount discovery = amazonAccount("0");
List<SubChannel> shops = adapter.listSubChannels(context(discovery, "smoke-amazon-shops-"));
System.out.println("[amazon shops] count=" + shops.size());
for (SubChannel shop : shops) {
System.out.println(" sid=" + shop.externalStoreId()
+ " name=" + shop.name()
+ " platform=" + shop.platform());
}
return shops.isEmpty() ? null : shops.get(0).externalStoreId();
}
private ChannelContext context(ChannelAccount account, String prefix) {
return ChannelContext.of(account, connection(),
prefix + System.currentTimeMillis(), Clock.systemUTC());
}
/** 端点与凭据由调用方传入;冒烟测试里来自常量。 */
private ChannelConnection connection() {
return ChannelConnection.of(BASE_URL, ChannelSecret.builder()
.appKey(APP_KEY).appSecret(APP_SECRET).build());
}
private ChannelAccount account() {
return account(LingxingConstants.toPlatform(PLATFORM_CODE), PLATFORM_CODE, STORE_ID);
}
private ChannelAccount amazonAccount(String sid) {
return account(Platform.AMAZON_SC, LingxingConstants.PLATFORM_CODE_AMAZON, sid);
}
private ChannelAccount account(Platform platform, int platformCode, String storeId) {
return ChannelAccount.builder()
.key(AccountKey.of(ChannelProvider.LINGXING, Platform.WALMART_SC, "oms-smoke-001"))
.externalStoreId(STORE_ID)
.platformCode(PLATFORM_CODE)
.key(AccountKey.of(ChannelProvider.LINGXING, platform, "oms-smoke-001"))
.externalStoreId(storeId)
.platformCode(platformCode)
.credentialRef("smoke")
.marketplaceZone("America/Los_Angeles")
.currency("USD")

Loading…
Cancel
Save