You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
715 lines
33 KiB
715 lines
33 KiB
package common.ecommerce.lingxing.probe; |
|
|
|
import common.ecommerce.channel.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.lingxing.LingxingApi; |
|
import common.ecommerce.lingxing.LingxingConstants; |
|
import common.ecommerce.lingxing.adapter.LingxingAdapter; |
|
import common.ecommerce.lingxing.auth.LingxingTokenClient; |
|
import common.ecommerce.lingxing.http.LingxingEnvelope; |
|
import common.ecommerce.lingxing.http.LingxingRateLimiter; |
|
import common.ecommerce.lingxing.http.LingxingRequestFactory; |
|
import common.ecommerce.lingxing.platform.LingxingCall; |
|
import common.ecommerce.lingxing.platform.multiplatform.order.LingxingOrderFilters; |
|
import common.ecommerce.shared.model.ChannelProvider; |
|
import common.ecommerce.shared.model.Capability; |
|
import common.ecommerce.shared.model.Platform; |
|
import common.ecommerce.channel.model.account.AccountKey; |
|
import common.ecommerce.channel.model.account.ChannelAccount; |
|
import common.ecommerce.channel.model.fulfillment.LabelQuery; |
|
import common.ecommerce.channel.model.fulfillment.OutboundOrder; |
|
import common.ecommerce.channel.model.fulfillment.OutboundOrderLine; |
|
import common.ecommerce.channel.model.fulfillment.OutboundOrderQuery; |
|
import common.ecommerce.channel.model.fulfillment.ShippingLabel; |
|
import common.ecommerce.channel.model.inbound.InboundReceipt; |
|
import common.ecommerce.channel.model.inbound.InboundReceiptQuery; |
|
import common.ecommerce.channel.model.inbound.InboundShipment; |
|
import common.ecommerce.channel.model.inbound.InboundShipmentQuery; |
|
import common.ecommerce.channel.model.inbound.InboundShipmentTimeType; |
|
import common.ecommerce.channel.model.order.SalesOrder; |
|
import common.ecommerce.channel.model.order.SalesOrderQuery; |
|
import common.ecommerce.shared.support.Page; |
|
import common.ecommerce.shared.support.PlatformTime; |
|
import common.ecommerce.channel.sdk.ChannelConnection; |
|
import common.ecommerce.channel.sdk.ChannelContext; |
|
import common.ecommerce.shared.spi.AccessToken; |
|
import common.ecommerce.shared.spi.ChannelSecret; |
|
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
|
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
|
import org.junit.jupiter.api.Assumptions; |
|
import org.junit.jupiter.api.Test; |
|
import org.junit.jupiter.api.condition.EnabledIfSystemProperty; |
|
|
|
import java.time.Clock; |
|
import java.time.Duration; |
|
import java.time.Instant; |
|
import java.time.LocalDate; |
|
import java.util.ArrayList; |
|
import java.util.Collections; |
|
import java.util.LinkedHashMap; |
|
import java.util.List; |
|
import java.util.Map; |
|
import java.util.TreeMap; |
|
|
|
/** |
|
* 店铺 / 订单 / 面单 / 入库的只读探针:核对这些接口在真实环境下的出入参。 |
|
* |
|
* <p>与同目录其它探针一样:<b>默认跳过</b>,用 {@code -Dlingxing.probe=true} 显式开启, |
|
* 凭据走系统属性、<b>真实凭证不入库</b>:</p> |
|
* |
|
* <pre> |
|
* mvn -pl lingxing -am -DfailIfNoTests=false \ |
|
* -Dlingxing.probe=true \ |
|
* -Dlingxing.probe.appKey=你的appId -Dlingxing.probe.appSecret=你的appSecret \ |
|
* -Dtest=FulfillmentProbeTest test |
|
* </pre> |
|
* |
|
* <p>可选系统属性:{@code -Dlingxing.probe.storeId}(多平台店铺)、 |
|
* {@code -Dlingxing.probe.amazonSid}(WMS 出库单 / 面单 / AWD,必须数字)、 |
|
* {@code -Dlingxing.probe.walmartStoreId}(WFS)、{@code -Dlingxing.probe.tiktokStoreId}(FBT)、 |
|
* {@code -Dlingxing.probe.vcStoreId}(亚马逊 VC)。不填则从店铺列表自动发现。</p> |
|
* |
|
* <p><b>只做查询</b>,不调用任何写接口。异常只打印不抛出,一次跑完全部段落, |
|
* 方便逐条对照真实报文(尤其 {@code 待核对} 的字段名与格式)。</p> |
|
*/ |
|
@EnabledIfSystemProperty(named = "lingxing.probe", matches = "true") |
|
class FulfillmentProbeTest { |
|
|
|
// 真实凭据不入库:本地跑探针时用 -Dlingxing.probe.appKey=... -Dlingxing.probe.appSecret=... |
|
private static final String APP_KEY = System.getProperty("lingxing.probe.appKey", ""); |
|
private static final String APP_SECRET = System.getProperty("lingxing.probe.appSecret", ""); |
|
private static final String STORE_ID = opt("lingxing.probe.storeId"); |
|
private static final String AMAZON_SID = opt("lingxing.probe.amazonSid"); |
|
private static final String WALMART_STORE_ID = opt("lingxing.probe.walmartStoreId"); |
|
private static final String TIKTOK_STORE_ID = opt("lingxing.probe.tiktokStoreId"); |
|
private static final String VC_STORE_ID = opt("lingxing.probe.vcStoreId"); |
|
private static final Integer PLATFORM_CODE = optInt("lingxing.probe.platformCode"); |
|
|
|
private static final String BASE_URL = LingxingConstants.PRODUCTION_BASE_URL; |
|
private static final JacksonJsonCodec JSON = new JacksonJsonCodec(); |
|
|
|
/** 面单只取前几单,避免把大段 base64 刷到控制台。 */ |
|
private static final int LABEL_LIMIT = 5; |
|
|
|
private final LoggingTransport transport = |
|
new LoggingTransport(new OkHttpTransport("common-ecommerce-fulfillment-probe")); |
|
private final InMemoryTokenStore tokens = new InMemoryTokenStore(); |
|
private final LingxingAdapter adapter = new LingxingAdapter(transport, JSON, tokens, |
|
new InMemoryLockProvider(), Clock.systemUTC()); |
|
|
|
/** 多平台店铺自动发现结果;{@link #discoveryAttempted} 保证只发现一次。 */ |
|
private String discoveredStoreId; |
|
private boolean discoveryAttempted; |
|
|
|
// ================================================================ 店铺 |
|
|
|
/** |
|
* 普通店铺列表(适配器 {@code listSubChannels},内部按 {@code is_sync=1 + status=1} 过滤), |
|
* 再直连同一个接口不过滤这两项,把暂停同步 / 授权异常的店铺也打出来。 |
|
* |
|
* <p>两者相减就是被过滤掉的店铺;「订单 / 入库里莫名少的店铺」多半在这里。</p> |
|
*/ |
|
@Test |
|
void probeShops() { |
|
requireCredentials(); |
|
System.out.println("\n================ shops / 多平台店铺 ================"); |
|
try { |
|
ChannelContext ctx = context("probe-shops-"); |
|
List<SubChannel> visible = adapter.listSubChannels(ctx); |
|
System.out.println("[shops] 适配器可见=" + visible.size() |
|
+ " platform_code=" + platformCodeLabel()); |
|
for (SubChannel shop : visible) { |
|
System.out.println(" store_id=" + shop.externalStoreId() |
|
+ " platform_code=" + shop.platformCode() |
|
+ " platform=" + shop.platform() |
|
+ " name=" + shop.name() |
|
+ " platform_name=" + shop.attributes().get("platform_name")); |
|
} |
|
|
|
List<Map<String, Object>> all = fetchAllShops(); |
|
System.out.println("[shops all] 不过滤=" + all.size()); |
|
Map<String, List<Map<String, Object>>> byCode = new TreeMap<String, List<Map<String, Object>>>(); |
|
for (Map<String, Object> shop : all) { |
|
String code = String.valueOf(shop.get("platform_code")); |
|
List<Map<String, Object>> group = byCode.get(code); |
|
if (group == null) { |
|
group = new ArrayList<Map<String, Object>>(); |
|
byCode.put(code, group); |
|
} |
|
group.add(shop); |
|
} |
|
for (Map.Entry<String, List<Map<String, Object>>> e : byCode.entrySet()) { |
|
Platform mapped = LingxingConstants.toPlatform(toInt(e.getKey())); |
|
System.out.println(" code=" + e.getKey() |
|
+ " → " + (mapped == null ? "未登记" : mapped.name()) |
|
+ " 共 " + e.getValue().size() + " 家"); |
|
for (Map<String, Object> shop : e.getValue()) { |
|
System.out.println(" store_id=" + shop.get("store_id") |
|
+ " is_sync=" + shop.get("is_sync") |
|
+ " status=" + shop.get("status") |
|
+ " name=" + shop.get("store_name") |
|
+ " platform_name=" + shop.get("platform_name")); |
|
} |
|
} |
|
|
|
List<String> hidden = new ArrayList<String>(); |
|
for (Map<String, Object> shop : all) { |
|
String storeId = shop.get("store_id") == null ? null : String.valueOf(shop.get("store_id")); |
|
if (storeId == null || !containsStore(visible, storeId)) { |
|
hidden.add(storeId + "(" + shop.get("store_name") + ")"); |
|
} |
|
} |
|
System.out.println("[shops all] 被 is_sync/status 过滤掉=" + hidden.size() + " " + hidden); |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
} |
|
|
|
// ================================================================ 订单 |
|
|
|
/** 多平台订单:默认更新时间口径与订购时间口径各拉一页,对比条数。 */ |
|
@Test |
|
void probeOrdersByDateType() { |
|
requireCredentials(); |
|
System.out.println("\n================ orders / date_type ================"); |
|
try { |
|
ChannelAccount account = multiPlatformAccount(); |
|
if (account == null) { |
|
return; |
|
} |
|
ChannelContext ctx = context(account, "probe-orders-"); |
|
Instant to = Instant.now(); |
|
Instant from = to.minus(Duration.ofDays(2)); |
|
SalesOrderQuery query = SalesOrderQuery.builder() |
|
.updatedAfter(from) |
|
.updatedBefore(to) |
|
.pageSize(5) |
|
.build(); |
|
|
|
Page<SalesOrder> byUpdate = adapter.pull(ctx, query, LingxingOrderFilters.none()); |
|
System.out.println("[orders] date_type=update_time items=" + byUpdate.size() |
|
+ " nextCursor=" + byUpdate.nextCursor()); |
|
printOrders(byUpdate); |
|
|
|
Page<SalesOrder> byPurchase = adapter.pull(ctx, query, LingxingOrderFilters.builder() |
|
.dateType(LingxingOrderFilters.DATE_TYPE_PURCHASE_TIME) |
|
.build()); |
|
System.out.println("[orders] date_type=global_purchase_time items=" + byPurchase.size() |
|
+ " nextCursor=" + byPurchase.nextCursor()); |
|
printOrders(byPurchase); |
|
|
|
// 按平台单号回查:契约上允许不传时间窗,这里用上一页的样本验证是否被默认窗口滤掉 |
|
if (byUpdate.items().isEmpty()) { |
|
System.out.println("[orders] 窗口内没有样本,跳过 platform_order_no 回查"); |
|
return; |
|
} |
|
String platformOrderNo = byUpdate.items().get(0).channelOrderId(); |
|
Page<SalesOrder> hit = adapter.pull(ctx, query, LingxingOrderFilters.builder() |
|
.platformOrderNos(Collections.singletonList(platformOrderNo)) |
|
.build()); |
|
System.out.println("[orders] platform_order_no=" + platformOrderNo |
|
+ " → items=" + hit.size()); |
|
printOrders(hit); |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
} |
|
|
|
/** 亚马逊 SC 订单列表 + 详情;FBM 列表 + 详情(主键是领星系统单号)。 */ |
|
@Test |
|
void probeAmazonOrders() { |
|
requireCredentials(); |
|
System.out.println("\n================ orders / Amazon SC + FBM ================"); |
|
String sid = firstShopId(Platform.AMAZON_SC, LingxingConstants.PLATFORM_CODE_AMAZON, AMAZON_SID); |
|
if (sid == null) { |
|
return; |
|
} |
|
Instant to = Instant.now(); |
|
Instant from = to.minus(Duration.ofDays(2)); |
|
SalesOrderQuery query = SalesOrderQuery.builder() |
|
.updatedAfter(from) |
|
.updatedBefore(to) |
|
.pageSize(5) |
|
.build(); |
|
|
|
try { |
|
ChannelContext ctx = context(account(Platform.AMAZON_SC, |
|
LingxingConstants.PLATFORM_CODE_AMAZON, sid), "probe-amazon-orders-"); |
|
Page<SalesOrder> page = adapter.pull(ctx, query); |
|
System.out.println("[amazon orders] sid=" + sid + " items=" + page.size() |
|
+ " nextCursor=" + page.nextCursor()); |
|
printOrders(page); |
|
if (!page.items().isEmpty()) { |
|
System.out.println(" [detail] " + adapter.get(ctx, |
|
common.ecommerce.channel.model.order.SalesOrderRef.of( |
|
page.items().get(0).channelOrderId()))); |
|
} |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
|
|
try { |
|
ChannelContext ctx = context(account(Platform.AMAZON_SC, |
|
LingxingConstants.PLATFORM_CODE_AMAZON, sid), "probe-fbm-"); |
|
Page<SalesOrder> page = adapter.pullFbmOrders(ctx, query); |
|
System.out.println("[fbm orders] sid=" + sid + " items=" + page.size() |
|
+ " nextCursor=" + page.nextCursor()); |
|
printOrders(page); |
|
if (!page.items().isEmpty()) { |
|
System.out.println(" [detail] " + adapter.getFbmOrder(ctx, page.items().get(0).channelOrderId())); |
|
} |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
} |
|
|
|
/** 亚马逊 VC 订单列表 + 详情(详情分 DF / PO 两个接口,由 {@code get()} 分派)。 */ |
|
@Test |
|
void probeAmazonVcOrders() { |
|
requireCredentials(); |
|
System.out.println("\n================ orders / Amazon VC ================"); |
|
String vcStoreId = firstShopId(Platform.AMAZON_VC, |
|
LingxingConstants.PLATFORM_CODE_AMAZON_VC, VC_STORE_ID); |
|
if (vcStoreId == null) { |
|
return; |
|
} |
|
try { |
|
ChannelContext ctx = context(account(Platform.AMAZON_VC, |
|
LingxingConstants.PLATFORM_CODE_AMAZON_VC, vcStoreId), "probe-vc-orders-"); |
|
Instant to = Instant.now(); |
|
Page<SalesOrder> page = adapter.pull(ctx, SalesOrderQuery.builder() |
|
.updatedAfter(to.minus(Duration.ofDays(2))) |
|
.updatedBefore(to) |
|
.pageSize(5) |
|
.build()); |
|
System.out.println("[vc orders] vc_store_id=" + vcStoreId + " items=" + page.size() |
|
+ " nextCursor=" + page.nextCursor()); |
|
printOrders(page); |
|
if (!page.items().isEmpty()) { |
|
System.out.println(" [detail] " + adapter.get(ctx, |
|
common.ecommerce.channel.model.order.SalesOrderRef.of( |
|
page.items().get(0).channelOrderId()))); |
|
} |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
} |
|
|
|
// ================================================================ 面单 / 出库单 |
|
|
|
/** 销售出库单 → 面单({@code wo_number_arr} 与 {@code order_number_arr} 两条路径)。 */ |
|
@Test |
|
void probeOutboundOrdersAndLabels() { |
|
requireCredentials(); |
|
System.out.println("\n================ labels / WMS 出库单 + 面单 ================"); |
|
String sid = firstShopId(Platform.AMAZON_SC, LingxingConstants.PLATFORM_CODE_AMAZON, AMAZON_SID); |
|
if (sid == null) { |
|
System.out.println("[labels] 没有亚马逊店铺(WMS 需要数字 sid),跳过"); |
|
return; |
|
} |
|
try { |
|
ChannelContext ctx = context(account(Platform.AMAZON_SC, |
|
LingxingConstants.PLATFORM_CODE_AMAZON, sid), "probe-labels-"); |
|
Instant to = Instant.now(); |
|
Page<OutboundOrder> page = adapter.pull(ctx, OutboundOrderQuery.builder() |
|
.after(to.minus(Duration.ofDays(30))) |
|
.before(to) |
|
.timeType(OutboundOrderQuery.TIME_CREATED) |
|
.pageSize(5) |
|
.build()); |
|
System.out.println("[outbound orders] sid=" + sid + " items=" + page.size() |
|
+ " nextCursor=" + page.nextCursor()); |
|
for (OutboundOrder o : page.items()) { |
|
System.out.println(" wo_number=" + o.woNumber() |
|
+ " order_number=" + o.orderNumber() |
|
+ " status=" + o.status() + "/" + o.statusName() |
|
+ " warehouse=" + o.warehouseId() + "/" + o.warehouseName() |
|
+ " waybillNO=" + o.waybillNo() |
|
+ " amount=" + o.orderAmount() |
|
+ " surface=" + o.surfaceFileUrl()); |
|
for (OutboundOrderLine line : o.lines()) { |
|
System.out.println(" sku=" + line.sku() |
|
+ " msku=" + line.sellerSku() |
|
+ " qty=" + line.quantity() |
|
+ " unit=" + line.unitPrice()); |
|
} |
|
} |
|
if (page.items().isEmpty()) { |
|
System.out.println("[labels] 最近 30 天没有出库单,跳过面单"); |
|
return; |
|
} |
|
|
|
List<String> woNumbers = new ArrayList<String>(); |
|
List<String> orderNumbers = new ArrayList<String>(); |
|
for (OutboundOrder o : page.items()) { |
|
if (woNumbers.size() >= LABEL_LIMIT) { |
|
break; |
|
} |
|
woNumbers.add(o.woNumber()); |
|
if (o.orderNumber() != null) { |
|
orderNumbers.add(o.orderNumber()); |
|
} |
|
} |
|
printLabels("wo_number_arr", adapter.labels(ctx, LabelQuery.builder().woNumbers(woNumbers).build())); |
|
if (!orderNumbers.isEmpty()) { |
|
printLabels("order_number_arr", |
|
adapter.labels(ctx, LabelQuery.builder().orderNumbers(orderNumbers).build())); |
|
} |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
} |
|
|
|
// ================================================================ 入库 |
|
|
|
/** FBT(TikTok)/ WFS(沃尔玛)/ AWD(亚马逊)各拉一页,三种时间口径逐个试。 */ |
|
@Test |
|
void probeInboundShipments() { |
|
requireCredentials(); |
|
System.out.println("\n================ inbound / FBT + WFS + AWD ================"); |
|
probeInbound("FBT", Platform.TIKTOK, 10011, |
|
firstShopId(Platform.TIKTOK, 10011, TIKTOK_STORE_ID), |
|
InboundShipmentTimeType.CREATED, InboundShipmentTimeType.UPDATED, |
|
InboundShipmentTimeType.COMPLETED); |
|
probeInbound("WFS", Platform.WALMART_SC, 10008, |
|
firstShopId(Platform.WALMART_SC, 10008, WALMART_STORE_ID), |
|
InboundShipmentTimeType.CREATED, InboundShipmentTimeType.COMPLETED); |
|
probeInbound("AWD", Platform.AMAZON_SC, LingxingConstants.PLATFORM_CODE_AMAZON, |
|
firstShopId(Platform.AMAZON_SC, LingxingConstants.PLATFORM_CODE_AMAZON, AMAZON_SID), |
|
InboundShipmentTimeType.CREATED, InboundShipmentTimeType.UPDATED, |
|
// 完成时间不支持,预期被显式拒绝 |
|
InboundShipmentTimeType.COMPLETED); |
|
} |
|
|
|
/** FBA 到货接收明细:按签收日期(北京时间)取一页。 */ |
|
@Test |
|
void probeFbaReceivedInventory() { |
|
requireCredentials(); |
|
System.out.println("\n================ inbound / FBA 接收明细 ================"); |
|
String sid = firstShopId(Platform.AMAZON_SC, LingxingConstants.PLATFORM_CODE_AMAZON, AMAZON_SID); |
|
if (sid == null) { |
|
return; |
|
} |
|
try { |
|
ChannelAccount account = account(Platform.AMAZON_SC, |
|
LingxingConstants.PLATFORM_CODE_AMAZON, sid); |
|
if (!adapter.supports(account, Capability.INBOUND_RECEIPT)) { |
|
System.out.println("[inbound receipts] Amazon SC 未装配 FBA 接收明细,跳过"); |
|
return; |
|
} |
|
LocalDate eventDate = LocalDate.now(PlatformTime.BEIJING_ZONE).minusDays(1); |
|
Page<InboundReceipt> page = adapter.pull(context(account, "probe-inbound-receipts-"), |
|
InboundReceiptQuery.builder().sid(sid).eventDate(eventDate).pageSize(5).build()); |
|
System.out.println("[inbound receipts] sid=" + sid + " eventDate=" + eventDate |
|
+ " items=" + page.size() + " nextCursor=" + page.nextCursor()); |
|
for (InboundReceipt r : page.items()) { |
|
System.out.println(" shipmentId=" + r.shipmentId() |
|
+ " fnsku=" + r.fnsku() |
|
+ " sku=" + r.sku() |
|
+ " qty=" + r.quantity() |
|
+ " fc=" + r.fulfillmentCenterId() |
|
+ " receivedAt=" + (r.receivedAt() == null ? null : r.receivedAt().utc()) |
|
+ " uniqueIndex=" + r.uniqueIndex()); |
|
} |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
} |
|
|
|
// ================================================================ helpers |
|
|
|
private void probeInbound(String label, Platform platform, Integer platformCode, String storeId, |
|
InboundShipmentTimeType... timeTypes) { |
|
if (storeId == null) { |
|
System.out.println("[inbound " + label + "] 没有 " + platform + " 店铺,跳过"); |
|
return; |
|
} |
|
ChannelAccount account = account(platform, platformCode, storeId); |
|
if (!adapter.supports(account, Capability.INBOUND_SHIPMENT)) { |
|
System.out.println("[inbound " + label + "] " + platform + " 未装配入库货件查询,跳过"); |
|
return; |
|
} |
|
Instant to = Instant.now(); |
|
Instant from = to.minus(Duration.ofDays(7)); |
|
for (InboundShipmentTimeType timeType : timeTypes) { |
|
try { |
|
Page<InboundShipment> page = adapter.pull(context(account, "probe-inbound-"), |
|
InboundShipmentQuery.builder() |
|
.storeIds(storeId) |
|
.timeType(timeType) |
|
.after(from) |
|
.before(to) |
|
.pageSize(5) |
|
.build()); |
|
System.out.println("[inbound " + label + "] " + platform + " store=" + storeId |
|
+ " timeType=" + timeType + " items=" + page.size() |
|
+ " nextCursor=" + page.nextCursor()); |
|
for (InboundShipment s : page.items()) { |
|
System.out.println(" shipmentNo=" + s.shipmentNo() |
|
+ " shipmentId=" + s.shipmentId() |
|
+ " inboundOrderNo=" + s.inboundOrderNo() |
|
+ " status=" + s.status() + "/" + s.statusName() |
|
+ " storeIds=" + s.storeIds() |
|
+ " warehouse=" + s.warehouseName() |
|
+ " createdAt=" + (s.createdAt() == null ? null : s.createdAt().utc()) |
|
+ " lines=" + s.lines().size() |
|
+ " shippingRefs=" + s.shippingRefs().size()); |
|
} |
|
} catch (RuntimeException e) { |
|
printError(e); |
|
} |
|
} |
|
} |
|
|
|
/** 不过滤 {@code is_sync} / {@code status} 的店铺列表。 */ |
|
private List<Map<String, Object>> fetchAllShops() { |
|
LingxingCall call = call(context("probe-shops-all-")); |
|
Map<String, Object> body = new LinkedHashMap<String, Object>(); |
|
body.put("offset", 0); |
|
body.put("length", LingxingConstants.MULTI_PLATFORM_MAX_PAGE_SIZE); |
|
if (PLATFORM_CODE != null && PLATFORM_CODE != 0) { |
|
body.put("platform_code", Collections.singletonList(PLATFORM_CODE)); |
|
} |
|
HttpRequest req = call.signed(LingxingApi.SHOP_LIST_MULTI_PLATFORM, body, "probe.shops.all"); |
|
HttpResponse resp = call.execute(req); |
|
LingxingEnvelope env = call.envelope(resp, "probe.shops.all"); |
|
return toRows(JSON.listAt(env.body(), "data.list", LinkedHashMap.class)); |
|
} |
|
|
|
/** |
|
* 平台店铺 id:系统属性优先,否则按平台从店铺列表自动发现第一家。 |
|
* |
|
* @return null 表示没有可用店铺,调用方打印跳过 |
|
*/ |
|
private String firstShopId(Platform platform, Integer platformCode, String configured) { |
|
if (configured != null) { |
|
return configured; |
|
} |
|
ChannelAccount discovery = account(platform, platformCode, "0"); |
|
List<SubChannel> shops = adapter.listSubChannels(context(discovery, "probe-shops-" + platform + "-")); |
|
System.out.println("[shops] " + platform + " 自动发现 " + shops.size() + " 家店"); |
|
for (SubChannel shop : shops) { |
|
System.out.println(" store_id=" + shop.externalStoreId() |
|
+ " platform_code=" + shop.platformCode() |
|
+ " name=" + shop.name()); |
|
} |
|
return shops.isEmpty() ? null : shops.get(0).externalStoreId(); |
|
} |
|
|
|
private void requireCredentials() { |
|
Assumptions.assumeTrue(!APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), |
|
"未提供 -Dlingxing.probe.appKey / -Dlingxing.probe.appSecret,跳过探针"); |
|
} |
|
|
|
private ChannelContext context(String prefix) { |
|
return context(account(smokePlatform(), platformCodeOrNull(), STORE_ID == null ? "0" : STORE_ID), |
|
prefix); |
|
} |
|
|
|
private ChannelContext context(ChannelAccount account, String prefix) { |
|
return ChannelContext.of(account, connection(), prefix + System.currentTimeMillis(), Clock.systemUTC()); |
|
} |
|
|
|
/** 给适配器没有暴露入口的接口(不过滤 is_sync / status 的店铺列表)用。 */ |
|
private LingxingCall call(ChannelContext ctx) { |
|
Clock clock = Clock.systemUTC(); |
|
AccessToken token = new LingxingTokenClient(transport, JSON, clock) |
|
.fetch(BASE_URL, APP_KEY, APP_SECRET); |
|
return new LingxingCall(ctx, token, new LingxingRequestFactory(JSON, clock), |
|
new LingxingRateLimiter(), JSON, transport); |
|
} |
|
|
|
private static ChannelConnection connection() { |
|
return ChannelConnection.of(BASE_URL, ChannelSecret.builder() |
|
.appKey(APP_KEY).appSecret(APP_SECRET).build()); |
|
} |
|
|
|
private static void printOrders(Page<SalesOrder> page) { |
|
for (SalesOrder o : page.items()) { |
|
System.out.println(" " + o.channelOrderId() |
|
+ " status=" + o.status() |
|
+ " total=" + o.totalAmount() |
|
+ " lines=" + o.lines().size() |
|
+ " utc=" + (o.occurredAt() == null ? null : o.occurredAt().utc())); |
|
} |
|
} |
|
|
|
/** 只打 base64 长度,避免把整张面单刷到控制台。 */ |
|
private static void printLabels(String queryKey, List<ShippingLabel> labels) { |
|
System.out.println("[labels] " + queryKey + " count=" + labels.size()); |
|
for (ShippingLabel label : labels) { |
|
String base64 = label.contentBase64(); |
|
System.out.println(" wo_number=" + label.woNumber() |
|
+ " order_number=" + label.orderNumber() |
|
+ " provider=" + label.logisticsProviderId() |
|
+ " fileType=" + label.fileType() |
|
+ " fileSize=" + label.fileSize() |
|
+ " b64=" + (base64 == null ? "null" : base64.length() + " chars")); |
|
} |
|
} |
|
|
|
private static boolean containsStore(List<SubChannel> shops, String storeId) { |
|
for (SubChannel shop : shops) { |
|
if (storeId.equals(shop.externalStoreId())) { |
|
return true; |
|
} |
|
} |
|
return false; |
|
} |
|
|
|
/** |
|
* 多平台探针用的账户:显式传了 {@code -Dlingxing.probe.storeId} 就用它, |
|
* 否则从店铺列表自动发现第一家;都没有时返回 null,调用方跳过。 |
|
* |
|
* <p>自动发现结果缓存在实例字段里,避免每个探针都重复列一遍店铺。</p> |
|
*/ |
|
private ChannelAccount multiPlatformAccount() { |
|
ChannelContext discoveryCtx = context(account(smokePlatform(), platformCodeOrNull(), "0"), |
|
"probe-discovery-"); |
|
String storeId = discoveredStoreId; |
|
if (storeId == null && !discoveryAttempted) { |
|
discoveryAttempted = true; |
|
storeId = discoverFirstStore(discoveryCtx); |
|
if (storeId == null) { |
|
System.out.println("[shops] 没有配置 -Dlingxing.probe.storeId," |
|
+ "自动发现的店铺列表也是空,多平台探针跳过"); |
|
} else { |
|
System.out.println("[shops] 未指定 storeId,自动发现使用 store_id=" + storeId); |
|
} |
|
discoveredStoreId = storeId; |
|
} |
|
return storeId == null ? null : account(smokePlatform(), platformCodeOrNull(), storeId); |
|
} |
|
|
|
private String discoverFirstStore(ChannelContext ctx) { |
|
List<SubChannel> shops = adapter.listSubChannels(ctx); |
|
return shops.isEmpty() ? null : shops.get(0).externalStoreId(); |
|
} |
|
|
|
private static boolean hasPlatformCode() { |
|
return PLATFORM_CODE != null && PLATFORM_CODE != 0; |
|
} |
|
|
|
private static Integer platformCodeOrNull() { |
|
return hasPlatformCode() ? PLATFORM_CODE : null; |
|
} |
|
|
|
/** 没有平台码时兜底 CUSTOM:订单与店铺都走多平台接口,只按 store_id 过滤。 */ |
|
private static Platform smokePlatform() { |
|
return hasPlatformCode() ? LingxingConstants.toPlatform(PLATFORM_CODE) : Platform.CUSTOM; |
|
} |
|
|
|
private static String platformCodeLabel() { |
|
return hasPlatformCode() ? String.valueOf(PLATFORM_CODE) : "未指定(仅按 store_id 过滤)"; |
|
} |
|
|
|
/** |
|
* 账户构造取 {@code Integer}:{@code platformCode} 为 null 表示不带该过滤条件。 |
|
* 注意不要写成 {@code int}——自动发现时平台码常为 null,拆箱会直接 NPE。 |
|
*/ |
|
private static ChannelAccount account(Platform platform, Integer platformCode, String storeId) { |
|
return ChannelAccount.builder() |
|
.key(AccountKey.of(ChannelProvider.LINGXING, platform, |
|
"oms-" + platform.name().toLowerCase())) |
|
.externalStoreId(storeId == null || storeId.trim().isEmpty() ? "probe" : storeId) |
|
.platformCode(platformCode == null || platformCode == 0 ? null : platformCode) |
|
.credentialRef("probe") |
|
.marketplaceZone("America/Los_Angeles") |
|
.currency("USD") |
|
.build(); |
|
} |
|
|
|
private static String opt(String name) { |
|
String value = System.getProperty(name, ""); |
|
if (value == null) { |
|
return null; |
|
} |
|
String trimmed = value.trim(); |
|
return trimmed.isEmpty() ? null : trimmed; |
|
} |
|
|
|
private static Integer optInt(String name) { |
|
String value = opt(name); |
|
if (value == null) { |
|
return null; |
|
} |
|
try { |
|
return Integer.valueOf(value); |
|
} catch (NumberFormatException e) { |
|
return null; |
|
} |
|
} |
|
|
|
private static Integer toInt(Object v) { |
|
if (v == null) { |
|
return null; |
|
} |
|
try { |
|
return Integer.valueOf(String.valueOf(v).trim()); |
|
} catch (NumberFormatException e) { |
|
return null; |
|
} |
|
} |
|
|
|
private static List<Map<String, Object>> toRows(List<?> raw) { |
|
List<Map<String, Object>> out = new ArrayList<Map<String, Object>>(raw.size()); |
|
for (Object o : raw) { |
|
if (o instanceof Map) { |
|
Map<String, Object> row = new LinkedHashMap<String, Object>(); |
|
for (Map.Entry<?, ?> e : ((Map<?, ?>) o).entrySet()) { |
|
row.put(String.valueOf(e.getKey()), e.getValue()); |
|
} |
|
out.add(row); |
|
} |
|
} |
|
return out; |
|
} |
|
|
|
private static void printError(RuntimeException e) { |
|
String msg = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); |
|
System.out.println("[ERROR] " + e.getClass().getSimpleName() + ": " |
|
+ (msg.length() <= 300 ? msg : msg.substring(0, 300) + "…")); |
|
} |
|
|
|
/** 打印请求/响应(截断),只读排查用。token 打码。 */ |
|
static final class LoggingTransport implements HttpTransport { |
|
|
|
private static final int MAX_BODY = 2000; |
|
|
|
private final HttpTransport delegate; |
|
|
|
LoggingTransport(HttpTransport delegate) { |
|
this.delegate = delegate; |
|
} |
|
|
|
@Override |
|
public HttpResponse execute(HttpRequest request) { |
|
System.out.println(" --> " + request.method() + " " + pathOf(request.url())); |
|
System.out.println(" headers " + mask(request.headers().toString())); |
|
System.out.println(" body " + truncate(request.body())); |
|
HttpResponse response = delegate.execute(request); |
|
System.out.println(" <-- " + response.statusCode() + " " + truncate(response.body())); |
|
return response; |
|
} |
|
|
|
private static String mask(String headers) { |
|
return headers.replaceAll("(?i)(bearer\\s+)[^,\\]]+", "$1***"); |
|
} |
|
|
|
private static String pathOf(String url) { |
|
int i = url.indexOf('/', url.indexOf("://") + 3); |
|
return i < 0 ? url : url.substring(i); |
|
} |
|
|
|
private static String truncate(String body) { |
|
if (body == null) { |
|
return "null"; |
|
} |
|
return body.length() <= MAX_BODY ? body : body.substring(0, MAX_BODY) + "...(" + body.length() + " chars)"; |
|
} |
|
} |
|
}
|
|
|