Browse Source
- 新增 warehouse-sdk-hengjian 模块,注册 WarehouseProvider.HENGJIAN - 接入仓库目录、全量物流渠道、按仓物流渠道三个只读接口 - 信封校验覆盖三种真机形态:正常业务信封、HTTP 200 + code=999999、 HTTP 500 + 「未知的账户」;后两者映射为 AuthException - 能力位只声明 DIRECTORY / LOGISTICS_PRODUCT,未接接口不声明 - 新增只读探针(默认跳过,凭据走系统属性)与接入文档 Co-Authored-By: Claude Code <noreply@anthropic.com>feature/Walmart
23 changed files with 1886 additions and 0 deletions
@ -0,0 +1,220 @@
@@ -0,0 +1,220 @@
|
||||
# 恒健(HengJian / Efulfill)接入 |
||||
|
||||
语雀接口文档:<https://ehengjian.yuque.com/org-wiki-ehengjian-ocq8pc/tvzvkk>(book `tvzvkk`) |
||||
核对时间:2026-11-12(文档 `toc_updated_at` = 2026-11-10) |
||||
|
||||
## 1. 基本信息 |
||||
|
||||
| 项 | 值 | |
||||
|---|---| |
||||
| 适配器 ID / provider | `hengjian` / `WarehouseProvider.HENGJIAN`(code 50) | |
||||
| 测试环境 | `https://pr-open-api.ehengjian.com` | |
||||
| 生产环境 | `https://open-api.ehengjian.com` | |
||||
| 鉴权 | 组织级固定 token,放请求头**两个**:`Authorization` + `x-api-key`,取值相同 | |
||||
| token 获取 | 文档未写自助方式:测试参数需联系 `bianyuqi@henglin.com` | |
||||
| token 续期 | 文档未提 refresh;先按固定 token 处理(不经过 `TokenManager`) | |
||||
| 限流 | 未公开,保守默认 2 req/s/仓 | |
||||
| 成功判定 | body 里 `code = 200`;HTTP 通常恒为 200 | |
||||
| 时间口径 | 文档多处注明 **UTC**(`paidAt`、`expectedShipDate`、订单列表的时间参数) | |
||||
| 单位 | 商品尺寸 cm、重量 g;费用单位为 USD(试算接口另有单位入参) | |
||||
| 文档结构 | 67 个目录项,其中 64 个可见接口页(3 个 `visible=0`,1 个抓取 403);另有 `CloudShip接口文档` / `加拿大邮政` 两个不相关目录,其下文档均不可见 | |
||||
|
||||
### 鉴权真机结论(2026-11-12,未拿到有效 token) |
||||
|
||||
| 请求 | 结果 | |
||||
|---|---| |
||||
| 不带任何授权头 | **HTTP 200** + `{"statusCode":500,"status":1,"code":999999,"message":"查询失败Unauthorized"}` | |
||||
| 只带 `Authorization`(无效值) | HTTP 500 + `{"status":500,"error":"Internal Server Error","message":"未知的账户!"}` | |
||||
| 只带 `x-api-key`(无效值) | 同上 | |
||||
| 两个都带(无效值) | 同上 | |
||||
|
||||
**结论**: |
||||
|
||||
- 未授权有两种表现(HTTP 200 + `code=999999`;HTTP 500 + 「未知的账户」), |
||||
适配器把两者都映射成 `AuthException`,**不能**当普通业务失败或瞬时故障—— |
||||
否则宿主不会去刷新凭据,还会无意义重试。 |
||||
- 用无效 token 区分不出「两个头是否都必须」,所以按文档两个都带。拿到有效 token 后 |
||||
应补一次对照实验(各只带一个),再决定能否精简。 |
||||
|
||||
### 文档与实际不一致(待真机逐条确认) |
||||
|
||||
| # | 文档写的 | 问题 | |
||||
|---|---|---| |
||||
| 1 | 《基础API调用》:`Authorization` 与 `x-api-key` 都必填、都叫「授权Token」 | 没说两者是否同值;两个头是否都必须未验证(见上) | |
||||
| 2 | 《库存变动明细查询》(2026-10-20 新增):「沿用现有 OpenAPI 凭证,请求头使用 `Authorization: Bearer <token>`」 | 与《基础API调用》的双头要求**冲突**;该页是后来单独写的,可能代表新约定 | |
||||
| 3 | 《获取仓库支持的物流渠道》:`warehouseCodes` 类型写 `STRING` | 请求示例是数组 `["..."]`;按数组下发 | |
||||
| 4 | 《批量查询库存》:GET,参数是 `warehouseCodes` LIST | HTTP GET 不能可靠表达数组;先按重复 query 参数下发 | |
||||
| 5 | 《查询库存》《查询 sku》等页:`code` 类型写 `STRING` | 其它页写 INTEGER;信封按文本读再转数字,两种都认 | |
||||
| 6 | 多个接口页**不写路径 / 请求方式**(调拨取消、销毁计划、退货 v2、计费类) | 只能从标题和相邻页推断;这几类未接入前不需要 | |
||||
| 7 | 《创建/编辑 产品》`length` vs 《查询 sku》`itemLength` | 同一概念两个字段名;接入商品前要真机确认哪个是「产品长」 | |
||||
| 8 | 试算 / 地址属性文档的路径写的是 `open-api.ehenglin.com`、`thebizark.com` | 与 `ehengjian.com` 不同域,疑似旧域名或从别家文档复制;接入前必须真机核对 | |
||||
| 9 | 几乎所有接口页**没有验签 / 请求头说明** | 真机返回早于业务码的 Spring 错误页,说明鉴权在网关层,文档没覆盖 | |
||||
|
||||
> 运去哪的教训:只按文档写代码,有 4 处接口一个都跑不通。恒健的文档完整度更差 |
||||
> (路径缺失、类型不一致、域名不一致),**接入任何写接口前必须先跑只读探针**。 |
||||
|
||||
## 2. 已接入(本期) |
||||
|
||||
| # | 接口 | 路径 | 能力位 | 状态 | |
||||
|---|---|---|---|---| |
||||
| 1 | 获取当前组织仓库 | `POST /v2/warehouse/getWarehouse` | `DIRECTORY` | ✅ | |
||||
| 2 | 获取物流渠道(全量) | `POST /v2/carrierGroup/getCarrierGroup` | `DIRECTORY` / `LOGISTICS_PRODUCT` | ✅ | |
||||
| 3 | 获取仓库支持的物流渠道 | `POST /v2/carrierGroup/getWarehouseCarrierGroupServices` | 同上(适配器方法,非 capability) | ✅ | |
||||
| 4 | 回调 | — | — | ❌ 文档无回调页 | |
||||
|
||||
三个接口都是无副作用查询、都不依赖单号,所以用来先验证鉴权与信封。 |
||||
|
||||
### 返回形状差异 |
||||
|
||||
| 接口 | `data` | |
||||
|---|---| |
||||
| `getWarehouse` | 数组 | |
||||
| `getCarrierGroup` | 数组 | |
||||
| `getWarehouseCarrierGroupServices` | **对象**:`{"EFCA":[{...}], "EFGA":[...]}` | |
||||
|
||||
第三个接口只取请求的那个仓的键——别的仓的渠道混进来,会把「仓不支持该渠道」 |
||||
推到仓方去报错。 |
||||
|
||||
### 字段口径 |
||||
|
||||
| 统一模型字段 | 恒健字段 | 说明 | |
||||
|---|---|---| |
||||
| `WarehouseFacility.warehouseCode` | `warehouseCode` | 唯一标识,下单也用它 | |
||||
| `WarehouseFacility.providerWarehouseId` | — | 恒健没有独立内部 id,恒为 null | |
||||
| `WarehouseFacility.contactName/mobilePhone/email` | — | 文档仓对象没有这三个字段,**恒为 null**(平台限制) | |
||||
| `WarehouseFacility.postcode` | `postal` | 字段名不同 | |
||||
| `LogisticsProduct.logisticsProductCode` | `code` | 下单的 `carrierCode` 用它 | |
||||
| `LogisticsProduct.logisticsProductName` | `carrier` + `carrierServiceName` | 统一模型只有一个名称字段,拼成「UPS - Ground」 | |
||||
| `LogisticsProduct.crossCountry` | — | 恒健无此维度,恒 false(**不是**「不支持跨国」) | |
||||
|
||||
## 3. 未接入(文档已有,按需排期) |
||||
|
||||
按能力位分组,路径取自文档(**标注 ⚠ 的表示文档没写路径或路径可疑,需真机核对**): |
||||
|
||||
### 出库(`OUTBOUND`) |
||||
|
||||
| 接口 | 路径 | |
||||
|---|---| |
||||
| 创建销售发货单(带附件) | `POST /v1/saleOrder/create` → 返回 `data.orderId` | |
||||
| Create Sale Order With Label(英文版,同路径) | `POST /v1/saleOrder/create` | |
||||
| 订单详情 | `POST /v1/saleOrder/findOne` | |
||||
| 订单列表 | `GET /v1/saleOrder/findByPage` | |
||||
| 订单取消 | `POST /v1/saleOrder/cancel`(`orderId` + `orderNo` 都必填) | |
||||
| 订单上传附件 | `POST /v1/saleOrder/createAttachment` | |
||||
| 物流异动单 创建 / 查询 / 取消 | `POST /v1/trackingChange/create`、`POST /v1/saleOrder/findOrder`、`POST /v1/trackingChange/cancel` | |
||||
|
||||
要点: |
||||
|
||||
- 创建接口的必填字段:`orderNo`、`shipToCountry`、`shipToState`、`shipToCity`、`shipToPostal`、 |
||||
`shipToAddress1`、`shipToContact`、`shipToTelephone`、`createdAt`(英文版页标注 `Y`;中文版页标 `否`, |
||||
**两页矛盾**)、`productItems`(每行的 `sku/quantity/isInsure/isSignature`)、`attachInfoItems`。 |
||||
- `attachInfoItems.type`:`0` ShippingLabel / `1` PackingList / `2` BOL / `3` Other / `4` CartonLabel / |
||||
`5` PalletLabel / `6` itemlabel。`url` 与 `file`(base64) 二选一。 |
||||
- `orderStatusEnum` 取值:`pending / unshipped / approved / assigned / picked / shipped / canceled / refunded` |
||||
——与运去哪**同名但不同源**,必须各建一套平台枚举。 |
||||
- `isSignature`:`0` 否 / `1` 直接签收 / `2` 成人签收 / `3` 间接签收(仅 FedEx)。 |
||||
- 取消接口需要**创建时由仓方返回的 `orderId`**(`findByPage` 也回 `orderId`), |
||||
只给单号不行——所以 `OutboundReceipt.providerOrderId` 必须落库。 |
||||
|
||||
### 库存(`INVENTORY_QUERY`) |
||||
|
||||
| 接口 | 路径 | |
||||
|---|---| |
||||
| 查询库存(按 SKU) | `POST /v1/inventory/getInventory`(`skus` 必填) | |
||||
| 批量查询库存(分页) | `GET /v2/inventory/get_inventory_by_page` | |
||||
| 批次库存查询 | `POST v1/inventory/batch/getInventoryBatchByWarehouseCode`(⚠ 文档少了前导 `/`) | |
||||
| 库存批次快照 | `POST /v1/inventory/batch/getInventoryBatchSnapshotByPage` | |
||||
| 库存变动明细(流水) | `POST /v1/inventory/task/query`(该页要求 `Authorization: Bearer`,见冲突 #2) | |
||||
|
||||
库存字段:`inventoryType`(0 可售 / 1 不可售)、`inventoryAvailable`、`inventoryReserved`、 |
||||
`inventoryTransport`、`inventoryCurrent`、`updatedAt`。注意 `inventoryTransport` 与 |
||||
`inventoryCurrent` 文档标成 STRING,数量类最终要转 int。 |
||||
|
||||
### 商品(`PRODUCT`) |
||||
|
||||
`POST /v1/product/save`(创建/编辑)、`POST /v1/product/getBySku`、`GET /v1/productChannel/findByPage`、 |
||||
`POST /v2/product/queryPage`(分页 SKU,含产品打托信息)、`POST /v1/product/createProductAlias`。 |
||||
尺寸 cm / 重量 g,与统一模型一致(不需要换算)。 |
||||
|
||||
### 入库(`INBOUND`) |
||||
|
||||
入库计划创建 / 列表 / 查询 / 取消 / 加附件 / 上传附件 / 发运 / 更新到仓日期 / 生成箱标, |
||||
预约单创建 / 修改 / 取消 / 信息查询 / 日期查询。路径以 `/v1/inbound/...`、`/v3/booking_order/...` 为主。 |
||||
|
||||
### 调拨 / 退货 / 销毁 / 计费 / 测算 |
||||
|
||||
| 领域 | 规模 | |
||||
|---|---| |
||||
| 调拨 | 创建 / 查询 / 取消 / 上传附件(`/v1/transferPlan/...`) | |
||||
| 退货 | 旧版 3 个(标「废弃」)+ v2 10 个(`/v1/saleReturn/...`、`/v3/hj_wms/receiptReturn`) | |
||||
| 销毁 | 创建 / 取消 / 批量查询(`/v2/destroyPlanOrder/...`) | |
||||
| 计费 | 尾程配送费 / 仓储费明细 / 作业费账单明细 | |
||||
| 测算 | 测算费用 `/v2/api/shipping/calculate`、地址属性 `/v2/api/shipping/addressClassification`(⚠ 域名可疑) | |
||||
|
||||
## 4. 代码结构 |
||||
|
||||
``` |
||||
warehouse-sdk-hengjian/ |
||||
├── pom.xml |
||||
└── src/ |
||||
├── main/java/common/ecommerce/hengjian/ |
||||
│ ├── HengjianConstants.java 端点 / 路径 / 两个授权头 / 成功码 / 未授权码 / 限流 |
||||
│ ├── adapter/ |
||||
│ │ ├── HengjianAdapter.java 仓库目录 + 承运商 + 按仓渠道 |
||||
│ │ ├── HengjianAdapterFactory.java |
||||
│ │ └── HengjianDirectoryMapper.java 字段搬运 |
||||
│ ├── dto/ |
||||
│ │ ├── HengjianWarehouseDtos.java |
||||
│ │ └── HengjianCarrierGroupDtos.java 两个渠道接口共用行模型 |
||||
│ ├── enums/package-info.java 状态枚举约定(待建) |
||||
│ ├── http/ |
||||
│ │ ├── HengjianRequestFactory.java 双授权头 + 链路 ID |
||||
│ │ ├── HengjianEnvelope.java 三种形态信封校验 |
||||
│ │ └── HengjianRateLimiter.java |
||||
│ └── webhook/package-info.java 文档无回调,未实现 |
||||
└── test/java/common/ecommerce/hengjian/ |
||||
├── adapter/HengjianDirectoryTest.java 13 个:请求形状 / 鉴权头 / 映射 / 能力位 |
||||
├── adapter/HengjianAdapterTest.java 4 个:注册 / 能力拒绝 / 枚举 |
||||
├── http/HengjianEnvelopeTest.java 11 个:三种信封形态 + 错误路径 |
||||
└── probe/HengjianReadOnlyProbeTest.java 默认跳过,凭据走系统属性 |
||||
``` |
||||
|
||||
已验证:`mvn -pl warehouse-sdk-hengjian -am test` 全部通过(28 个 + 1 个跳过)。 |
||||
|
||||
## 5. 探针用法 |
||||
|
||||
```bash |
||||
mvn -pl warehouse-sdk-hengjian -DfailIfNoTests=false \ |
||||
-Dhengjian.probe=true \ |
||||
-Dhengjian.probe.token=<组织token> \ |
||||
-Dhengjian.probe.providerWarehouseId=EFCA \ |
||||
-Dtest=HengjianReadOnlyProbeTest test |
||||
``` |
||||
|
||||
- 默认跳过;token 不入库、只走系统属性。 |
||||
- 4 个用例:仓库目录 / 全量渠道 / 按仓渠道 / 承运商代码去重。异常只打印不中断。 |
||||
- 只读,不建单。 |
||||
|
||||
## 6. 待确认(交给业务方 / 恒健) |
||||
|
||||
| # | 要确认 | 影响 | |
||||
|---|---|---| |
||||
| 1 | **有效 token 与测试仓代码** | 没有就无法跑探针,后续接口一律「未验证」 | |
||||
| 2 | 两个授权头是否必须同时带、是否同值 | 决定 `HengjianRequestFactory` 能否精简 | |
||||
| 3 | 新约定(`Authorization: Bearer`)与旧双头是否二选一 | 冲突 #2,决定后续接口按哪套实现 | |
||||
| 4 | **是否有回调(Webhook)文档** | 没有回调就只能轮询订单状态 | |
||||
| 5 | 限流值、单日配额 | 现在是保守默认 2 req/s | |
||||
| 6 | 能否在 PR 环境走写操作(建单 / 取消) | 决定全链路探针怎么设计 | |
||||
| 7 | 计费 / 测算接口的真实域名 | 文档写的是 `ehenglin.com` / `thebizark.com` | |
||||
| 8 | 商品「产品长」到底是 `length` 还是 `itemLength` | 接入商品前必须确认,否则尺寸错位 | |
||||
| 9 | 是否有沙箱测试 SKU | 建单需要仓方系统里真实存在的 SKU(运去哪的 `lineCode` 就踩过这个坑) | |
||||
| 10 | 时区口径 | 文档多处写 UTC,但仓在美国;需真机确认返回的时间到底是不是 UTC | |
||||
|
||||
## 7. 下一步 |
||||
|
||||
1. 拿到 token 后跑 `HengjianReadOnlyProbeTest`,把结论补进本文档「文档与实际不一致」表。 |
||||
2. 按 [onboarding-checklist.md](../onboarding-checklist.md) 阶段 2 逐接口接入,建议顺序: |
||||
**出库(创建 / 详情 / 列表 / 取消)→ 库存(按 SKU + 分页)→ 商品 → 入库 → 退货 v2**。 |
||||
3. 每个写接口接入前先确认第 6 节的 1 / 6 / 9 三项,否则写接口只能停在「有代码、未验证」。 |
||||
4. 出库状态枚举按 `orderStatusEnum` 全量建(8 个值),未知归 `UNKNOWN`,原值进 `rawStatus`; |
||||
注意 `unshipped` / `shipped` 必须精确匹配,不能用 `contains("SHIP")`。 |
||||
@ -0,0 +1,49 @@
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" |
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
||||
<modelVersion>4.0.0</modelVersion> |
||||
|
||||
<parent> |
||||
<groupId>ecommerce</groupId> |
||||
<artifactId>channel-sdk-parent</artifactId> |
||||
<version>1.0.0-SNAPSHOT</version> |
||||
</parent> |
||||
|
||||
<artifactId>warehouse-sdk-hengjian</artifactId> |
||||
<description>恒健(HengJian / Efulfill)三方仓适配器(3PL 仓储履约)</description> |
||||
|
||||
<dependencies> |
||||
<dependency> |
||||
<groupId>ecommerce</groupId> |
||||
<artifactId>sdk-common</artifactId> |
||||
</dependency> |
||||
<dependency> |
||||
<groupId>ecommerce</groupId> |
||||
<artifactId>warehouse-sdk-core</artifactId> |
||||
</dependency> |
||||
<dependency> |
||||
<groupId>com.fasterxml.jackson.core</groupId> |
||||
<artifactId>jackson-databind</artifactId> |
||||
</dependency> |
||||
<dependency> |
||||
<groupId>com.squareup.okhttp3</groupId> |
||||
<artifactId>okhttp</artifactId> |
||||
</dependency> |
||||
<dependency> |
||||
<groupId>org.slf4j</groupId> |
||||
<artifactId>slf4j-api</artifactId> |
||||
</dependency> |
||||
|
||||
<dependency> |
||||
<groupId>ecommerce</groupId> |
||||
<artifactId>warehouse-sdk-testkit</artifactId> |
||||
<scope>test</scope> |
||||
</dependency> |
||||
<dependency> |
||||
<groupId>org.junit.jupiter</groupId> |
||||
<artifactId>junit-jupiter</artifactId> |
||||
<scope>test</scope> |
||||
</dependency> |
||||
</dependencies> |
||||
</project> |
||||
@ -0,0 +1,81 @@
@@ -0,0 +1,81 @@
|
||||
package common.ecommerce.hengjian; |
||||
|
||||
/** |
||||
* 恒健(HengJian / Efulfill)协议常量。 |
||||
* |
||||
* <p>端点与路径是<b>协议的一部分</b>,写在代码里,不做成配置表。 |
||||
* 运行时不使用 {@link #TEST_BASE_URL}:端点由调用方每次经 |
||||
* {@code WarehouseConnection} 传入。</p> |
||||
* |
||||
* <p>依据恒健语雀《OpenAPI接口文档》(book tvzvkk,2026-11 核对)。 |
||||
* 该文档单篇接口页里<b>没有</b>写鉴权细节,鉴权只在《基础API调用》一页, |
||||
* 且写了两个都叫「授权Token」的请求头。</p> |
||||
*/ |
||||
public final class HengjianConstants { |
||||
|
||||
/** 适配器标识。 */ |
||||
public static final String ADAPTER_ID = "hengjian"; |
||||
|
||||
/** |
||||
* 测试 / 联调环境基址。 |
||||
* |
||||
* <p>文档写的是 {@code https://pr-open-api.ehengjian.com},末尾不带斜杠,
|
||||
* 与 {@code WarehouseConnection} 的归一化一致,路径直接以 {@code /} 开头拼接。</p> |
||||
*/ |
||||
public static final String TEST_BASE_URL = "https://pr-open-api.ehengjian.com"; |
||||
|
||||
/** 生产环境基址;运行时不使用,调用方需要时自己传。 */ |
||||
public static final String PRODUCTION_BASE_URL = "https://open-api.ehengjian.com"; |
||||
|
||||
/** |
||||
* 授权请求头 1:{@code Authorization}。 |
||||
* |
||||
* <p>文档把 {@code Authorization} 与 {@code x-api-key} 两个头都标成「授权Token」, |
||||
* 且都标「必须」,所以两个都带、取值相同(复用 {@code ChannelSecret.appSecret()})。</p> |
||||
* |
||||
* <p><b>真机尚不能确认是否可以只带一个</b>:用一个无效 token 试过, |
||||
* 只带一个和两个都带都返回 500「未知的账户!」,区分不出是哪个头在起作用。 |
||||
* 拿到有效 token 后应补一次对照实验,再决定能否精简。</p> |
||||
*/ |
||||
public static final String AUTHORIZATION_HEADER = "Authorization"; |
||||
|
||||
/** 授权请求头 2:{@code x-api-key};取值同 {@link #AUTHORIZATION_HEADER}。 */ |
||||
public static final String API_KEY_HEADER = "x-api-key"; |
||||
|
||||
/** 获取当前组织仓库(无参数)。 */ |
||||
public static final String PATH_WAREHOUSE_LIST = "/v2/warehouse/getWarehouse"; |
||||
|
||||
/** 获取物流渠道(无参数):全部承运商服务的扁平清单。 */ |
||||
public static final String PATH_CARRIER_GROUP = "/v2/carrierGroup/getCarrierGroup"; |
||||
|
||||
/** 获取仓库支持的物流渠道:按仓代码过滤。 */ |
||||
public static final String PATH_WAREHOUSE_CARRIER_GROUP = |
||||
"/v2/carrierGroup/getWarehouseCarrierGroupServices"; |
||||
|
||||
/** 业务成功码;文档各接口一致写 {@code 200}。 */ |
||||
public static final int SUCCESS_CODE = 200; |
||||
|
||||
/** |
||||
* 未授权 / 未知账户的业务码。 |
||||
* |
||||
* <p><b>真机观察</b>(2026-11-12,测试环境):不带任何授权头请求 |
||||
* {@code /v2/warehouse/getWarehouse},HTTP 仍是 <b>200</b>,body 是 |
||||
* {@code {"statusCode":500,"status":1,"code":999999,"message":"查询失败Unauthorized"}}。 |
||||
* 带上任意一个头(值无效)时则返回 Spring 的 500 错误页 |
||||
* {@code {"status":500,...,"message":"未知的账户!"}}。</p> |
||||
* |
||||
* <p>因此这个码必须按<b>认证失败</b>处理,不能当普通业务失败——否则宿主只会看到 |
||||
* 一条「业务码非 200」,不会去刷新凭据。</p> |
||||
*/ |
||||
public static final int UNAUTHORIZED_CODE = 999999; |
||||
|
||||
/** |
||||
* 限流:每秒许可数。 |
||||
* |
||||
* <p>恒健文档未公开限流值,先按三家仓的保守默认 2 req/s/仓;联调确认后只改这一处。</p> |
||||
*/ |
||||
public static final int PERMITS_PER_SECOND = 2; |
||||
|
||||
private HengjianConstants() { |
||||
} |
||||
} |
||||
@ -0,0 +1,215 @@
@@ -0,0 +1,215 @@
|
||||
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.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.warehouse.capability.LogisticsProductCapable; |
||||
import common.ecommerce.warehouse.capability.WarehouseDirectoryCapable; |
||||
import common.ecommerce.warehouse.enums.WarehouseCapability; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.error.WarehouseException; |
||||
import common.ecommerce.warehouse.model.LogisticsProduct; |
||||
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 DIRECTORY} 与 {@code LOGISTICS_PRODUCT} 两个能力位。</p> |
||||
* |
||||
* <p>出库 / 库存 / 入库 / 退货等接口<b>尚未接入</b>,能力位不声明: |
||||
* 门面调用会显式抛 {@code WarehouseUnsupportedCapabilityException},不返回空集合。</p> |
||||
* |
||||
* <p>适配器只持有协议与基础设施,不持有端点与凭据——两者随每次调用经 |
||||
* {@code WarehouseConnection} 传入。</p> |
||||
*/ |
||||
public final class HengjianAdapter implements WarehouseDirectoryCapable, LogisticsProductCapable { |
||||
|
||||
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 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.DIRECTORY, |
||||
WarehouseCapability.LOGISTICS_PRODUCT); |
||||
} |
||||
|
||||
// ------------------------------------------------------------------ 仓库目录
|
||||
|
||||
/** |
||||
* 当前组织下的全部仓库({@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; |
||||
} |
||||
} |
||||
@ -0,0 +1,35 @@
@@ -0,0 +1,35 @@
|
||||
package common.ecommerce.hengjian.adapter; |
||||
|
||||
import common.ecommerce.hengjian.HengjianConstants; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.http.OkHttpTransport; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.sdk.WarehouseAdapter; |
||||
import common.ecommerce.warehouse.sdk.WarehouseAdapterFactory; |
||||
|
||||
/** |
||||
* 恒健适配器工厂。 |
||||
* |
||||
* <p>端点与凭据由调用方在每次请求时传入,工厂只装配协议与基础设施。 |
||||
* 恒健是组织级固定 token(两个请求头),没有换取 / 续约流程,所以不需要 |
||||
* {@code TokenStore} / {@code LockProvider}——与运去哪同构,与信仓不同。</p> |
||||
*/ |
||||
public final class HengjianAdapterFactory implements WarehouseAdapterFactory { |
||||
|
||||
@Override |
||||
public String adapterId() { |
||||
return HengjianConstants.ADAPTER_ID; |
||||
} |
||||
|
||||
@Override |
||||
public WarehouseProvider provider() { |
||||
return WarehouseProvider.HENGJIAN; |
||||
} |
||||
|
||||
@Override |
||||
public WarehouseAdapter create(AdapterConfig config) { |
||||
return new HengjianAdapter( |
||||
new OkHttpTransport("common-ecommerce/1.0.0 (hengjian)"), |
||||
new JacksonJsonCodec()); |
||||
} |
||||
} |
||||
@ -0,0 +1,106 @@
@@ -0,0 +1,106 @@
|
||||
package common.ecommerce.hengjian.adapter; |
||||
|
||||
import common.ecommerce.hengjian.dto.HengjianCarrierGroupDtos; |
||||
import common.ecommerce.hengjian.dto.HengjianWarehouseDtos; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.LogisticsProduct; |
||||
import common.ecommerce.warehouse.model.WarehouseFacility; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 恒健仓库档案与物流渠道映射。 |
||||
* |
||||
* <p>只做字段搬运,不发请求、不读配置。</p> |
||||
*/ |
||||
public final class HengjianDirectoryMapper { |
||||
|
||||
private HengjianDirectoryMapper() { |
||||
} |
||||
|
||||
/** |
||||
* 仓库行 → 统一仓库档案。 |
||||
* |
||||
* <p>恒健文档的仓对象<b>没有联系人、电话、邮箱字段</b>(运去哪 / 信仓有), |
||||
* 所以 {@code contactName / mobilePhone / email} 恒为 null——这是平台限制, |
||||
* 不是漏接。</p> |
||||
*/ |
||||
public static List<WarehouseFacility> toWarehouses(List<HengjianWarehouseDtos.WarehouseRow> rows) { |
||||
List<WarehouseFacility> out = new ArrayList<WarehouseFacility>(); |
||||
if (rows == null) { |
||||
return out; |
||||
} |
||||
for (HengjianWarehouseDtos.WarehouseRow row : rows) { |
||||
if (row == null || blank(row.warehouseCode)) { |
||||
// 没有仓代码的行没法下单,跳过而不是造一条空档案
|
||||
continue; |
||||
} |
||||
out.add(WarehouseFacility.builder() |
||||
.sourceProvider(WarehouseProvider.HENGJIAN) |
||||
.warehouseCode(row.warehouseCode.trim()) |
||||
.name(trimToNull(row.name)) |
||||
.country(trimToNull(row.country)) |
||||
.state(trimToNull(row.state)) |
||||
.province(trimToNull(row.state)) |
||||
.city(trimToNull(row.city)) |
||||
.address1(trimToNull(row.address1)) |
||||
.address2(trimToNull(row.address2)) |
||||
.postcode(trimToNull(row.postal)) |
||||
.build()); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
/** |
||||
* 承运商服务行 → 统一物流产品。 |
||||
* |
||||
* <p>{@code logisticsProductCode} 取恒健的 {@code code}(下单的 {@code carrierCode}), |
||||
* 名称拼成「承运商 + 服务名」——恒健把承运商和服务分在两列,统一模型只有一个名称字段。</p> |
||||
* |
||||
* <p>{@code crossCountry} 恒为 false:恒健文档没有这个维度,<b>不是</b>「不支持跨国」。</p> |
||||
* |
||||
* @param warehouseCode 仓代码;全量渠道接口没有这个维度时传 null |
||||
*/ |
||||
public static List<LogisticsProduct> toProducts( |
||||
List<HengjianCarrierGroupDtos.CarrierServiceRow> rows, String warehouseCode) { |
||||
List<LogisticsProduct> out = new ArrayList<LogisticsProduct>(); |
||||
if (rows == null) { |
||||
return out; |
||||
} |
||||
for (HengjianCarrierGroupDtos.CarrierServiceRow row : rows) { |
||||
if (row == null || blank(row.code)) { |
||||
continue; |
||||
} |
||||
out.add(LogisticsProduct.builder() |
||||
.sourceProvider(WarehouseProvider.HENGJIAN) |
||||
.warehouseCode(trimToNull(warehouseCode)) |
||||
.logisticsProductCode(row.code.trim()) |
||||
.logisticsProductName(displayName(row)) |
||||
.crossCountry(false) |
||||
.build()); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
/** 「承运商 - 服务名」;缺哪个就只用另一个,都没有给 null。 */ |
||||
public static String displayName(HengjianCarrierGroupDtos.CarrierServiceRow row) { |
||||
String carrier = trimToNull(row.carrier); |
||||
String service = trimToNull(row.carrierServiceName); |
||||
if (carrier == null) { |
||||
return service; |
||||
} |
||||
if (service == null) { |
||||
return carrier; |
||||
} |
||||
return carrier + " - " + service; |
||||
} |
||||
|
||||
static boolean blank(String v) { |
||||
return v == null || v.trim().isEmpty(); |
||||
} |
||||
|
||||
private static String trimToNull(String v) { |
||||
return blank(v) ? null : v.trim(); |
||||
} |
||||
} |
||||
@ -0,0 +1,50 @@
@@ -0,0 +1,50 @@
|
||||
package common.ecommerce.hengjian.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 恒健报文结构:《获取物流渠道》({@code POST /v2/carrierGroup/getCarrierGroup},无请求参数) |
||||
* 与《获取仓库支持的物流渠道》({@code POST |
||||
* /v2/carrierGroup/getWarehouseCarrierGroupServices})。 |
||||
* |
||||
* <p>两个接口返回的行结构完全一样,只有外层形状不同:</p> |
||||
* <ul> |
||||
* <li>全量渠道:{@code data} 是数组;</li> |
||||
* <li>按仓过滤:{@code data} 是以仓代码为键的对象, |
||||
* {@code {"EFCA":[{...}]}}。</li> |
||||
* </ul> |
||||
* <p>所以行模型共用,外层各自声明。</p> |
||||
*/ |
||||
public final class HengjianCarrierGroupDtos { |
||||
|
||||
private HengjianCarrierGroupDtos() { |
||||
} |
||||
|
||||
/** 一个承运商服务。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CarrierServiceRow { |
||||
|
||||
/** 物流产品代码;下单的 {@code carrierCode} 用它。 */ |
||||
public String code; |
||||
/** 承运商代码,如 {@code UPS};下单的 {@code carrier} 用它。 */ |
||||
public String carrier; |
||||
/** 物流产品服务名称,给人看。 */ |
||||
public String carrierServiceName; |
||||
} |
||||
|
||||
/** |
||||
* 按仓过滤的响应 {@code data} 形状:仓代码 → 该仓可用的服务清单。 |
||||
* |
||||
* <p>键是动态的仓代码,不能声明成固定字段;解析时按 JSON 顶层对象逐键读取。</p> |
||||
*/ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class WarehouseCarrierGroupRow { |
||||
|
||||
/** 仓代码(由解析时注入)。 */ |
||||
public String warehouseCode; |
||||
/** 该仓可用服务。 */ |
||||
public List<CarrierServiceRow> services; |
||||
} |
||||
} |
||||
@ -0,0 +1,42 @@
@@ -0,0 +1,42 @@
|
||||
package common.ecommerce.hengjian.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
/** |
||||
* 恒健报文结构:获取当前组织仓库({@code POST /v2/warehouse/getWarehouse},无请求参数)。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构; |
||||
* 与其它接口共用的结构各自复制一份,避免跨接口耦合。</p> |
||||
*/ |
||||
public final class HengjianWarehouseDtos { |
||||
|
||||
private HengjianWarehouseDtos() { |
||||
} |
||||
|
||||
/** |
||||
* 仓库行。 |
||||
* |
||||
* <p>字段名照抄文档。<b>恒健没有给仓方内部 id</b>,{@code warehouseCode} 就是下单时 |
||||
* 要传的仓代码,也是唯一标识。</p> |
||||
*/ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class WarehouseRow { |
||||
|
||||
/** 仓库 code;下单的 {@code warehouseCode} 用它。 */ |
||||
public String warehouseCode; |
||||
/** 仓库名称。 */ |
||||
public String name; |
||||
/** 国家,2 位。 */ |
||||
public String country; |
||||
/** 州;文档写作「州」。 */ |
||||
public String state; |
||||
/** 城市。 */ |
||||
public String city; |
||||
/** 地址 1。 */ |
||||
public String address1; |
||||
/** 地址 2。 */ |
||||
public String address2; |
||||
/** 邮编。 */ |
||||
public String postal; |
||||
} |
||||
} |
||||
@ -0,0 +1,10 @@
@@ -0,0 +1,10 @@
|
||||
/** |
||||
* 恒健报文结构(DTO)。 |
||||
* |
||||
* <p><b>约定</b>:一个接口一个文件,不建大而全的 Dtos;字段名照抄文档, |
||||
* 连拼写错误也照抄并加注释说明;保留 {@code @JsonInclude(NON_NULL)}。</p> |
||||
* |
||||
* <p>恒健文档里接口路径统一前缀 {@code /v1} 或 {@code /v2};字段多为 camelCase, |
||||
* 目前只出现一处文档笔误(见 {@code docs-warehouse/hengjian/README.md} 的「文档与实际不符」)。</p> |
||||
*/ |
||||
package common.ecommerce.hengjian.dto; |
||||
@ -0,0 +1,18 @@
@@ -0,0 +1,18 @@
|
||||
/** |
||||
* 恒健平台枚举(<b>本期尚未建立</b>)。 |
||||
* |
||||
* <p>只读基础资料阶段没有状态码。接入出库 / 库存 / 退货时按 |
||||
* {@code docs-warehouse/onboarding-checklist.md} 阶段 2.6 建:</p> |
||||
* |
||||
* <ul> |
||||
* <li>带仓方原始码 + {@code toCore()} 映射到底层枚举;</li> |
||||
* <li><b>精确匹配</b>不用 {@code contains};未知值归 {@code UNKNOWN} 不猜;</li> |
||||
* <li>提供反向 {@code codeOf()} 供下发;</li> |
||||
* <li>用完的原值同时写进模型的 {@code rawStatus}。</li> |
||||
* </ul> |
||||
* |
||||
* <p>恒健已知的状态字段:{@code /v1/saleOrder/findByPage} 的 {@code orderStatusEnum} |
||||
* 取值为 {@code pending / unshipped / approved / assigned / picked / shipped / |
||||
* canceled / refunded}——注意与运去哪<b>同名</b>,但那是巧合,两套码表各建各的。</p> |
||||
*/ |
||||
package common.ecommerce.hengjian.enums; |
||||
@ -0,0 +1,197 @@
@@ -0,0 +1,197 @@
|
||||
package common.ecommerce.hengjian.http; |
||||
|
||||
import common.ecommerce.http.HttpResponse; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.hengjian.HengjianConstants; |
||||
import common.ecommerce.shared.error.AuthException; |
||||
import common.ecommerce.shared.error.PlatformBusinessException; |
||||
import common.ecommerce.shared.error.RateLimitException; |
||||
import common.ecommerce.shared.error.TransientException; |
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.warehouse.error.WarehouseException; |
||||
|
||||
/** |
||||
* 恒健响应信封校验。 |
||||
* |
||||
* <p>恒健统一信封(《基础API调用》与绝大多数接口页一致):</p> |
||||
* <pre> |
||||
* { "statusCode": 200, "status": 0, "code": 200, "message": "查询成功" } |
||||
* </pre> |
||||
* |
||||
* <p>HTTP 通常恒为 200,成败看 <b>body 里的 {@code code}:200 成功</b>。 |
||||
* 少数接口页只列 {@code code + message}(如查询库存),也有的把 {@code code} |
||||
* 标成 STRING;这里统一按文本读再转数字,两种形态都能识别。</p> |
||||
* |
||||
* <p><b>真机观察(2026-11-12,测试环境):</b></p> |
||||
* <ul> |
||||
* <li>不带授权头:HTTP 200 + {@code {"statusCode":500,"status":1,"code":999999, |
||||
* "message":"查询失败Unauthorized"}};</li> |
||||
* <li>只带一个授权头(值无效):HTTP 500 + Spring 错误页 |
||||
* {@code {"status":500,"error":"Internal Server Error","message":"未知的账户!"}}。</li> |
||||
* </ul> |
||||
* <p>前者按认证失败处理({@link AuthException});后者没有业务码,按 HTTP 5xx |
||||
* 归 {@link TransientException},但「未知的账户」实际是凭据问题,所以单独识别成 |
||||
* {@link AuthException},避免宿主无意义重试。</p> |
||||
*/ |
||||
public final class HengjianEnvelope { |
||||
|
||||
/** 业务成功码。 */ |
||||
public static final int SUCCESS_CODE = HengjianConstants.SUCCESS_CODE; |
||||
|
||||
private final String rawBody; |
||||
|
||||
private HengjianEnvelope(String rawBody) { |
||||
this.rawBody = rawBody; |
||||
} |
||||
|
||||
/** |
||||
* 校验 HTTP 状态与业务码。 |
||||
* |
||||
* @throws AuthException 401 / 403,或业务码 999999,或「未知的账户」 |
||||
* @throws RateLimitException 429 |
||||
* @throws TransientException 5xx(认证相关的 500 除外) |
||||
* @throws ValidationException 其它 4xx / 空 body / 没有业务码 |
||||
* @throws PlatformBusinessException 业务码非成功 |
||||
*/ |
||||
public static HengjianEnvelope of(HttpResponse response, JacksonJsonCodec json, |
||||
String operation, String warehouseCode, String requestId) { |
||||
int status = response.statusCode(); |
||||
if (status == 401 || status == 403) { |
||||
throw new AuthException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian auth failed: http " + status) |
||||
.platformCode(String.valueOf(status)) |
||||
.rawResponse(truncate(response.body())) |
||||
.retryable(false)); |
||||
} |
||||
if (status == 429) { |
||||
throw new RateLimitException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian rate limited") |
||||
.platformCode(String.valueOf(status)) |
||||
.retryable(true), retryAfterMillis(response)); |
||||
} |
||||
if (status >= 500) { |
||||
// 只有一个授权头时恒健抛 Spring 500「未知的账户!」,这是凭据问题不是瞬时故障
|
||||
if (mentionsUnknownAccount(json, response.body())) { |
||||
throw new AuthException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian rejected the credential: unknown account") |
||||
.platformCode(String.valueOf(status)) |
||||
.rawResponse(truncate(response.body())) |
||||
.retryable(false)); |
||||
} |
||||
throw new TransientException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian server error: http " + status) |
||||
.platformCode(String.valueOf(status)) |
||||
.retryable(true), null); |
||||
} |
||||
if (status < 200 || status >= 300) { |
||||
throw new ValidationException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian request rejected: http " + status |
||||
+ ", body=" + truncate(response.body())) |
||||
.platformCode(String.valueOf(status)) |
||||
.rawResponse(truncate(response.body())) |
||||
.retryable(false)); |
||||
} |
||||
|
||||
String body = response.body(); |
||||
if (body == null || body.trim().isEmpty()) { |
||||
throw new ValidationException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian returned an empty body; cannot verify business code") |
||||
.platformCode(String.valueOf(status)) |
||||
.retryable(false)); |
||||
} |
||||
|
||||
int code = firstPresentCode(json, body); |
||||
if (code == Integer.MIN_VALUE) { |
||||
throw new ValidationException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian response has no business code: " + truncate(body)) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(false)); |
||||
} |
||||
if (code == HengjianConstants.UNAUTHORIZED_CODE) { |
||||
throw new AuthException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian unauthorized: code=" + code + ", message=" + messageOf(json, body)) |
||||
.platformCode(String.valueOf(code)) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(false)); |
||||
} |
||||
if (code != SUCCESS_CODE) { |
||||
throw new PlatformBusinessException(base(operation, warehouseCode, requestId) |
||||
.message("hengjian business error: code=" + code + ", message=" + messageOf(json, body)) |
||||
.platformCode(String.valueOf(code)) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(false)); |
||||
} |
||||
return new HengjianEnvelope(body); |
||||
} |
||||
|
||||
/** 原始响应体(已确认业务成功)。 */ |
||||
public String body() { |
||||
return rawBody; |
||||
} |
||||
|
||||
/** |
||||
* 取业务码:先 {@code code},缺了再看 {@code status}。 |
||||
* |
||||
* <p>恒健有的接口页只写 {@code code},有的只写 {@code status},还有的把 |
||||
* {@code code} 标成 STRING。统一按文本读,缺失返回 {@link Integer#MIN_VALUE}。</p> |
||||
*/ |
||||
private static int firstPresentCode(JacksonJsonCodec json, String body) { |
||||
Integer code = intOrNull(json.stringAt(body, "code")); |
||||
if (code != null) { |
||||
return code; |
||||
} |
||||
Integer status = intOrNull(json.stringAt(body, "status")); |
||||
return status != null ? status : Integer.MIN_VALUE; |
||||
} |
||||
|
||||
private static boolean mentionsUnknownAccount(JacksonJsonCodec json, String body) { |
||||
String message = messageOf(json, body); |
||||
return message != null && message.contains("未知的账户"); |
||||
} |
||||
|
||||
/** 业务提示语;恒健用 {@code message}。 */ |
||||
private static String messageOf(JacksonJsonCodec json, String body) { |
||||
String message = json.stringAt(body, "message"); |
||||
return message != null ? message : json.stringAt(body, "msg"); |
||||
} |
||||
|
||||
private static Integer intOrNull(String value) { |
||||
if (value == null || value.trim().isEmpty()) { |
||||
return null; |
||||
} |
||||
try { |
||||
return Integer.valueOf(value.trim()); |
||||
} catch (NumberFormatException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
/** {@code Retry-After} 秒折算毫秒;缺失按 1s。 */ |
||||
private static long retryAfterMillis(HttpResponse response) { |
||||
String header = response.header("Retry-After"); |
||||
if (header == null || header.trim().isEmpty()) { |
||||
return 1000L; |
||||
} |
||||
try { |
||||
return Long.parseLong(header.trim()) * 1000L; |
||||
} catch (NumberFormatException e) { |
||||
return 1000L; |
||||
} |
||||
} |
||||
|
||||
private static WarehouseException.Builder base(String operation, String warehouseCode, |
||||
String requestId) { |
||||
return WarehouseException.builder() |
||||
.operation(operation) |
||||
.warehouseCode(warehouseCode) |
||||
.provider(HengjianConstants.ADAPTER_ID) |
||||
.requestId(requestId); |
||||
} |
||||
|
||||
private static String truncate(String body) { |
||||
if (body == null) { |
||||
return null; |
||||
} |
||||
return body.length() <= 2000 ? body : body.substring(0, 2000) + "..."; |
||||
} |
||||
} |
||||
@ -0,0 +1,65 @@
@@ -0,0 +1,65 @@
|
||||
package common.ecommerce.hengjian.http; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
import java.util.function.LongSupplier; |
||||
|
||||
/** |
||||
* 按接口路径的令牌桶(间隔式)。 |
||||
* |
||||
* <p>恒健文档未公开限流值,先按保守默认 {@link common.ecommerce.hengjian.HengjianConstants#PERMITS_PER_SECOND} |
||||
* 节流;429 的 {@code Retry-After} 由宿主处理,这里只做本地限速。</p> |
||||
* |
||||
* <p>进程内实现,多实例部署会叠加;需要跨实例限流时由宿主替换。 |
||||
* 可注入 {@link Sleeper} 与纳秒时钟,测试不真的 sleep。</p> |
||||
*/ |
||||
public final class HengjianRateLimiter { |
||||
|
||||
/** 便于测试注入,生产用 {@link Thread#sleep}。 */ |
||||
public interface Sleeper { |
||||
void sleep(long millis, int nanos); |
||||
} |
||||
|
||||
private final Map<String, Long> nextAllowed = new HashMap<String, Long>(); |
||||
private final Sleeper sleeper; |
||||
private final LongSupplier nanoClock; |
||||
|
||||
public HengjianRateLimiter() { |
||||
this(new Sleeper() { |
||||
@Override |
||||
public void sleep(long millis, int nanos) { |
||||
try { |
||||
Thread.sleep(millis, nanos); |
||||
} catch (InterruptedException e) { |
||||
Thread.currentThread().interrupt(); |
||||
} |
||||
} |
||||
}, new LongSupplier() { |
||||
@Override |
||||
public long getAsLong() { |
||||
return System.nanoTime(); |
||||
} |
||||
}); |
||||
} |
||||
|
||||
public HengjianRateLimiter(Sleeper sleeper, LongSupplier nanoClock) { |
||||
this.sleeper = sleeper; |
||||
this.nanoClock = nanoClock; |
||||
} |
||||
|
||||
/** 同一路径两次调用之间至少间隔 {@code 1e9 / permitsPerSecond} 纳秒。 */ |
||||
public synchronized void acquire(String path, int permitsPerSecond) { |
||||
if (permitsPerSecond <= 0) { |
||||
return; |
||||
} |
||||
long interval = 1_000_000_000L / permitsPerSecond; |
||||
long now = nanoClock.getAsLong(); |
||||
Long next = nextAllowed.get(path); |
||||
if (next != null && now < next) { |
||||
long wait = next - now; |
||||
sleeper.sleep(wait / 1_000_000L, (int) (wait % 1_000_000L)); |
||||
now = nanoClock.getAsLong(); |
||||
} |
||||
nextAllowed.put(path, now + interval); |
||||
} |
||||
} |
||||
@ -0,0 +1,137 @@
@@ -0,0 +1,137 @@
|
||||
package common.ecommerce.hengjian.http; |
||||
|
||||
import common.ecommerce.hengjian.HengjianConstants; |
||||
import common.ecommerce.http.HttpRequest; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.shared.audit.CallScope; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
|
||||
import java.io.UnsupportedEncodingException; |
||||
import java.net.URLEncoder; |
||||
import java.util.Collection; |
||||
import java.util.LinkedHashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* 构造恒健请求。 |
||||
* |
||||
* <p>鉴权是<b>组织级固定 token 放请求头</b>(《基础API调用》),没有换取 / 续约流程, |
||||
* 因此不经过 {@code TokenManager}。token 复用 {@link ChannelSecret#appSecret()} 承载。</p> |
||||
* |
||||
* <p>文档要求 {@code Authorization} 与 {@code x-api-key} <b>两个头都带</b>,取值相同; |
||||
* 真机用无效 token 试过,只带一个也返回「未知的账户!」,无法区分, |
||||
* 所以按文档两个都带。见 {@code HengjianConstants} 的说明。</p> |
||||
*/ |
||||
public final class HengjianRequestFactory { |
||||
|
||||
private final JacksonJsonCodec json; |
||||
|
||||
public HengjianRequestFactory(JacksonJsonCodec json) { |
||||
this.json = json; |
||||
} |
||||
|
||||
/** POST:业务参数放 JSON 请求体;无参数接口传 null 或空 body。 */ |
||||
public HttpRequest post(String baseUrl, String path, Object body, |
||||
ChannelSecret secret, CallScope ctx, String operation) { |
||||
return HttpRequest.builder() |
||||
.method("POST") |
||||
.url(baseUrl + path) |
||||
.contentType("application/json") |
||||
.headers(headers(secret, ctx)) |
||||
.body(body == null ? "{}" : json.toJson(body)) |
||||
.operation(operation) |
||||
.build(); |
||||
} |
||||
|
||||
/** GET:业务参数放 query。 */ |
||||
public HttpRequest get(String baseUrl, String path, Map<String, Object> params, |
||||
ChannelSecret secret, CallScope ctx, String operation) { |
||||
return HttpRequest.builder() |
||||
.method("GET") |
||||
.url(baseUrl + path + queryString(params)) |
||||
.headers(headers(secret, ctx)) |
||||
.operation(operation) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* GET:支持同名参数重复出现,如 {@code warehouseCodes=A&warehouseCodes=B}。 |
||||
* |
||||
* <p>恒健的「批量查询库存」文档把 {@code warehouseCodes} 写成 LIST 却用 GET, |
||||
* 这是唯一能表达数组的方式;联调时若仓方只认逗号分隔,改这里一处。</p> |
||||
*/ |
||||
public HttpRequest getMulti(String baseUrl, String path, Map<String, List<String>> params, |
||||
ChannelSecret secret, CallScope ctx, String operation) { |
||||
StringBuilder query = new StringBuilder(); |
||||
if (params != null) { |
||||
for (Map.Entry<String, List<String>> e : params.entrySet()) { |
||||
List<String> values = e.getValue(); |
||||
if (values == null) { |
||||
continue; |
||||
} |
||||
for (String value : values) { |
||||
if (value == null) { |
||||
continue; |
||||
} |
||||
query.append(query.length() == 0 ? '?' : '&'); |
||||
query.append(urlEncode(e.getKey())).append('=').append(urlEncode(value)); |
||||
} |
||||
} |
||||
} |
||||
return HttpRequest.builder() |
||||
.method("GET") |
||||
.url(baseUrl + path + query) |
||||
.headers(headers(secret, ctx)) |
||||
.operation(operation) |
||||
.build(); |
||||
} |
||||
|
||||
/** 本次调用统一携带的请求头:两个授权头 + 链路 ID。 */ |
||||
private static Map<String, String> headers(ChannelSecret secret, CallScope ctx) { |
||||
String token = requireToken(secret); |
||||
Map<String, String> out = new LinkedHashMap<String, String>(); |
||||
out.put(HengjianConstants.AUTHORIZATION_HEADER, token); |
||||
out.put(HengjianConstants.API_KEY_HEADER, token); |
||||
out.put("requestId", ctx.requestId()); |
||||
return out; |
||||
} |
||||
|
||||
/** 缺 token 直接失败:发一个没有鉴权的请求只会拿到看不懂的 Unauthorized。 */ |
||||
private static String requireToken(ChannelSecret secret) { |
||||
String token = secret == null ? null : secret.appSecret(); |
||||
if (token == null || token.trim().isEmpty()) { |
||||
throw new IllegalStateException("hengjian requires an organization token in ChannelSecret.appSecret()"); |
||||
} |
||||
return token; |
||||
} |
||||
|
||||
/** 拼 {@code ?k=v};null 值跳过,返回串自带前导 {@code ?}。 */ |
||||
private static String queryString(Map<String, Object> params) { |
||||
if (params == null) { |
||||
return ""; |
||||
} |
||||
StringBuilder sb = new StringBuilder(); |
||||
for (Map.Entry<String, Object> e : params.entrySet()) { |
||||
if (e.getValue() == null) { |
||||
continue; |
||||
} |
||||
if (e.getValue() instanceof Collection || e.getValue() instanceof Map) { |
||||
// 数组参数必须走 getMulti,否则会被序列化成看不懂的 JSON 串
|
||||
throw new IllegalStateException( |
||||
"hengjian GET does not support collection parameters; use getMulti: " + e.getKey()); |
||||
} |
||||
sb.append(sb.length() == 0 ? '?' : '&'); |
||||
sb.append(urlEncode(e.getKey())).append('=').append(urlEncode(String.valueOf(e.getValue()))); |
||||
} |
||||
return sb.toString(); |
||||
} |
||||
|
||||
private static String urlEncode(String v) { |
||||
try { |
||||
return URLEncoder.encode(v == null ? "" : v, "UTF-8"); |
||||
} catch (UnsupportedEncodingException e) { |
||||
throw new IllegalStateException(e); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,12 @@
@@ -0,0 +1,12 @@
|
||||
/** |
||||
* 恒健出入网层:请求构造、限流、响应信封校验。 |
||||
* |
||||
* <p>鉴权与其它仓不同:<b>两个请求头都要带</b>({@code Authorization} 与 |
||||
* {@code x-api-key},取值相同)。真机实测只带一个会返回「未知的账户!」, |
||||
* 详见 {@code HengjianConstants}。</p> |
||||
* |
||||
* <p>信封校验区分三种形态:正常业务信封({@code code=200} 成功)、 |
||||
* 未授权(HTTP 200 + {@code code=999999})、凭据被拒(HTTP 500 + 「未知的账户」)。 |
||||
* 后两种都映射成 {@code AuthException},见 {@code HengjianEnvelope}。</p> |
||||
*/ |
||||
package common.ecommerce.hengjian.http; |
||||
@ -0,0 +1,12 @@
@@ -0,0 +1,12 @@
|
||||
/** |
||||
* 恒健回调验签与解析(<b>待接入</b>)。 |
||||
* |
||||
* <p>恒健语雀文档目前<b>没有回调(Webhook)相关页面</b>:book 目录里只有 OpenAPI |
||||
* 接口,没有推送地址、验签算法或响应体约定。因此本期不声明 {@code WEBHOOK} 能力位, |
||||
* 也不实现 {@code WarehouseWebhookCapable}——声明了却解析不了,宿主会当能力可用。</p> |
||||
* |
||||
* <p>拿到回调文档后按 {@code docs-warehouse/callback.md} 接入:用 |
||||
* {@code WebhookSignatures}(HMAC + 恒定时间比较 + 时间窗);多个回调共用一个地址时 |
||||
* 按报文特征分派;回调也要走 {@code CallSupport.observe}。</p> |
||||
*/ |
||||
package common.ecommerce.hengjian.webhook; |
||||
@ -0,0 +1,88 @@
@@ -0,0 +1,88 @@
|
||||
package common.ecommerce.hengjian.adapter; |
||||
|
||||
import common.ecommerce.hengjian.HengjianConstants; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.error.WarehouseUnsupportedCapabilityException; |
||||
import common.ecommerce.warehouse.model.OutboundRef; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseSdk; |
||||
import common.ecommerce.warehouse.spi.WarehouseAccount; |
||||
import common.ecommerce.warehouse.testkit.InMemoryWarehouses; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Instant; |
||||
import java.time.ZoneOffset; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 恒健适配器门面契约:注册后能按 provider 解析,未实现的能力显式拒绝。 |
||||
*/ |
||||
class HengjianAdapterTest { |
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-12T00:00:00Z"), ZoneOffset.UTC); |
||||
private static final String WH = "HJ-EFCA"; |
||||
|
||||
private static WarehouseAccount account() { |
||||
return WarehouseAccount.builder() |
||||
.warehouseCode(WH) |
||||
.provider(WarehouseProvider.HENGJIAN.name()) |
||||
.providerWarehouseId("EFCA") |
||||
.credentialRef("kms://test/hengjian") |
||||
.timeZone("America/Los_Angeles") |
||||
.build(); |
||||
} |
||||
|
||||
private static WarehouseSdk sdk() { |
||||
return WarehouseSdk.builder() |
||||
.warehouseRepository(new InMemoryWarehouses().put(account())) |
||||
.clock(CLOCK) |
||||
.register(new HengjianAdapterFactory()) |
||||
.build(); |
||||
} |
||||
|
||||
private static WarehouseConnection conn() { |
||||
return WarehouseConnection.of(HengjianConstants.TEST_BASE_URL, |
||||
ChannelSecret.builder().appSecret("token-1").build()); |
||||
} |
||||
|
||||
@Test |
||||
void registersAndResolves() { |
||||
WarehouseSdk sdk = sdk(); |
||||
|
||||
assertTrue(sdk.capabilities(WH).supports( |
||||
common.ecommerce.warehouse.enums.WarehouseCapability.DIRECTORY)); |
||||
assertTrue(sdk.capabilities(WH).supports( |
||||
common.ecommerce.warehouse.enums.WarehouseCapability.LOGISTICS_PRODUCT)); |
||||
} |
||||
|
||||
/** 出库未接入:门面显式拒绝,不返回空列表。 */ |
||||
@Test |
||||
void unimplementedOutboundIsRejected() { |
||||
WarehouseSdk sdk = sdk(); |
||||
|
||||
assertThrows(WarehouseUnsupportedCapabilityException.class, |
||||
() -> sdk.warehouses(WH, conn()).outbound().get(OutboundRef.ofRequestNo("OB-1"))); |
||||
} |
||||
|
||||
/** 能力矩阵查询本身可用(不触发真实 API)。 */ |
||||
@Test |
||||
void capabilityQueryIsOffline() { |
||||
HengjianAdapter adapter = new HengjianAdapter(RecordingTransport.create(), new JacksonJsonCodec()); |
||||
|
||||
assertTrue(!adapter.capabilities().contains( |
||||
common.ecommerce.warehouse.enums.WarehouseCapability.INVENTORY_QUERY)); |
||||
} |
||||
|
||||
@Test |
||||
void providerEnumIsRegistered() { |
||||
assertEquals("恒健", WarehouseProvider.HENGJIAN.label()); |
||||
assertEquals(50, WarehouseProvider.HENGJIAN.code()); |
||||
} |
||||
} |
||||
@ -0,0 +1,251 @@
@@ -0,0 +1,251 @@
|
||||
package common.ecommerce.hengjian.adapter; |
||||
|
||||
import common.ecommerce.hengjian.HengjianConstants; |
||||
import common.ecommerce.hengjian.http.HengjianEnvelope; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.enums.WarehouseCapability; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.LogisticsProduct; |
||||
import common.ecommerce.warehouse.model.WarehouseFacility; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Instant; |
||||
import java.time.ZoneOffset; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertNull; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 恒健基础资料契约测试:请求形状、鉴权头、响应映射。 |
||||
* |
||||
* <p>全部基于录制夹具,无网络。</p> |
||||
*/ |
||||
class HengjianDirectoryTest { |
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-12T00:00:00Z"), ZoneOffset.UTC); |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("HJ-EFCA", WarehouseProvider.HENGJIAN, "EFCA", |
||||
WarehouseConnection.of(HengjianConstants.TEST_BASE_URL, |
||||
ChannelSecret.builder().appSecret("token-1").build()), |
||||
"req-1", CLOCK); |
||||
} |
||||
|
||||
private static HengjianAdapter adapter(RecordingTransport transport) { |
||||
return new HengjianAdapter(transport, new JacksonJsonCodec()); |
||||
} |
||||
|
||||
/** 文档示例的仓库结构。 */ |
||||
private static final String WAREHOUSE_BODY = |
||||
"{\"statusCode\":200,\"status\":0,\"code\":200,\"message\":\"查询成功\",\"data\":[" |
||||
+ "{\"warehouseCode\":\"EFCA\",\"name\":\"恒健加州仓\",\"country\":\"US\"," |
||||
+ "\"state\":\"CA\",\"city\":\"Los Angeles\",\"address1\":\"1 Main St\"," |
||||
+ "\"address2\":\"\",\"postal\":\"90001\"}," |
||||
+ "{\"warehouseCode\":\"EFNJ\",\"name\":\"恒健新泽西仓\",\"country\":\"US\"," |
||||
+ "\"state\":\"NJ\",\"city\":\"Wharton\",\"address1\":\"40 Harry Shupe Blvd\"," |
||||
+ "\"address2\":\"\",\"postal\":\"07885\"}]}"; |
||||
|
||||
// ---------------------------------------------------------------- 鉴权
|
||||
|
||||
/** |
||||
* 文档把两个头都标成「授权Token」且都标必须,所以两个都要带、取值相同。 |
||||
* |
||||
* <p>真机用无效 token 试过,只带一个也返回「未知的账户!」,暂时无法用实验 |
||||
* 证明「必须两个」;拿到有效 token 后补一次对照实验再决定能否精简。</p> |
||||
*/ |
||||
@Test |
||||
void sendsBothAuthorizationHeaders() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_WAREHOUSE_LIST, req -> Responses.ok(WAREHOUSE_BODY)); |
||||
adapter(transport).warehouses(ctx()); |
||||
|
||||
Map<String, String> headers = transport.lastDataRequest().headers(); |
||||
assertEquals("token-1", headers.get(HengjianConstants.AUTHORIZATION_HEADER)); |
||||
assertEquals("token-1", headers.get(HengjianConstants.API_KEY_HEADER)); |
||||
assertEquals("req-1", headers.get("requestId")); |
||||
} |
||||
|
||||
/** 缺 token 直接失败,不发一个没有鉴权的请求。 */ |
||||
@Test |
||||
void rejectsRequestWithoutToken() { |
||||
RecordingTransport transport = RecordingTransport.create(); |
||||
WarehouseContext ctx = WarehouseContext.of("HJ-EFCA", WarehouseProvider.HENGJIAN, "EFCA", |
||||
WarehouseConnection.of(HengjianConstants.TEST_BASE_URL, ChannelSecret.builder().build()), |
||||
"req-1", CLOCK); |
||||
|
||||
try { |
||||
adapter(transport).warehouses(ctx); |
||||
throw new AssertionError("expected IllegalStateException"); |
||||
} catch (IllegalStateException ex) { |
||||
assertTrue(ex.getMessage().contains("appSecret"), ex.getMessage()); |
||||
} |
||||
assertTrue(transport.dataRequests().isEmpty(), "不应发出无鉴权请求"); |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- 仓库目录
|
||||
|
||||
@Test |
||||
void sendsPostWithoutParameters() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_WAREHOUSE_LIST, req -> Responses.ok(WAREHOUSE_BODY)); |
||||
adapter(transport).warehouses(ctx()); |
||||
|
||||
assertEquals("POST", transport.lastDataRequest().method()); |
||||
assertEquals(HengjianConstants.TEST_BASE_URL + "/v2/warehouse/getWarehouse", |
||||
transport.lastDataRequest().url()); |
||||
assertEquals("{}", transport.lastDataRequest().body()); |
||||
} |
||||
|
||||
@Test |
||||
void mapsEveryWarehouseField() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_WAREHOUSE_LIST, req -> Responses.ok(WAREHOUSE_BODY)); |
||||
WarehouseFacility wh = adapter(transport).warehouses(ctx()).get(0); |
||||
|
||||
assertEquals(WarehouseProvider.HENGJIAN, wh.sourceProvider()); |
||||
assertEquals("EFCA", wh.warehouseCode()); |
||||
assertEquals("恒健加州仓", wh.name()); |
||||
assertEquals("US", wh.country()); |
||||
assertEquals("CA", wh.state()); |
||||
assertEquals("CA", wh.province()); |
||||
assertEquals("Los Angeles", wh.city()); |
||||
assertEquals("1 Main St", wh.address1()); |
||||
assertNull(wh.address2(), "空串归一成 null,避免宿主把 \"\" 当有效值"); |
||||
assertEquals("90001", wh.postcode()); |
||||
// 恒健文档的仓对象没有联系人 / 电话 / 邮箱——平台限制,不是漏接
|
||||
assertNull(wh.contactName()); |
||||
assertNull(wh.mobilePhone()); |
||||
assertNull(wh.email()); |
||||
assertNull(wh.providerWarehouseId(), "恒健没有独立的仓方内部 id"); |
||||
} |
||||
|
||||
@Test |
||||
void skipsRowsWithoutWarehouseCode() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_WAREHOUSE_LIST, req -> Responses.ok( |
||||
"{\"code\":200,\"message\":\"ok\",\"data\":[" |
||||
+ "{\"name\":\"没有仓代码的行\"}," |
||||
+ "{\"warehouseCode\":\"EFCA\",\"name\":\"仓\"}]}")); |
||||
List<WarehouseFacility> list = adapter(transport).warehouses(ctx()); |
||||
|
||||
assertEquals(1, list.size()); |
||||
assertEquals("EFCA", list.get(0).warehouseCode()); |
||||
} |
||||
|
||||
@Test |
||||
void emptyWarehouseListIsNotAnError() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_WAREHOUSE_LIST, req -> Responses.ok( |
||||
"{\"code\":200,\"message\":\"ok\",\"data\":[]}")); |
||||
|
||||
assertTrue(adapter(transport).warehouses(ctx()).isEmpty()); |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- 物流渠道
|
||||
|
||||
private static final String CARRIER_BODY = |
||||
"{\"statusCode\":200,\"status\":0,\"code\":200,\"message\":\"查询成功\",\"data\":[" |
||||
+ "{\"code\":\"UPS2DAM_HL\",\"carrier\":\"UPS\",\"carrierServiceName\":\"2nd Day Air AM\"}," |
||||
+ "{\"code\":\"UPSG_HL\",\"carrier\":\"UPS\",\"carrierServiceName\":\"Ground\"}," |
||||
+ "{\"code\":\"FEDHD\",\"carrier\":\"FedEx\",\"carrierServiceName\":\"Home Delivery\"}]}"; |
||||
|
||||
@Test |
||||
void carriersAreDeduplicatedAndOrdered() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_CARRIER_GROUP, req -> Responses.ok(CARRIER_BODY)); |
||||
List<String> codes = adapter(transport).carriers(ctx()); |
||||
|
||||
assertEquals(3, codes.size()); |
||||
assertEquals("UPS2DAM_HL", codes.get(0)); |
||||
assertEquals("FEDHD", codes.get(2)); |
||||
} |
||||
|
||||
@Test |
||||
void carrierRequestHasNoBodyParameters() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_CARRIER_GROUP, req -> Responses.ok(CARRIER_BODY)); |
||||
adapter(transport).carriers(ctx()); |
||||
|
||||
assertEquals("POST", transport.lastDataRequest().method()); |
||||
assertEquals(HengjianConstants.TEST_BASE_URL + "/v2/carrierGroup/getCarrierGroup", |
||||
transport.lastDataRequest().url()); |
||||
assertEquals("{}", transport.lastDataRequest().body()); |
||||
} |
||||
|
||||
@Test |
||||
void mapsLogisticsProduct() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_CARRIER_GROUP, req -> Responses.ok(CARRIER_BODY)); |
||||
LogisticsProduct p = adapter(transport).products(ctx(), null).get(0); |
||||
|
||||
assertEquals(WarehouseProvider.HENGJIAN, p.sourceProvider()); |
||||
assertEquals("EFCA", p.warehouseCode(), "未指定仓时用账户配置的 providerWarehouseId"); |
||||
assertEquals("UPS2DAM_HL", p.logisticsProductCode()); |
||||
assertEquals("UPS - 2nd Day Air AM", p.logisticsProductName()); |
||||
// 恒健文档没有跨国维度:false 表示「未提供」,不是「不支持」
|
||||
assertTrue(!p.crossCountry()); |
||||
} |
||||
|
||||
/** 按仓过滤的接口外层是「仓代码 → 数组」的对象,不是数组。 */ |
||||
@Test |
||||
void warehouseCarrierServicesParsesObjectShapedData() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_WAREHOUSE_CARRIER_GROUP, req -> Responses.ok( |
||||
"{\"code\":200,\"message\":\"查询成功\",\"data\":{" |
||||
+ "\"EFCA\":[{\"code\":\"UPSG_HL\",\"carrier\":\"UPS\"," |
||||
+ "\"carrierServiceName\":\"Ground\"}]," |
||||
+ "\"EFGA\":[{\"code\":\"OTHER_HL\",\"carrier\":\"UPS\"," |
||||
+ "\"carrierServiceName\":\"别的仓的渠道\"}]}}")); |
||||
List<LogisticsProduct> list = adapter(transport).productsOfWarehouse(ctx(), "EFCA"); |
||||
|
||||
assertEquals(1, list.size(), "只取请求的仓,别人的渠道不能混进来"); |
||||
assertEquals("UPSG_HL", list.get(0).logisticsProductCode()); |
||||
assertEquals("EFCA", list.get(0).warehouseCode()); |
||||
} |
||||
|
||||
@Test |
||||
void warehouseCarrierServicesSendsWarehouseCodes() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(HengjianConstants.PATH_WAREHOUSE_CARRIER_GROUP, req -> Responses.ok( |
||||
"{\"code\":200,\"message\":\"ok\",\"data\":{\"EFCA\":[]}}")); |
||||
adapter(transport).productsOfWarehouse(ctx(), null); |
||||
|
||||
String body = transport.lastDataRequest().body(); |
||||
assertTrue(body.contains("\"warehouseCodes\""), body); |
||||
assertTrue(body.contains("\"EFCA\""), body); |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- 能力位
|
||||
|
||||
@Test |
||||
void declaresOnlyReadOnlyDirectoryCapabilities() { |
||||
HengjianAdapter adapter = adapter(RecordingTransport.create()); |
||||
|
||||
assertTrue(adapter.capabilities().contains(WarehouseCapability.DIRECTORY)); |
||||
assertTrue(adapter.capabilities().contains(WarehouseCapability.LOGISTICS_PRODUCT)); |
||||
// 出库 / 库存 / 入库 / 退货都还没接:声明了就必须有实现
|
||||
assertTrue(!adapter.capabilities().contains(WarehouseCapability.OUTBOUND)); |
||||
assertTrue(!adapter.capabilities().contains(WarehouseCapability.INVENTORY_QUERY)); |
||||
assertTrue(!adapter.capabilities().contains(WarehouseCapability.INBOUND)); |
||||
assertTrue(!adapter.capabilities().contains(WarehouseCapability.RETURN)); |
||||
assertTrue(!adapter.capabilities().contains(WarehouseCapability.WEBHOOK)); |
||||
} |
||||
|
||||
@Test |
||||
void adapterIdentity() { |
||||
HengjianAdapter adapter = adapter(RecordingTransport.create()); |
||||
|
||||
assertEquals(HengjianConstants.ADAPTER_ID, adapter.adapterId()); |
||||
assertEquals(WarehouseProvider.HENGJIAN, adapter.provider()); |
||||
assertEquals(HengjianEnvelope.SUCCESS_CODE, HengjianConstants.SUCCESS_CODE); |
||||
} |
||||
} |
||||
@ -0,0 +1,126 @@
@@ -0,0 +1,126 @@
|
||||
package common.ecommerce.hengjian.http; |
||||
|
||||
import common.ecommerce.http.HttpResponse; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.shared.error.AuthException; |
||||
import common.ecommerce.shared.error.PlatformBusinessException; |
||||
import common.ecommerce.shared.error.TransientException; |
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.util.Collections; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 恒健响应信封校验。 |
||||
* |
||||
* <p>把真机观察到的三种形态都固化成用例:正常业务信封、 |
||||
* HTTP 200 + {@code code=999999}(未授权)、HTTP 500 + 「未知的账户」。 |
||||
* 后续有人把信封改成严格数字解析、或把 999999 当普通业务失败,这些用例会挂。</p> |
||||
*/ |
||||
class HengjianEnvelopeTest { |
||||
|
||||
private static final JacksonJsonCodec JSON = new JacksonJsonCodec(); |
||||
|
||||
private static HttpResponse ok(String body) { |
||||
return HttpResponse.of(200, Collections.<String, String>emptyMap(), body, 0L); |
||||
} |
||||
|
||||
private static HengjianEnvelope parse(HttpResponse response) { |
||||
return HengjianEnvelope.of(response, JSON, "warehouse.test", "WH-1", "req-1"); |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- 成功
|
||||
|
||||
@Test |
||||
void acceptsNumericCode() { |
||||
String body = "{\"statusCode\":200,\"status\":0,\"code\":200,\"message\":\"查询成功\"}"; |
||||
assertEquals(body, parse(ok(body)).body()); |
||||
} |
||||
|
||||
/** 查询库存等接口页把 code 标成 STRING,必须同样按成功处理。 */ |
||||
@Test |
||||
void acceptsStringCode() { |
||||
parse(ok("{\"code\":\"200\",\"message\":\"ok\"}")); |
||||
} |
||||
|
||||
/** 个别接口页只列 status 不列 code。 */ |
||||
@Test |
||||
void fallsBackToStatusWhenCodeMissing() { |
||||
parse(ok("{\"status\":200,\"message\":\"ok\"}")); |
||||
} |
||||
|
||||
// ---------------------------------------------------------------- 失败
|
||||
|
||||
@Test |
||||
void businessErrorIsNotRetryable() { |
||||
PlatformBusinessException ex = assertThrows(PlatformBusinessException.class, |
||||
() -> parse(ok("{\"code\":500,\"message\":\"sku 不存在\"}"))); |
||||
assertTrue(ex.getMessage().contains("500"), ex.getMessage()); |
||||
assertTrue(ex.getMessage().contains("sku 不存在"), ex.getMessage()); |
||||
assertTrue(!ex.retryable()); |
||||
} |
||||
|
||||
/** |
||||
* 真机:不带授权头时 HTTP 200 但 body 里 code=999999。 |
||||
* 这必须归认证失败——当普通业务失败宿主不会刷新凭据。 |
||||
*/ |
||||
@Test |
||||
void unauthorizedCodeIsAuthFailure() { |
||||
AuthException ex = assertThrows(AuthException.class, () -> parse(ok( |
||||
"{\"statusCode\":500,\"status\":1,\"code\":999999," |
||||
+ "\"message\":\"查询失败Unauthorized\"}"))); |
||||
assertEquals("999999", ex.platformCode()); |
||||
assertTrue(!ex.retryable()); |
||||
} |
||||
|
||||
/** |
||||
* 真机:只带一个授权头 / token 无效时 HTTP 500 + Spring 错误页。 |
||||
* 消息虽是 500,根因是凭据,按认证失败处理,避免宿主无意义重试。 |
||||
*/ |
||||
@Test |
||||
void unknownAccountOn500IsAuthFailure() { |
||||
AuthException ex = assertThrows(AuthException.class, () -> parse( |
||||
HttpResponse.of(500, Collections.<String, String>emptyMap(), |
||||
"{\"timestamp\":\"2026-11-12T07:01:31.760+0000\",\"status\":500," |
||||
+ "\"error\":\"Internal Server Error\"," |
||||
+ "\"message\":\"未知的账户!\",\"path\":\"/v2/warehouse/getWarehouse\"}", |
||||
0L))); |
||||
assertTrue(ex.getMessage().contains("unknown account"), ex.getMessage()); |
||||
assertTrue(!ex.retryable()); |
||||
} |
||||
|
||||
/** 普通 5xx(网关 / 后端故障)仍按瞬时错误处理。 */ |
||||
@Test |
||||
void plainServerErrorIsRetryable() { |
||||
TransientException ex = assertThrows(TransientException.class, () -> parse( |
||||
HttpResponse.of(502, Collections.<String, String>emptyMap(), "bad gateway", 0L))); |
||||
assertTrue(ex.retryable()); |
||||
} |
||||
|
||||
@Test |
||||
void http401IsAuthFailure() { |
||||
assertThrows(AuthException.class, () -> parse( |
||||
HttpResponse.of(401, Collections.<String, String>emptyMap(), "", 0L))); |
||||
} |
||||
|
||||
@Test |
||||
void emptyBodyIsValidationError() { |
||||
assertThrows(ValidationException.class, () -> parse(ok(""))); |
||||
} |
||||
|
||||
@Test |
||||
void missingCodeIsValidationError() { |
||||
ValidationException ex = assertThrows(ValidationException.class, |
||||
() -> parse(ok("{\"message\":\"no code here\"}"))); |
||||
assertTrue(ex.getMessage().contains("no business code"), ex.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void nonJsonErrorBodyIsValidationError() { |
||||
assertThrows(ValidationException.class, () -> parse(ok("<html>proxy error</html>"))); |
||||
} |
||||
} |
||||
@ -0,0 +1,148 @@
@@ -0,0 +1,148 @@
|
||||
package common.ecommerce.hengjian.probe; |
||||
|
||||
import common.ecommerce.hengjian.HengjianConstants; |
||||
import common.ecommerce.hengjian.adapter.HengjianAdapter; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.http.OkHttpTransport; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.LogisticsProduct; |
||||
import common.ecommerce.warehouse.model.WarehouseFacility; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
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.util.List; |
||||
|
||||
/** |
||||
* 恒健<b>只读</b>探针:核对已对接接口的真实出入参。 |
||||
* |
||||
* <p>默认跳过,用 {@code -Dhengjian.probe=true} 显式开启;凭据走系统属性, |
||||
* <b>真实 token 不入库</b>:</p> |
||||
* |
||||
* <pre> |
||||
* mvn -pl warehouse-sdk-hengjian -DfailIfNoTests=false \ |
||||
* -Dhengjian.probe=true \ |
||||
* -Dhengjian.probe.token=你的组织token \ |
||||
* -Dhengjian.probe.warehouseCode=EFCA \ |
||||
* -Dtest=HengjianReadOnlyProbeTest test |
||||
* </pre> |
||||
* |
||||
* <p><b>只跑查询类接口</b>:建单 / 取消 / 销毁会真实创建单据,没有测试环境 |
||||
* 明确许可前一律不碰。</p> |
||||
* |
||||
* <p>输出只打印字段名与取值摘要,不打印 token 与完整报文(可能含 PII)。</p> |
||||
*/ |
||||
@EnabledIfSystemProperty(named = "hengjian.probe", matches = "true") |
||||
class HengjianReadOnlyProbeTest { |
||||
|
||||
private static final String TOKEN = System.getProperty("hengjian.probe.token", ""); |
||||
private static final String BASE_URL = opt("hengjian.probe.baseUrl", HengjianConstants.TEST_BASE_URL); |
||||
private static final String WAREHOUSE_CODE = opt("hengjian.probe.warehouseCode", "HJ-PROBE"); |
||||
private static final String PROVIDER_WAREHOUSE = opt("hengjian.probe.providerWarehouseId", "EFCA"); |
||||
|
||||
private static String opt(String key, String fallback) { |
||||
String v = System.getProperty(key); |
||||
return v == null || v.trim().isEmpty() ? fallback : v.trim(); |
||||
} |
||||
|
||||
private static void assumeToken() { |
||||
Assumptions.assumeTrue(!TOKEN.trim().isEmpty(), |
||||
"未提供 -Dhengjian.probe.token,跳过恒健探针"); |
||||
} |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of(WAREHOUSE_CODE, WarehouseProvider.HENGJIAN, PROVIDER_WAREHOUSE, |
||||
WarehouseConnection.of(BASE_URL, |
||||
ChannelSecret.builder().appSecret(TOKEN.trim()).build()), |
||||
"probe-" + System.currentTimeMillis(), Clock.systemUTC()); |
||||
} |
||||
|
||||
private static HengjianAdapter adapter() { |
||||
return new HengjianAdapter(new OkHttpTransport("common-ecommerce-hengjian-probe"), |
||||
new JacksonJsonCodec()); |
||||
} |
||||
|
||||
/** 一次跑完,异常只打印不中断——探针要把所有问题一次暴露出来。 */ |
||||
private static void run(String what, Runnable action) { |
||||
System.out.println("---- " + what); |
||||
try { |
||||
action.run(); |
||||
} catch (RuntimeException e) { |
||||
System.out.println(" [FAIL] " + e.getClass().getSimpleName() + ": " + e.getMessage()); |
||||
} |
||||
} |
||||
|
||||
/** 仓库目录:不依赖任何单号,最容易验通,也顺带验证鉴权与信封。 */ |
||||
@Test |
||||
void probeWarehouseDirectory() { |
||||
assumeToken(); |
||||
run("POST /v2/warehouse/getWarehouse", new Runnable() { |
||||
@Override |
||||
public void run() { |
||||
List<WarehouseFacility> list = adapter().warehouses(ctx()); |
||||
System.out.println(" 返回 " + list.size() + " 个仓"); |
||||
for (int i = 0; i < Math.min(list.size(), 10); i++) { |
||||
WarehouseFacility w = list.get(i); |
||||
System.out.println(" [" + i + "] code=" + w.warehouseCode() |
||||
+ " name=" + w.name() |
||||
+ " country=" + w.country() |
||||
+ " state=" + w.state() |
||||
+ " city=" + w.city() |
||||
+ " postal=" + w.postcode()); |
||||
} |
||||
} |
||||
}); |
||||
} |
||||
|
||||
/** 全量物流渠道:验证无参数 POST 与 data 是数组。 */ |
||||
@Test |
||||
void probeAllCarrierServices() { |
||||
assumeToken(); |
||||
run("POST /v2/carrierGroup/getCarrierGroup", new Runnable() { |
||||
@Override |
||||
public void run() { |
||||
List<LogisticsProduct> list = adapter().products(ctx(), PROVIDER_WAREHOUSE); |
||||
System.out.println(" 返回 " + list.size() + " 个物流产品"); |
||||
for (int i = 0; i < Math.min(list.size(), 10); i++) { |
||||
LogisticsProduct p = list.get(i); |
||||
System.out.println(" [" + i + "] code=" + p.logisticsProductCode() |
||||
+ " name=" + p.logisticsProductName()); |
||||
} |
||||
} |
||||
}); |
||||
} |
||||
|
||||
/** 按仓过滤的物流渠道:验证 data 是「仓代码 → 数组」的对象。 */ |
||||
@Test |
||||
void probeWarehouseCarrierServices() { |
||||
assumeToken(); |
||||
run("POST /v2/carrierGroup/getWarehouseCarrierGroupServices", new Runnable() { |
||||
@Override |
||||
public void run() { |
||||
List<LogisticsProduct> list = adapter().productsOfWarehouse(ctx(), PROVIDER_WAREHOUSE); |
||||
System.out.println(" 仓 " + PROVIDER_WAREHOUSE + " 返回 " + list.size() + " 个物流产品"); |
||||
for (int i = 0; i < Math.min(list.size(), 10); i++) { |
||||
System.out.println(" [" + i + "] code=" + list.get(i).logisticsProductCode() |
||||
+ " name=" + list.get(i).logisticsProductName()); |
||||
} |
||||
} |
||||
}); |
||||
} |
||||
|
||||
/** 承运商代码清单(走同一个全量接口,验证去重)。 */ |
||||
@Test |
||||
void probeCarrierCodes() { |
||||
assumeToken(); |
||||
run("POST /v2/carrierGroup/getCarrierGroup (carriers)", new Runnable() { |
||||
@Override |
||||
public void run() { |
||||
List<String> codes = adapter().carriers(ctx()); |
||||
System.out.println(" 去重后 " + codes.size() + " 个 code:" + codes); |
||||
} |
||||
}); |
||||
} |
||||
} |
||||
Loading…
Reference in new issue