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.

359 lines
16 KiB

package common.ecommerce.hengjian.adapter;
import com.fasterxml.jackson.databind.JsonNode;
import common.ecommerce.hengjian.HengjianConstants;
import common.ecommerce.hengjian.dto.HengjianCarrierGroupDtos;
import common.ecommerce.hengjian.dto.HengjianCreateOrderDtos;
import common.ecommerce.hengjian.dto.HengjianProductSaveDtos;
import common.ecommerce.hengjian.dto.HengjianWarehouseDtos;
import common.ecommerce.hengjian.http.HengjianEnvelope;
import common.ecommerce.hengjian.http.HengjianRateLimiter;
import common.ecommerce.hengjian.http.HengjianRequestFactory;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpResponse;
import common.ecommerce.http.HttpTransport;
import common.ecommerce.http.JacksonJsonCodec;
import common.ecommerce.shared.support.Page;
import common.ecommerce.warehouse.capability.LogisticsProductCapable;
import common.ecommerce.warehouse.capability.OutboundCapable;
import common.ecommerce.warehouse.capability.WarehouseDirectoryCapable;
import common.ecommerce.warehouse.capability.WarehouseProduct;
import common.ecommerce.warehouse.capability.WarehouseProductCapable;
import common.ecommerce.warehouse.enums.CancelEligibility;
import common.ecommerce.warehouse.enums.LabelMode;
import common.ecommerce.warehouse.enums.WarehouseCapability;
import common.ecommerce.warehouse.enums.WarehouseProvider;
import common.ecommerce.warehouse.error.WarehouseException;
import common.ecommerce.warehouse.model.CancelCommand;
import common.ecommerce.warehouse.model.CancelResult;
import common.ecommerce.warehouse.model.LogisticsProduct;
import common.ecommerce.warehouse.model.OutboundCommand;
import common.ecommerce.warehouse.model.OutboundOrder;
import common.ecommerce.warehouse.model.OutboundQuery;
import common.ecommerce.warehouse.model.OutboundReceipt;
import common.ecommerce.warehouse.model.OutboundRef;
import common.ecommerce.warehouse.model.PackageResult;
import common.ecommerce.warehouse.model.WarehouseFacility;
import common.ecommerce.warehouse.sdk.WarehouseContext;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 恒健适配器。
*
* <p><b>已接入</b>:仓库目录、承运商 / 物流产品、按仓的物流渠道(只读),
* 以及商品创建 / 编辑({@code /v1/product/save},保存语义)。</p>
*
* <p>出库 / 库存 / 入库 / 退货等接口<b>尚未接入</b>,能力位不声明:
* 门面调用会显式抛 {@code WarehouseUnsupportedCapabilityException},不返回空集合。</p>
*
* <p>适配器只持有协议与基础设施,不持有端点与凭据——两者随每次调用经
* {@code WarehouseConnection} 传入。</p>
*/
public final class HengjianAdapter implements WarehouseDirectoryCapable, LogisticsProductCapable,
WarehouseProductCapable, OutboundCapable {
private static final String OP_WAREHOUSE_LIST = "warehouse.directory.warehouses";
private static final String OP_CARRIERS = "warehouse.directory.carriers";
private static final String OP_LOGISTICS_PRODUCTS = "warehouse.logistics.products";
private static final String OP_PRODUCT_SAVE = "warehouse.product.create";
private static final String OP_ORDER_CREATE = "warehouse.outbound.create";
/** 保存语义没有 create / update 之分,仓方也不回是哪种。 */
private static final String SAVED = "SAVED";
private final HttpTransport transport;
private final JacksonJsonCodec json;
private final HengjianRequestFactory requestFactory;
private final HengjianRateLimiter rateLimiter;
public HengjianAdapter(HttpTransport transport, JacksonJsonCodec json) {
this.transport = transport;
this.json = json;
this.requestFactory = new HengjianRequestFactory(json);
this.rateLimiter = new HengjianRateLimiter();
}
@Override
public String adapterId() {
return HengjianConstants.ADAPTER_ID;
}
@Override
public WarehouseProvider provider() {
return WarehouseProvider.HENGJIAN;
}
@Override
public EnumSet<WarehouseCapability> capabilities() {
return EnumSet.of(
WarehouseCapability.PRODUCT,
WarehouseCapability.OUTBOUND,
WarehouseCapability.PLATFORM_LABEL_DELIVERY,
WarehouseCapability.DIRECTORY,
WarehouseCapability.LOGISTICS_PRODUCT);
}
// ------------------------------------------------------------------ 出库
/**
* 创建销售发货单({@code POST /v1/saleOrder/create})。
*
* <p>承接 {@code WarehouseOutbounds.create} 的幂等守卫:同一
* {@code outboundRequestNo} 重复下发由门面拦住,这里只负责拼报文与解析。</p>
*
* <p>响应只回 {@code data.orderId}(<b>仓内部数字 id</b>,不是字符串单号)。
* 恒健的取消接口同时要 {@code orderId} 与 {@code orderNo},所以这个 id
* 必须随 {@link OutboundReceipt#providerOrderId()} 落库;缺了它后续取消做不了,
* 因此拿不到就报错,<b>不静默当成创建成功</b>。</p>
*/
@Override
public OutboundReceipt create(WarehouseContext ctx, OutboundCommand cmd) {
requirePlatformLabelSupported(cmd);
String warehouseCode = HengjianOutboundMapper.resolveWarehouseCode(
cmd.warehouseId(), ctx.providerWarehouseId());
HengjianCreateOrderDtos.CreateOrderRequest body =
HengjianOutboundMapper.toRequest(cmd, warehouseCode, ctx.clock());
String raw = execute(ctx, HengjianConstants.PATH_ORDER_CREATE, body, OP_ORDER_CREATE);
HengjianCreateOrderDtos.CreateOrderResponse resp =
json.fromJson(raw, HengjianCreateOrderDtos.CreateOrderResponse.class);
if (resp == null || resp.data == null || resp.data.orderId == null) {
throw WarehouseException.builder()
.message("hengjian create order returned no data.orderId: " + safeRelay(raw))
.operation(OP_ORDER_CREATE)
.warehouseCode(ctx.warehouseCode())
.provider(provider().name())
.requestId(ctx.requestId())
.retryable(false)
.rawResponse(safeRelay(raw))
.build();
}
return OutboundReceipt.of(cmd.outboundRequestNo(), String.valueOf(resp.data.orderId),
resp.message);
}
/** 恒健出库查询尚未接入:显式拒绝,不返回 null 让调用方以为「仓说没有这单」。 */
@Override
public OutboundOrder get(WarehouseContext ctx, OutboundRef ref) {
throw unsupportedOutbound("warehouse.outbound.get", ctx);
}
@Override
public Page<OutboundOrder> query(WarehouseContext ctx, OutboundQuery query) {
throw unsupportedOutbound("warehouse.outbound.query", ctx);
}
@Override
public CancelEligibility checkCancel(WarehouseContext ctx, OutboundRef ref) {
throw unsupportedOutbound("warehouse.outbound.checkCancel", ctx);
}
@Override
public CancelResult cancel(WarehouseContext ctx, CancelCommand cmd) {
throw unsupportedOutbound("warehouse.outbound.cancel", ctx);
}
@Override
public List<PackageResult> packages(WarehouseContext ctx, OutboundRef ref) {
throw unsupportedOutbound("warehouse.outbound.packages", ctx);
}
/**
* 平台面单必须真的带文件。
*
* <p>恒健的面单就是 {@code attachInfoItems} 里的一条附件;声明了
* {@code PLATFORM_LABEL_DELIVERY} 却不给文件,仓没有面单可打,等于静默失败。</p>
*/
private static void requirePlatformLabelSupported(OutboundCommand cmd) {
if (cmd.labelMode() == LabelMode.PLATFORM_LABEL
&& (cmd.labelContentBase64() == null || cmd.labelContentBase64().trim().isEmpty())) {
throw new IllegalArgumentException(
"labelContentBase64 is required when labelMode=PLATFORM_LABEL for "
+ cmd.outboundRequestNo());
}
}
private WarehouseException unsupportedOutbound(String operation, WarehouseContext ctx) {
return WarehouseException.builder()
.message("hengjian does not implement " + operation + " yet")
.operation(operation)
.warehouseCode(ctx.warehouseCode())
.provider(provider().name())
.requestId(ctx.requestId())
.retryable(false)
.build();
}
/** 原始响应可能含 PII,异常里只留短片段。 */
private static String safeRelay(String raw) {
if (raw == null) {
return null;
}
return raw.length() <= 300 ? raw : raw.substring(0, 300) + "...";
}
// ------------------------------------------------------------------ 商品
/**
* 创建 / 编辑商品({@code POST /v1/product/save})。
*
* <p>接口是<b>保存语义</b>:同一 SKU 再调即更新,所以不区分 create 与 update,
* 也不像信仓那样先查一次再决定调哪个接口。</p>
*
* <p>响应只有 {@code code / message},<b>没有 data</b>,因此结果里的
* {@code status} 固定为 {@code SAVED}、{@code rawStatus} 取仓方的 message——
* 仓方并不告诉我们这次是新建还是更新,不能替它编。</p>
*
* @throws IllegalArgumentException 恒健要求但统一模型未给的非空字段缺失(本地拒绝)
*/
@Override
public ProductResult createOrUpdate(WarehouseContext ctx, WarehouseProduct product) {
HengjianProductSaveDtos.SaveProductRequest body = HengjianProductMapper.toRequest(product);
String raw = execute(ctx, HengjianConstants.PATH_PRODUCT_SAVE, body, OP_PRODUCT_SAVE);
return ProductResult.of(body.sku, SAVED, json.stringAt(raw, "message"));
}
// ------------------------------------------------------------------ 仓库目录
/**
* 当前组织下的全部仓库({@code POST /v2/warehouse/getWarehouse},无参数)。
*
* <p>返回的 {@code warehouseCode} 可直接用于下单、库存查询等接口。</p>
*/
@Override
public List<WarehouseFacility> warehouses(WarehouseContext ctx) {
String raw = execute(ctx, HengjianConstants.PATH_WAREHOUSE_LIST, null, OP_WAREHOUSE_LIST);
List<HengjianWarehouseDtos.WarehouseRow> rows =
json.listAt(raw, "data", HengjianWarehouseDtos.WarehouseRow.class);
return HengjianDirectoryMapper.toWarehouses(rows);
}
/**
* 承运商 / 物流方式代码({@code POST /v2/carrierGroup/getCarrierGroup},无参数)。
*
* <p>返回物流产品代码(如 {@code UPS2DAM_HL}),可直接作为下单的 {@code carrierCode}。
* 按出现顺序去重。</p>
*/
@Override
public List<String> carriers(WarehouseContext ctx) {
return codesOf(fetchAllServices(ctx));
}
/**
* 物流产品清单({@code POST /v2/carrierGroup/getCarrierGroup})。
*
* <p>恒健这个接口<b>没有仓维度</b>,拿到的是组织级清单;{@code warehouseCode}
* 仅用于写进结果字段,便于调用方区分来源。需要「某仓支持哪些渠道」用
* {@link #productsOfWarehouse}。</p>
*/
@Override
public List<LogisticsProduct> products(WarehouseContext ctx, String warehouseCode) {
return HengjianDirectoryMapper.toProducts(fetchAllServices(ctx), resolveWarehouseCode(ctx, warehouseCode));
}
/**
* 查询「某仓支持哪些物流渠道」({@code POST
* /v2/carrierGroup/getWarehouseCarrierGroupServices})。
*
* <p>返回形状与 {@link #products} 不同:{@code data} 是以仓代码为键的对象,
* 不是数组;只取请求的那个仓,混进别的仓的渠道会让「仓不支持该渠道」
* 变成仓方报错。</p>
*/
public List<LogisticsProduct> productsOfWarehouse(WarehouseContext ctx, String warehouseCode) {
String code = resolveWarehouseCode(ctx, warehouseCode);
if (code == null) {
throw new IllegalArgumentException(
"hengjian warehouse carrier services need a warehouseCode; none given and account has none");
}
List<String> codes = new ArrayList<String>();
codes.add(code);
Map<String, Object> body = new LinkedHashMap<String, Object>();
body.put("warehouseCodes", codes);
String raw = execute(ctx, HengjianConstants.PATH_WAREHOUSE_CARRIER_GROUP, body,
OP_LOGISTICS_PRODUCTS);
return HengjianDirectoryMapper.toProducts(servicesOfWarehouse(raw, code), code);
}
// ------------------------------------------------------------------ 内部
private List<HengjianCarrierGroupDtos.CarrierServiceRow> fetchAllServices(WarehouseContext ctx) {
String raw = execute(ctx, HengjianConstants.PATH_CARRIER_GROUP, null, OP_CARRIERS);
return json.listAt(raw, "data", HengjianCarrierGroupDtos.CarrierServiceRow.class);
}
/** {@code data} 是 {@code 仓代码 → 服务数组} 的对象;只取指定仓。 */
private List<HengjianCarrierGroupDtos.CarrierServiceRow> servicesOfWarehouse(String raw, String warehouseCode) {
List<HengjianCarrierGroupDtos.CarrierServiceRow> rows =
new ArrayList<HengjianCarrierGroupDtos.CarrierServiceRow>();
JsonNode data = json.nodeAt(raw, "data");
if (data == null || !data.isObject()) {
return rows;
}
JsonNode node = data.get(warehouseCode);
if (node == null || !node.isArray()) {
return rows;
}
Iterator<JsonNode> it = node.elements();
while (it.hasNext()) {
rows.add(json.mapper().convertValue(it.next(),
HengjianCarrierGroupDtos.CarrierServiceRow.class));
}
return rows;
}
/** 显式仓代码优先,否则用账户配置的;都没有返回 null,由调用方决定是否拒绝。 */
private static String resolveWarehouseCode(WarehouseContext ctx, String warehouseCode) {
if (warehouseCode != null && !warehouseCode.trim().isEmpty()) {
return warehouseCode.trim();
}
String configured = ctx.providerWarehouseId();
return configured == null || configured.trim().isEmpty() ? null : configured.trim();
}
private static List<String> codesOf(List<HengjianCarrierGroupDtos.CarrierServiceRow> rows) {
List<String> out = new ArrayList<String>();
if (rows == null) {
return out;
}
for (HengjianCarrierGroupDtos.CarrierServiceRow row : rows) {
if (row == null || row.code == null || row.code.trim().isEmpty()) {
continue;
}
String code = row.code.trim();
if (!out.contains(code)) {
out.add(code);
}
}
return out;
}
/**
* 发请求并校验信封。
*
* @param body null 表示无参数接口,发送空 JSON 对象
*/
private String execute(WarehouseContext ctx, String path, Object body, String operation) {
rateLimiter.acquire(path, HengjianConstants.PERMITS_PER_SECOND);
HttpRequest req = requestFactory.post(ctx.endpointBaseUrl(), path, body, ctx.secret(), ctx, operation);
HttpResponse resp = transport.execute(req);
String raw = HengjianEnvelope.of(resp, json, operation, ctx.warehouseCode(), ctx.requestId()).body();
if (raw == null || raw.trim().isEmpty()) {
throw WarehouseException.builder()
.message("hengjian " + operation + " returned an empty body")
.operation(operation)
.warehouseCode(ctx.warehouseCode())
.provider(provider().name())
.requestId(ctx.requestId())
.retryable(true)
.build();
}
return raw;
}
}