Compare commits
10 Commits
586d9c5eb8
...
12718ec376
| Author | SHA1 | Date |
|---|---|---|
|
|
12718ec376 | 1 week ago |
|
|
fbf2363c06 | 1 week ago |
|
|
ad41104cc6 | 1 week ago |
|
|
274425c0e5 | 1 week ago |
|
|
03f4773cb8 | 1 week ago |
|
|
15605b58db | 1 week ago |
|
|
c96b43faed | 1 week ago |
|
|
5962988f86 | 1 week ago |
|
|
c07d848628 | 1 week ago |
|
|
e522c08377 | 1 week ago |
40 changed files with 5617 additions and 25 deletions
@ -0,0 +1,40 @@
@@ -0,0 +1,40 @@
|
||||
# 易达云:待确认事项 |
||||
|
||||
接入过程中发现、需要业务或仓方确认的点。**先记下来,不阻塞接口对接。** |
||||
|
||||
## 待仓方确认 |
||||
|
||||
| # | 问题 | 当前处理 | 影响 | |
||||
|---|---|---|---| |
||||
| 1 | **创建产品是否需要 `declarationInfoList` 的进口国** | 默认 `US` | 申报准确性 | |
||||
| 2 | `declarationType` 码值(0 出口 / 1 进口) | 按示例推断 | 申报方向可能反 | |
||||
| 3 | 业务接口能否用 `openApiAdminSecret` 免签 | 当前一律用 `appSecret` 算 MD5 | 若只有 token 接口免签,现在是正确的 | |
||||
| 4 | 创建产品同 SKU 重复调用的行为 | 按「创建」语义处理,无更新接口 | 重复建档会报错 | |
||||
| 5 | 出库单 `getOrderInfo` 的 `carrierInfoList` 是否总与追踪号一一对应 | 按数组原样映射 | 多包裹场景 | |
||||
| 11 | 交易明细超过 200 条时如何翻页 | 当前只取第一页 | 大账户对账会漏 | |
||||
| 12 | `billingCode` 有没有完整字典(现在按关键字推断) | 认不出归 null | 费用分类准确度 | |
||||
| 13 | 订单费用明细的 `billingId` 能否作为幂等键 | 当前未用作主键 | 重复拉取去重 | |
||||
|
||||
## 待业务确认 |
||||
|
||||
| # | 问题 | 当前处理 | 影响 | |
||||
|---|---|---|---| |
||||
| 6 | **派送地址的州要全称(California)还是二字码(CA)** | 原样透传 | 所有出库单地址 | |
||||
| 7 | 统一模型缺的字段:带电 / 包材 / 物流包装 | 创建产品里硬编码为「不带」 | 带电商品无法正确申报 | |
||||
| 8 | 保价服务(`is_insurance`) | 未下发,标准模型无字段 | 保价订单 | |
||||
| 9 | `OutboundCommand` 没有 `carrierProductId`(易达云物流产品 id) | 未下发,走仓方默认分物流规则 | 指定物流产品 | |
||||
| 10 | `channelName` 从 `Platform` 枚举推(AMAZON_SC → Amazon) | 首段大写 | 非标准平台名可能对不上 | |
||||
|
||||
## 已确认(不需要再问) |
||||
|
||||
| 项 | 结论 | |
||||
|---|---| |
||||
| 测试基址 | `https://test.omniselling.com.cn/saas-service/openapi/microService` | |
||||
| 测试账号 | `openapi-test` / `123456` | |
||||
| token 接口响应 | 扁平结构,无 `code`,无有效期,`token_type=bearer` | |
||||
| token 请求头 | `POST /oauth/token` **不带** `token` 头 | |
||||
| 业务请求头 | `Authorization: Bearer <token>` + `appKey` + `timestamp` + `sign` | |
||||
| 签名算法 | `MD5(body + "." + appSecret)`,小写十六进制 | |
||||
| 时间戳单位 | 毫秒,5 分钟内有效 | |
||||
| 布尔标志 | **0 是 / 1 否**(与直觉相反) | |
||||
| 重量单位 | kg(我们的是 g,需换算) | |
||||
@ -0,0 +1,46 @@
@@ -0,0 +1,46 @@
|
||||
package common.ecommerce.warehouse.enums; |
||||
|
||||
/** |
||||
* 费用查询时「业务单号」的类型。 |
||||
* |
||||
* <p>有的仓要求明确告诉它这个单号是哪种(易达云的 {@code type}: |
||||
* 0 订单号 / 1 平台单号 / 2 追踪号),有的仓只有一种查法。统一成枚举, |
||||
* 不支持的取值由适配器<b>显式拒绝</b>——静默按别的口径查会让对账金额对不上。</p> |
||||
*/ |
||||
public enum FeeQueryNoType { |
||||
|
||||
/** 仓侧订单号(如易达云的 ORD 号)。 */ |
||||
PROVIDER_ORDER_NO(10, "仓侧订单号"), |
||||
/** 平台订单号(客户单号 / poNumber)。 */ |
||||
PLATFORM_ORDER_NO(20, "平台单号"), |
||||
/** 物流追踪号。 */ |
||||
TRACKING_NO(30, "追踪号"); |
||||
|
||||
private final int code; |
||||
private final String label; |
||||
|
||||
FeeQueryNoType(int code, String label) { |
||||
this.code = code; |
||||
this.label = label; |
||||
} |
||||
|
||||
/** 落库用的稳定码;由 SDK 分配,永不复用、永不重排。 */ |
||||
public int code() { |
||||
return code; |
||||
} |
||||
|
||||
/** 中文显示名。 */ |
||||
public String label() { |
||||
return label; |
||||
} |
||||
|
||||
/** 按落库码反查。 */ |
||||
public static FeeQueryNoType ofCode(int code) { |
||||
for (FeeQueryNoType t : values()) { |
||||
if (t.code == code) { |
||||
return t; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
} |
||||
@ -0,0 +1,150 @@
@@ -0,0 +1,150 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunAccountFlowDtos; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.WarehouseFeeType; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.BillingDocument; |
||||
import common.ecommerce.warehouse.model.FeeQuery; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.time.Instant; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云交易明细映射({@code POST /webApi/accountFlow/list})。 |
||||
* |
||||
* <p>三个口径差异:</p> |
||||
* <ul> |
||||
* <li><b>不按单号去重</b>:同一单号的同一计费项有多条流水,每条都是独立账目</li> |
||||
* <li><b>金额是 string 且可为负</b>:{@code "-0.500"} 是扣费,正数是充值 / 退费</li> |
||||
* <li><b>页码必填</b>:文档明确 {@code pageNum} / {@code pageSize} 必填, |
||||
* 所以统一模型不做「不传就全量」</li> |
||||
* </ul> |
||||
*/ |
||||
public final class EdayunFeeMapper { |
||||
|
||||
/** 没给业务单号时,计费时间段必填且不超过 180 天。 */ |
||||
static final int MAX_RANGE_DAYS = 180; |
||||
|
||||
/** 单页上限。 */ |
||||
static final int MAX_PAGE_SIZE = 200; |
||||
|
||||
private EdayunFeeMapper() { |
||||
} |
||||
|
||||
/** |
||||
* 统一查询条件 → 交易明细请求。 |
||||
* |
||||
* @throws IllegalArgumentException 既没有业务单号也没有计费时间窗 |
||||
*/ |
||||
public static EdayunAccountFlowDtos.ListFlowRequest toRequest(FeeQuery query) { |
||||
EdayunAccountFlowDtos.ListFlowRequest req = new EdayunAccountFlowDtos.ListFlowRequest(); |
||||
|
||||
// 业务单号:统一模型里对应 externalOrderNo(仓方单号)
|
||||
req.bizNo = firstNonBlank(query.externalOrderNo(), query.saleOrderNo()); |
||||
|
||||
if (query.hasSettledRange()) { |
||||
long days = java.time.Duration.between( |
||||
query.settledAfter(), query.settledBefore()).toDays(); |
||||
if (!hasText(req.bizNo) && days > MAX_RANGE_DAYS) { |
||||
throw new IllegalArgumentException( |
||||
"edayun account flow query without bizNo requires a range <= 180 days, got " + days); |
||||
} |
||||
req.beginBillingTime = query.settledAfter().toEpochMilli(); |
||||
req.endBillingTime = query.settledBefore().toEpochMilli(); |
||||
} else if (!hasText(req.bizNo)) { |
||||
throw new IllegalArgumentException( |
||||
"edayun account flow query requires a bizNo or a billing time range;" |
||||
+ " refusing to pull all flows"); |
||||
} |
||||
|
||||
req.pageNum = 1; |
||||
req.pageSize = MAX_PAGE_SIZE; |
||||
return req; |
||||
} |
||||
|
||||
/** 一条流水 → 统一费用单据。 */ |
||||
public static BillingDocument toDocument(EdayunAccountFlowDtos.FlowRow row, String warehouseCode) { |
||||
return BillingDocument.builder() |
||||
.warehouseCode(warehouseCode) |
||||
.sourceProvider(WarehouseProvider.EDAYUN) |
||||
.documentNo(row.relateBusinessCode) |
||||
.serialNumber(row.serialNumber) |
||||
.feeName(row.billingName) |
||||
.feeType(feeTypeOf(row.billingCode)) |
||||
// 交易明细是已发生账目,不是预估
|
||||
.estimated(false) |
||||
.settledAt(instantOf(row.billingTime)) |
||||
.amount(amountOf(row)) |
||||
.accountBalance(moneyOrNull(row.accountBalance, row.accountCurrency)) |
||||
.saleOrderNo(firstNonBlank(row.poNumber, row.relateBusinessCode)) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* 金额:{@code billingAmount} 是 string,可为负。 |
||||
* |
||||
* <p>币种优先用 {@code accountCurrency}(账户币种),缺失才退回 |
||||
* {@code originalCurrency}。两者可能不同——跨币种账户会有汇率。</p> |
||||
*/ |
||||
static Money amountOf(EdayunAccountFlowDtos.FlowRow row) { |
||||
String currency = firstNonBlank(row.accountCurrency, row.originalCurrency); |
||||
if (!hasText(row.billingAmount)) { |
||||
return Money.zero(currency == null ? "USD" : currency); |
||||
} |
||||
return Money.of(new BigDecimal(row.billingAmount.trim()), |
||||
currency == null ? "USD" : currency); |
||||
} |
||||
|
||||
/** |
||||
* 计费项编码 → 业务语义。 |
||||
* |
||||
* <p>易达云用编码(如 {@code farawayFee})而不是分类码,所以只能按关键字推断; |
||||
* <b>认不出返回 null</b>,不猜——对账时宁可不分类,也不能分类错。</p> |
||||
*/ |
||||
static WarehouseFeeType feeTypeOf(String billingCode) { |
||||
if (!hasText(billingCode)) { |
||||
return null; |
||||
} |
||||
String code = billingCode.toLowerCase(); |
||||
if (code.contains("storage") || code.contains("warehouse")) { |
||||
return WarehouseFeeType.STORAGE; |
||||
} |
||||
if (code.contains("operation") || code.contains("handle") || code.contains("handling")) { |
||||
return WarehouseFeeType.OPERATION; |
||||
} |
||||
if (code.contains("freight") || code.contains("shipping") || code.contains("delivery") |
||||
|| code.contains("faraway") || code.contains("remote")) { |
||||
return WarehouseFeeType.LAST_MILE; |
||||
} |
||||
if (code.contains("service") || code.contains("value") || code.contains("pack") |
||||
|| code.contains("label")) { |
||||
return WarehouseFeeType.VALUE_ADDED; |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
private static Instant instantOf(Long millis) { |
||||
return millis == null || millis <= 0 ? null : Instant.ofEpochMilli(millis); |
||||
} |
||||
|
||||
private static Money moneyOrNull(Double amount, String currency) { |
||||
if (amount == null) { |
||||
return null; |
||||
} |
||||
return Money.of(BigDecimal.valueOf(amount), hasText(currency) ? currency.trim() : "USD"); |
||||
} |
||||
|
||||
private static String firstNonBlank(String a, String b) { |
||||
if (hasText(a)) { |
||||
return a.trim(); |
||||
} |
||||
return hasText(b) ? b.trim() : null; |
||||
} |
||||
|
||||
private static boolean hasText(String v) { |
||||
return v != null && !v.trim().isEmpty(); |
||||
} |
||||
} |
||||
@ -0,0 +1,205 @@
@@ -0,0 +1,205 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunOrderCostDtos; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.FeeQueryNoType; |
||||
import common.ecommerce.warehouse.enums.WarehouseFeeType; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.BillingDocument; |
||||
import common.ecommerce.warehouse.model.FeeQuery; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.time.Duration; |
||||
import java.time.Instant; |
||||
import java.util.ArrayList; |
||||
import java.util.Collections; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云订单费用明细映射 |
||||
* ({@code POST /webApi/order/cost/v1/selectOrderCostInfoList})。 |
||||
* |
||||
* <p>与交易明细({@code accountFlow/list})的区别:</p> |
||||
* <ul> |
||||
* <li>交易明细 = 账户流水,带账户余额,金额为负表示扣费</li> |
||||
* <li>订单费用 = 按订单拆的报价,带<b>应收 / 折扣 / 实付</b>三个金额与计费重</li> |
||||
* </ul> |
||||
* |
||||
* <p>金额口径:{@code realPayPrice} 是实付(应收 - 折扣), |
||||
* 落到 {@link BillingDocument#amount()} 的是<b>实付</b>——对账要以实际发生为准。</p> |
||||
*/ |
||||
public final class EdayunOrderCostMapper { |
||||
|
||||
/** 计费时间窗上限 3 个月。 */ |
||||
static final int MAX_RANGE_MONTHS = 3; |
||||
|
||||
/** 单页上限。 */ |
||||
static final int MAX_PAGE_SIZE = 200; |
||||
|
||||
private EdayunOrderCostMapper() { |
||||
} |
||||
|
||||
/** 统一查询条件 → 订单费用查询请求。 */ |
||||
public static EdayunOrderCostDtos.SelectOrderCostRequest toRequest(FeeQuery query) { |
||||
EdayunOrderCostDtos.SelectOrderCostRequest req = |
||||
new EdayunOrderCostDtos.SelectOrderCostRequest(); |
||||
req.pageNum = 1; |
||||
req.pageSize = MAX_PAGE_SIZE; |
||||
|
||||
// 单号 + 类型:两者要配合使用
|
||||
String orderNo = firstNonBlank(query.externalOrderNo(), query.saleOrderNo()); |
||||
req.orderNo = orderNo; |
||||
req.type = typeOf(query.noType()); |
||||
|
||||
if (query.hasSettledRange()) { |
||||
long months = Duration.between(query.settledAfter(), query.settledBefore()).toDays() / 30; |
||||
if (months > MAX_RANGE_MONTHS) { |
||||
throw new IllegalArgumentException( |
||||
"edayun order cost query range must not exceed 3 months, got about " |
||||
+ months + " months"); |
||||
} |
||||
req.beginBillingTime = query.settledAfter().toEpochMilli(); |
||||
req.endBillingTime = query.settledBefore().toEpochMilli(); |
||||
} else if (!hasText(orderNo)) { |
||||
throw new IllegalArgumentException( |
||||
"edayun order cost query requires an order number or a billing time range;" |
||||
+ " refusing to pull all costs"); |
||||
} |
||||
|
||||
req.skuCode = query.providerSku(); |
||||
return req; |
||||
} |
||||
|
||||
/** |
||||
* 统一单号类型 → 易达云 {@code type}。 |
||||
* |
||||
* <p>不支持的取值<b>显式拒绝</b>:静默按别的口径查会让对账金额对不上。</p> |
||||
*/ |
||||
static Integer typeOf(FeeQueryNoType noType) { |
||||
if (noType == null) { |
||||
return null; |
||||
} |
||||
switch (noType) { |
||||
case PROVIDER_ORDER_NO: |
||||
return 0; |
||||
case PLATFORM_ORDER_NO: |
||||
return 1; |
||||
case TRACKING_NO: |
||||
return 2; |
||||
default: |
||||
throw new IllegalArgumentException( |
||||
"edayun order cost query does not support noType: " + noType); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 一行订单费用 → 若干条 {@link BillingDocument}。 |
||||
* |
||||
* <p>一层里可能有多个 {@code chargeDetails},每个下面又有多个 {@code feeDetails}。 |
||||
* 这里按<b>计费项</b>展开:每个 feeDetail 一条记录,对账才能落到具体费用项。</p> |
||||
* |
||||
* <p>如果没有 {@code feeDetails} 但有 {@code chargeDetails} 汇总,就按汇总记一条。</p> |
||||
*/ |
||||
public static List<BillingDocument> toDocuments(EdayunOrderCostDtos.OrderCostRow row, |
||||
String warehouseCode) { |
||||
List<BillingDocument> out = new ArrayList<BillingDocument>(); |
||||
if (row.chargeDetails == null || row.chargeDetails.isEmpty()) { |
||||
// 只有汇总金额的情况下退化为一条「订单总费用」
|
||||
out.add(baseBuilder(row, warehouseCode) |
||||
.feeName("订单总费用") |
||||
.feeType(null) |
||||
.amount(Money.zero(defaultCurrency(row))) |
||||
.build()); |
||||
return out; |
||||
} |
||||
|
||||
for (EdayunOrderCostDtos.ChargeDetail charge : row.chargeDetails) { |
||||
if (charge.feeDetails != null && !charge.feeDetails.isEmpty()) { |
||||
for (EdayunOrderCostDtos.FeeDetail fee : charge.feeDetails) { |
||||
out.add(baseBuilder(row, warehouseCode) |
||||
.feeName(fee.billingName) |
||||
.feeType(feeTypeOf(fee.billingName)) |
||||
.amount(moneyOf(fee.realPayPrice, |
||||
firstNonBlank(fee.currencyCode, fee.quotationCurrency, |
||||
defaultCurrency(row)))) |
||||
.build()); |
||||
} |
||||
} else { |
||||
out.add(baseBuilder(row, warehouseCode) |
||||
.feeName("订单费用") |
||||
.feeType(null) |
||||
.amount(moneyOf(charge.realPayPrice, |
||||
firstNonBlank(charge.currencyCode, charge.quotationCurrency, |
||||
defaultCurrency(row)))) |
||||
.build()); |
||||
} |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
private static BillingDocument.Builder baseBuilder(EdayunOrderCostDtos.OrderCostRow row, |
||||
String warehouseCode) { |
||||
return BillingDocument.builder() |
||||
.warehouseCode(firstNonBlank(row.warehouseName, warehouseCode)) |
||||
.sourceProvider(WarehouseProvider.EDAYUN) |
||||
.documentNo(row.orderCode) |
||||
.serialNumber(row.trackingNo) |
||||
// 订单费用是实际发生的,不是预估
|
||||
.estimated(false) |
||||
.settledAt(row.billingTime == null ? null : Instant.ofEpochMilli(row.billingTime)) |
||||
.saleOrderNo(firstNonBlank(row.poNumber, row.orderCode)); |
||||
} |
||||
|
||||
/** |
||||
* 按计费项名称归类。 |
||||
* |
||||
* <p>易达云的名称是中文(如「尾程-出库处理费」),按关键字推断; |
||||
* 认不出返回 null,不猜——对账时宁可不分类,也不能分错。</p> |
||||
*/ |
||||
static WarehouseFeeType feeTypeOf(String name) { |
||||
if (!hasText(name)) { |
||||
return null; |
||||
} |
||||
String n = name.toLowerCase(); |
||||
if (n.contains("仓储") || n.contains("storage") || n.contains("仓租")) { |
||||
return WarehouseFeeType.STORAGE; |
||||
} |
||||
if (n.contains("处理费") || n.contains("operation") || n.contains("handling") |
||||
|| n.contains("操作")) { |
||||
return WarehouseFeeType.OPERATION; |
||||
} |
||||
if (n.contains("尾程") || n.contains("运费") || n.contains("freight") |
||||
|| n.contains("delivery") || n.contains("燃油") || n.contains("附加费")) { |
||||
return WarehouseFeeType.LAST_MILE; |
||||
} |
||||
if (n.contains("增值") || n.contains("service") || n.contains("贴标") |
||||
|| n.contains("label") || n.contains("打包")) { |
||||
return WarehouseFeeType.VALUE_ADDED; |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
private static String defaultCurrency(EdayunOrderCostDtos.OrderCostRow row) { |
||||
return "USD"; |
||||
} |
||||
|
||||
private static Money moneyOf(Double amount, String currency) { |
||||
if (amount == null) { |
||||
return Money.zero(currency == null ? "USD" : currency); |
||||
} |
||||
return Money.of(BigDecimal.valueOf(amount), currency == null ? "USD" : currency); |
||||
} |
||||
|
||||
private static String firstNonBlank(String... values) { |
||||
for (String v : values) { |
||||
if (hasText(v)) { |
||||
return v.trim(); |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
private static boolean hasText(String v) { |
||||
return v != null && !v.trim().isEmpty(); |
||||
} |
||||
} |
||||
@ -0,0 +1,202 @@
@@ -0,0 +1,202 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.dto.EdayunCreateOrderDtos; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.LabelMode; |
||||
import common.ecommerce.warehouse.model.OutboundCommand; |
||||
import common.ecommerce.warehouse.model.OutboundLine; |
||||
import common.ecommerce.warehouse.model.ShipTo; |
||||
|
||||
import java.time.Instant; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云出库单报文映射({@code POST /webApi/order/v1/createOrder})。 |
||||
* |
||||
* <p>三处需要注意的口径:</p> |
||||
* <ul> |
||||
* <li><b>幂等键是 {@code poNumber}</b>——文档明确「取消重推要保证平台单号跟之前一样」</li> |
||||
* <li><b>时间戳单位是毫秒</b>({@code promiseShipTime}),不是秒</li> |
||||
* <li><b>地址是州全称</b>({@code California}),不是二字码——标准模型给的是 {@code CA}</li> |
||||
* </ul> |
||||
*/ |
||||
public final class EdayunOrderMapper { |
||||
|
||||
private EdayunOrderMapper() { |
||||
} |
||||
|
||||
/** 统一命令 → 创建出库单请求。 */ |
||||
public static EdayunCreateOrderDtos.CreateOrderRequest toCreateRequest( |
||||
OutboundCommand cmd, String providerWarehouseId) { |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = |
||||
new EdayunCreateOrderDtos.CreateOrderRequest(); |
||||
|
||||
// 幂等键:文档要求重推时保持不变
|
||||
req.poNumber = firstNonBlank(cmd.orderRef(), cmd.outboundRequestNo()); |
||||
req.remark = cmd.remark(); |
||||
req.currency = cmd.currency() == null ? null : cmd.currency().trim(); |
||||
|
||||
Money total = cmd.declaredTotal(); |
||||
if (total != null) { |
||||
req.orderCost = total.amount().doubleValue(); |
||||
if (req.currency == null) { |
||||
req.currency = total.currency().getCurrencyCode(); |
||||
} |
||||
} |
||||
|
||||
// 仓库:命令显式指定优先,否则用账户配置
|
||||
req.warehouseId = firstNonBlank(cmd.warehouseId(), providerWarehouseId); |
||||
|
||||
// 平台:易达云要平台名称字符串
|
||||
req.channelName = channelNameOf(cmd); |
||||
req.primeFlag = cmd.sfp(); |
||||
|
||||
// 最晚发货时间:毫秒时间戳
|
||||
req.promiseShipTime = millisOf(cmd.latestShipDate()); |
||||
|
||||
req.orderAddressVO = toAddress(cmd.shipTo()); |
||||
req.productItemVOList = toProducts(cmd.lines()); |
||||
req.addService = addServicesOf(cmd); |
||||
|
||||
applyPlatformLabel(cmd, req); |
||||
applyWarehouseLabel(cmd, req); |
||||
return req; |
||||
} |
||||
|
||||
/** |
||||
* 平台面单 / 自供面单:文档要求「物流产品 + 面单信息」两个条件缺一不可。 |
||||
* |
||||
* <p>标准模型里对应 {@code labelMode=PLATFORM_LABEL} + {@code labelContentBase64} + |
||||
* {@code trackingNumber}。</p> |
||||
* |
||||
* <p><b>注意</b>:易达云要的是<b>文件 URL</b>,不是 base64。所以 |
||||
* {@code labelContentBase64} 在这里无法直接用——若调用方给的是 URL 就透传, |
||||
* 给的是 base64 则拒绝并说明原因(不静默丢弃)。</p> |
||||
*/ |
||||
private static void applyPlatformLabel(OutboundCommand cmd, |
||||
EdayunCreateOrderDtos.CreateOrderRequest req) { |
||||
if (cmd.labelMode() != LabelMode.PLATFORM_LABEL) { |
||||
return; |
||||
} |
||||
String content = cmd.labelContentBase64(); |
||||
if (content == null || content.trim().isEmpty()) { |
||||
return; |
||||
} |
||||
if (content.startsWith("http://") || content.startsWith("https://")) { |
||||
req.labels = content.trim(); |
||||
} else { |
||||
throw new IllegalArgumentException( |
||||
"edayun needs a label FILE URL, got base64 for " + cmd.outboundRequestNo() |
||||
+ "; upload the file first and pass its URL"); |
||||
} |
||||
req.trackingNo = firstNonBlank(cmd.trackingNumber(), req.trackingNo); |
||||
req.carrierName = firstNonBlank(cmd.carrier(), req.carrierName); |
||||
} |
||||
|
||||
/** 仓自有面单:只需承运商信息,不需要 labels。 */ |
||||
private static void applyWarehouseLabel(OutboundCommand cmd, |
||||
EdayunCreateOrderDtos.CreateOrderRequest req) { |
||||
if (cmd.labelMode() == LabelMode.PLATFORM_LABEL) { |
||||
return; |
||||
} |
||||
req.carrierName = firstNonBlank(cmd.carrier(), cmd.carrierCode()); |
||||
} |
||||
|
||||
/** 物流增值:签收 / 保价。 */ |
||||
private static List<String> addServicesOf(OutboundCommand cmd) { |
||||
List<String> services = new ArrayList<String>(2); |
||||
if (Boolean.TRUE.equals(cmd.signatureRequired())) { |
||||
services.add(EdayunConstants.ADD_SERVICE_SIGNATURE); |
||||
} |
||||
return services.isEmpty() ? null : services; |
||||
} |
||||
|
||||
/** 地址:注意运去哪用州二字码,易达云要州全称。 */ |
||||
private static EdayunCreateOrderDtos.CreateOrderRequest.OrderAddress toAddress(ShipTo shipTo) { |
||||
EdayunCreateOrderDtos.CreateOrderRequest.OrderAddress addr = |
||||
new EdayunCreateOrderDtos.CreateOrderRequest.OrderAddress(); |
||||
addr.buyerName = shipTo.name(); |
||||
addr.buyerPhone = shipTo.phone(); |
||||
addr.email = shipTo.email(); |
||||
addr.destCountryName = shipTo.countryCode(); |
||||
// 标准模型给的是二字码(CA);易达云要全称(California)。
|
||||
// 这里原样透传,由调用方决定传哪个——映射表需要业务确认。
|
||||
addr.destProvinceName = shipTo.stateOrProvince(); |
||||
addr.destCity = shipTo.city(); |
||||
addr.destFirstAddress = shipTo.addressLine1(); |
||||
addr.destSecondAddress = joinNonBlank(shipTo.addressLine2(), shipTo.addressLine3()); |
||||
addr.zipCode = shipTo.postalCode(); |
||||
return addr; |
||||
} |
||||
|
||||
private static List<EdayunCreateOrderDtos.CreateOrderRequest.ProductItem> toProducts( |
||||
List<OutboundLine> lines) { |
||||
if (lines == null || lines.isEmpty()) { |
||||
return null; |
||||
} |
||||
List<EdayunCreateOrderDtos.CreateOrderRequest.ProductItem> out = |
||||
new ArrayList<EdayunCreateOrderDtos.CreateOrderRequest.ProductItem>(lines.size()); |
||||
for (OutboundLine line : lines) { |
||||
EdayunCreateOrderDtos.CreateOrderRequest.ProductItem item = |
||||
new EdayunCreateOrderDtos.CreateOrderRequest.ProductItem(); |
||||
item.productSku = firstNonBlank(line.providerSku(), line.omsSku()); |
||||
item.quantity = line.quantity(); |
||||
Money value = line.declareValue(); |
||||
if (value != null) { |
||||
// 文档说 unitPrice 是单价(不是总额),所以直接取值,不乘数量
|
||||
item.unitPrice = value.amount().doubleValue(); |
||||
item.currencyCode = value.currency().getCurrencyCode(); |
||||
} |
||||
if (!line.platformOrderItemIds().isEmpty()) { |
||||
item.platformItemId = line.platformOrderItemIds().get(0); |
||||
} |
||||
out.add(item); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
/** 平台名称:标准模型是枚举,易达云要字符串。 */ |
||||
static String channelNameOf(OutboundCommand cmd) { |
||||
if (cmd.salesPlatform() == null) { |
||||
return null; |
||||
} |
||||
// Platform 枚举名形如 AMAZON_SC / WALMART_SC / EBAY;
|
||||
// 取第一段并转成易达云文档里的大小写(Amazon / eBay / Temu / TIKTOK)
|
||||
String name = cmd.salesPlatform().name(); |
||||
int underscore = name.indexOf('_'); |
||||
String base = underscore > 0 ? name.substring(0, underscore) : name; |
||||
if ("AMAZON".equals(base)) { |
||||
return "Amazon"; |
||||
} |
||||
if ("TIKTOK".equals(base)) { |
||||
return "TIKTOK"; |
||||
} |
||||
if ("EBAY".equals(base)) { |
||||
return "eBay"; |
||||
} |
||||
// 其余按首字母大写
|
||||
return base.charAt(0) + base.substring(1).toLowerCase(); |
||||
} |
||||
|
||||
private static Long millisOf(Instant instant) { |
||||
return instant == null ? null : instant.toEpochMilli(); |
||||
} |
||||
|
||||
private static String joinNonBlank(String a, String b) { |
||||
String first = firstNonBlank(a, null); |
||||
String second = firstNonBlank(b, null); |
||||
if (first == null) { |
||||
return second; |
||||
} |
||||
return second == null ? first : first + " " + second; |
||||
} |
||||
|
||||
private static String firstNonBlank(String a, String b) { |
||||
if (a != null && !a.trim().isEmpty()) { |
||||
return a.trim(); |
||||
} |
||||
return b != null && !b.trim().isEmpty() ? b.trim() : null; |
||||
} |
||||
} |
||||
@ -0,0 +1,296 @@
@@ -0,0 +1,296 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunGetOrderDtos; |
||||
import common.ecommerce.edayun.dto.EdayunGetOrderLabelDtos; |
||||
import common.ecommerce.edayun.enums.EdayunOrderStatus; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.LabelMode; |
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.OutboundLine; |
||||
import common.ecommerce.warehouse.model.OutboundOrder; |
||||
import common.ecommerce.warehouse.model.PackageResult; |
||||
import common.ecommerce.warehouse.model.SerialNumber; |
||||
import common.ecommerce.warehouse.model.ShipTo; |
||||
import common.ecommerce.warehouse.model.WarehouseAttachment; |
||||
|
||||
import java.time.Instant; |
||||
import java.util.ArrayList; |
||||
import java.util.Collections; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云出库单查询报文映射。 |
||||
* |
||||
* <p>两个接口:</p> |
||||
* <ul> |
||||
* <li>{@code getOrderInfo} → {@link OutboundOrder}(含包裹、SN、地址、增值服务)</li> |
||||
* <li>{@code getOrderLabel} → 面单 URL 列表</li> |
||||
* </ul> |
||||
* |
||||
* <p>三处口径与创建侧对称:时间戳是毫秒、金额币种在顶层、异常原因在 {@code errorMsg}。</p> |
||||
*/ |
||||
public final class EdayunOrderQueryMapper { |
||||
|
||||
private EdayunOrderQueryMapper() { |
||||
} |
||||
|
||||
/** 订单详情 → 统一出库单。 */ |
||||
public static OutboundOrder toOrder(EdayunGetOrderDtos.OrderInfo info, String warehouseCode, |
||||
String requestedOrderNo) { |
||||
OutboundStatus status = EdayunOrderStatus.toCore(info.orderStatus); |
||||
List<EdayunGetOrderDtos.OrderInfo.CarrierInfo> carriers = info.carrierInfoList; |
||||
|
||||
OutboundOrder.Builder builder = OutboundOrder.builder() |
||||
.warehouseCode(firstNonBlank(info.warehouseCode, warehouseCode)) |
||||
// poNumber 是我们下发的来源单号;orderNo 是仓侧的
|
||||
.outboundRequestNo(firstNonBlank(info.poNumber, requestedOrderNo)) |
||||
.providerOrderId(info.orderNo) |
||||
.orderRef(info.poNumber) |
||||
.status(status) |
||||
.rawStatus(info.orderStatus) |
||||
.carrier(firstNonBlank(info.carrierName, firstCarrierName(carriers))) |
||||
.trackingNumber(firstNonBlank(info.trackingNo, firstTracking(carriers))) |
||||
.carrierCode(firstNonBlank(info.carrierId, firstCarrierId(carriers))) |
||||
.currency(info.currency) |
||||
.requestedAt(instantOf(info.createTime, null)) |
||||
.shippedAt(instantOf(null, info.shippedTime)) |
||||
.shipTo(toShipTo(info.orderAddressVO)) |
||||
.exceptionCode(hasText(info.errorMsg) ? info.errorMsg : null) |
||||
.estimatedShippingFee(moneyOrNull(info.estimatedCost, info.currency)) |
||||
.insured(flagOf(info.orderAttribute == null ? null : info.orderAttribute.insuranceFlag)) |
||||
.signatureRequired(flagOf(info.orderAttribute == null ? null |
||||
: info.orderAttribute.signatureFlag)) |
||||
.sourceProvider(WarehouseProvider.EDAYUN); |
||||
|
||||
builder.lines(toLines(info.productItemVOList)); |
||||
for (SerialNumber sn : toSerialNumbers(info.productItemVOList)) { |
||||
builder.serialNumber(sn); |
||||
} |
||||
for (WarehouseAttachment att : toAttachments(carriers)) { |
||||
builder.attachment(att); |
||||
} |
||||
return builder.build(); |
||||
} |
||||
|
||||
/** 面单查询 → 包裹列表(一个包裹一个 tracker + 一个面单 URL)。 */ |
||||
public static List<PackageResult> toPackages(EdayunGetOrderLabelDtos.LabelData data, |
||||
String outboundRequestNo) { |
||||
if (data == null || !hasText(data.trackingNo)) { |
||||
return Collections.emptyList(); |
||||
} |
||||
List<String> trackings = split(data.trackingNo); |
||||
List<String> labels = split(data.labels); |
||||
|
||||
List<PackageResult> out = new ArrayList<PackageResult>(trackings.size()); |
||||
for (int i = 0; i < trackings.size(); i++) { |
||||
String tracking = trackings.get(i); |
||||
out.add(PackageResult.builder() |
||||
.packageId(hasText(tracking) ? tracking : "PKG-" + i) |
||||
.outboundRequestNo(firstNonBlank(data.poNumber, outboundRequestNo)) |
||||
.trackingNumber(hasText(tracking) ? tracking : null) |
||||
.carrier(data.carrierName) |
||||
.carrierCode(data.carrierId) |
||||
// 多个 labels 与多个 trackingNo 按位置对应
|
||||
.labelRef(i < labels.size() ? labels.get(i) : null) |
||||
.build()); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
/** |
||||
* 面单 URL 列表 → 附件。 |
||||
* |
||||
* <p>与 {@code trackingNo} 按逗号位置对应;数量不一致时按索引匹配,多出来的忽略。</p> |
||||
*/ |
||||
public static List<WarehouseAttachment> attachmentsOf(EdayunGetOrderLabelDtos.LabelData data) { |
||||
if (data == null) { |
||||
return Collections.emptyList(); |
||||
} |
||||
List<String> trackings = split(data.trackingNo); |
||||
List<String> labels = split(data.labels); |
||||
List<WarehouseAttachment> out = new ArrayList<WarehouseAttachment>(labels.size()); |
||||
for (int i = 0; i < labels.size(); i++) { |
||||
String url = labels.get(i); |
||||
if (!hasText(url)) { |
||||
continue; |
||||
} |
||||
out.add(WarehouseAttachment.builder() |
||||
.name(i < trackings.size() && hasText(trackings.get(i)) |
||||
? trackings.get(i) : "label-" + i) |
||||
.type("ShippingLabel") |
||||
.url(url) |
||||
.build()); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 子结构
|
||||
|
||||
private static ShipTo toShipTo(EdayunGetOrderDtos.OrderInfo.OrderAddress a) { |
||||
if (a == null) { |
||||
return null; |
||||
} |
||||
return ShipTo.builder() |
||||
.name(a.buyerName) |
||||
.phone(a.buyerPhone) |
||||
.email(a.email) |
||||
.countryCode(firstNonBlank(a.destCountry, a.destCountryName)) |
||||
// 易达云同时给了二字码与全称;优先二字码(标准模型口径)
|
||||
.stateOrProvince(firstNonBlank(a.destProvince, a.destProvinceName)) |
||||
.city(firstNonBlank(a.destCity, a.destCityName)) |
||||
.addressLine1(a.destFirstAddress) |
||||
.addressLine2(a.destSecondAddress) |
||||
.postalCode(a.zipCode) |
||||
.build(); |
||||
} |
||||
|
||||
private static List<OutboundLine> toLines(List<EdayunGetOrderDtos.OrderInfo.ProductItem> items) { |
||||
if (items == null || items.isEmpty()) { |
||||
return Collections.emptyList(); |
||||
} |
||||
List<OutboundLine> out = new ArrayList<OutboundLine>(items.size()); |
||||
for (EdayunGetOrderDtos.OrderInfo.ProductItem item : items) { |
||||
if (!hasText(item.productSku)) { |
||||
continue; |
||||
} |
||||
out.add(OutboundLine.builder() |
||||
.lineNo(item.productSku) |
||||
.omsSku(item.productSku) |
||||
.providerSku(item.productSku) |
||||
.quantity(item.quantity == null ? 0 : item.quantity) |
||||
.declareValue(moneyOrNull(item.unitPrice, null)) |
||||
.build()); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
/** 序列号:按 SKU 汇总。 */ |
||||
private static List<SerialNumber> toSerialNumbers( |
||||
List<EdayunGetOrderDtos.OrderInfo.ProductItem> items) { |
||||
if (items == null || items.isEmpty()) { |
||||
return Collections.emptyList(); |
||||
} |
||||
List<SerialNumber> out = new ArrayList<SerialNumber>(); |
||||
for (EdayunGetOrderDtos.OrderInfo.ProductItem item : items) { |
||||
if (item.snCodeList == null) { |
||||
continue; |
||||
} |
||||
for (String sn : item.snCodeList) { |
||||
if (!hasText(sn)) { |
||||
continue; |
||||
} |
||||
out.add(SerialNumber.builder() |
||||
.providerSku(item.productSku) |
||||
.snCode(sn.trim()) |
||||
.lineNo(item.productSku) |
||||
.build()); |
||||
} |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
/** 包裹的面单地址 → 附件。 */ |
||||
private static List<WarehouseAttachment> toAttachments( |
||||
List<EdayunGetOrderDtos.OrderInfo.CarrierInfo> carriers) { |
||||
if (carriers == null || carriers.isEmpty()) { |
||||
return Collections.emptyList(); |
||||
} |
||||
List<WarehouseAttachment> out = new ArrayList<WarehouseAttachment>(); |
||||
for (EdayunGetOrderDtos.OrderInfo.CarrierInfo c : carriers) { |
||||
if (!hasText(c.fileUrl)) { |
||||
continue; |
||||
} |
||||
out.add(WarehouseAttachment.builder() |
||||
.name(firstNonBlank(c.fileName, c.trackingNo)) |
||||
.type("ShippingLabel") |
||||
.url(c.fileUrl) |
||||
.packageNo(c.trackingNo) |
||||
.build()); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
private static String firstCarrierName(List<EdayunGetOrderDtos.OrderInfo.CarrierInfo> list) { |
||||
return firstField(list, Field.NAME); |
||||
} |
||||
|
||||
private static String firstCarrierId(List<EdayunGetOrderDtos.OrderInfo.CarrierInfo> list) { |
||||
return firstField(list, Field.ID); |
||||
} |
||||
|
||||
private static String firstTracking(List<EdayunGetOrderDtos.OrderInfo.CarrierInfo> list) { |
||||
return firstField(list, Field.TRACKING); |
||||
} |
||||
|
||||
private enum Field { NAME, ID, TRACKING } |
||||
|
||||
private static String firstField(List<EdayunGetOrderDtos.OrderInfo.CarrierInfo> list, Field f) { |
||||
if (list == null) { |
||||
return null; |
||||
} |
||||
for (EdayunGetOrderDtos.OrderInfo.CarrierInfo c : list) { |
||||
String v = f == Field.NAME ? c.carrierName |
||||
: f == Field.ID ? c.carrierId : c.trackingNo; |
||||
if (hasText(v)) { |
||||
return v.trim(); |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
// ------------------------------------------------------------ helpers
|
||||
|
||||
/** 易达云的毫秒时间戳字段有的是 number、有的是 string,统一转。 */ |
||||
static Instant instantOf(String epochText, Long epochMillis) { |
||||
if (epochMillis != null && epochMillis > 0) { |
||||
return Instant.ofEpochMilli(epochMillis); |
||||
} |
||||
if (!hasText(epochText)) { |
||||
return null; |
||||
} |
||||
try { |
||||
long v = Long.parseLong(epochText.trim()); |
||||
// 10 位按秒,13 位按毫秒
|
||||
return epochText.trim().length() <= 10 ? Instant.ofEpochSecond(v) : Instant.ofEpochMilli(v); |
||||
} catch (NumberFormatException e) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
/** 0/1 旗标;null 保持 null(「仓方未给」不等于「否」)。 */ |
||||
static Boolean flagOf(Integer flag) { |
||||
return flag == null ? null : flag != 0; |
||||
} |
||||
|
||||
private static Money moneyOrNull(Double amount, String currency) { |
||||
if (amount == null) { |
||||
return null; |
||||
} |
||||
return Money.of(java.math.BigDecimal.valueOf(amount), |
||||
hasText(currency) ? currency.trim() : "USD"); |
||||
} |
||||
|
||||
private static List<String> split(String csv) { |
||||
if (!hasText(csv)) { |
||||
return Collections.emptyList(); |
||||
} |
||||
String[] parts = csv.split(","); |
||||
List<String> out = new ArrayList<String>(parts.length); |
||||
for (String p : parts) { |
||||
out.add(p.trim()); |
||||
} |
||||
return out; |
||||
} |
||||
|
||||
private static String firstNonBlank(String a, String b) { |
||||
if (hasText(a)) { |
||||
return a.trim(); |
||||
} |
||||
return hasText(b) ? b.trim() : null; |
||||
} |
||||
|
||||
private static boolean hasText(String v) { |
||||
return v != null && !v.trim().isEmpty(); |
||||
} |
||||
} |
||||
@ -0,0 +1,139 @@
@@ -0,0 +1,139 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunCreateProductDtos; |
||||
import common.ecommerce.edayun.enums.EdayunDeclarationType; |
||||
import common.ecommerce.edayun.enums.EdayunYesNo; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.capability.WarehouseProduct; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云商品报文映射({@code POST /webApi/skuInfo/v1/createProduct})。 |
||||
* |
||||
* <p>单位差异:{@link WarehouseProduct} 用 g / cm,易达云用 <b>kg</b> / cm。 |
||||
* 重量在这里换算,调用方不用管。</p> |
||||
* |
||||
* <p>三处「字段有默认值但语义不同」的地方:</p> |
||||
* <ul> |
||||
* <li>{@code brandFlag}:0 是 / 1 否(<b>与直觉相反</b>),没有品牌信息时传 1</li> |
||||
* <li>{@code logisticsPackagingType}:0 是 / 1 否,同样反向</li> |
||||
* <li>{@code electricFlag}:0 带电 / 1 不带电,同样反向</li> |
||||
* </ul> |
||||
*/ |
||||
public final class EdayunProductMapper { |
||||
|
||||
/** 1 克 = 0.001 千克。 */ |
||||
private static final double GRAMS_PER_KG = 1000.0; |
||||
|
||||
private EdayunProductMapper() { |
||||
} |
||||
|
||||
/** 统一商品 → 创建产品请求。 */ |
||||
public static EdayunCreateProductDtos.CreateProductRequest toCreateRequest(WarehouseProduct product) { |
||||
EdayunCreateProductDtos.CreateProductRequest req = |
||||
new EdayunCreateProductDtos.CreateProductRequest(); |
||||
|
||||
req.skuCode = skuOf(product); |
||||
req.skuName = product.name(); |
||||
req.skuNameEn = product.nameEn(); |
||||
req.extraBarcode1 = product.barcode(); |
||||
req.skuUrl = product.link(); |
||||
req.remark = product.remark(); |
||||
|
||||
// 反向标志:没有品牌信息时传「非品牌」
|
||||
req.brandFlag = EdayunYesNo.noOf(product.customItemNo() != null |
||||
&& !product.customItemNo().trim().isEmpty()); |
||||
|
||||
req.weight = gramsToKg(product.weightGrams()); |
||||
req.length = product.lengthCm(); |
||||
req.width = product.widthCm(); |
||||
req.height = product.heightCm(); |
||||
|
||||
// 统一模型没有「是否自带物流包装」的概念,默认按「自带」传 0
|
||||
req.logisticsPackagingType = 0; |
||||
// 统一模型没有包材概念,默认不是包材
|
||||
req.pmFlag = Boolean.FALSE; |
||||
|
||||
// 带电信息由调用方经 packType 之外的通道表达不了,默认按不带电
|
||||
req.electricFlag = 1; |
||||
|
||||
req.batchManagementEnabled = EdayunYesNo.codeOf(product.lotControlEnabled()); |
||||
req.collectSerialNumber = product.snManagementMode() == null ? null |
||||
: (product.snManagementMode() > 0 ? 1 : 0); |
||||
|
||||
// 图片
|
||||
if (product.imageUrl() != null && !product.imageUrl().trim().isEmpty()) { |
||||
EdayunCreateProductDtos.CreateProductRequest.Picture pic = |
||||
new EdayunCreateProductDtos.CreateProductRequest.Picture(); |
||||
pic.picUrl = product.imageUrl().trim(); |
||||
List<EdayunCreateProductDtos.CreateProductRequest.Picture> pics = |
||||
new ArrayList<EdayunCreateProductDtos.CreateProductRequest.Picture>(1); |
||||
pics.add(pic); |
||||
req.picList = pics; |
||||
} |
||||
|
||||
// 效期 → batchInfo
|
||||
if (product.expirationControl() != null && product.expirationControl() |
||||
&& product.expirationDays() != null) { |
||||
EdayunCreateProductDtos.CreateProductRequest.BatchInfo batch = |
||||
new EdayunCreateProductDtos.CreateProductRequest.BatchInfo(); |
||||
batch.expirationEnabled = 1; |
||||
batch.shelfLifeDays = product.expirationDays(); |
||||
req.batchInfo = batch; |
||||
} |
||||
|
||||
req.declarationInfoList = declarationsOf(product); |
||||
return req; |
||||
} |
||||
|
||||
/** |
||||
* 申报信息:出口 + 进口各一条。 |
||||
* |
||||
* <p>文档要求「一个 sku 至少需要一条出口 + 一条进口」,但标准模型只有一组 |
||||
* 申报字段(HS / 原产国 / 申报价值 / 申报品名)。这里用同一组数据生成两条, |
||||
* 国家分别取 {@code countryOfOrigin}(出口)与默认 {@code US}(进口)。</p> |
||||
* |
||||
* <p><b>待确认</b>:进口国的取法需要业务侧明确——目前是猜的。</p> |
||||
*/ |
||||
private static List<EdayunCreateProductDtos.CreateProductRequest.Declaration> declarationsOf( |
||||
WarehouseProduct product) { |
||||
Money value = product.declaredValue(); |
||||
String origin = product.countryOfOrigin(); |
||||
if (value == null || origin == null || origin.trim().isEmpty()) { |
||||
// 文档标必填,但标准模型允许这三个字段整组缺省;缺省时不下发,
|
||||
// 由仓方报错——不在本地编造申报信息
|
||||
return null; |
||||
} |
||||
|
||||
List<EdayunCreateProductDtos.CreateProductRequest.Declaration> out = |
||||
new ArrayList<EdayunCreateProductDtos.CreateProductRequest.Declaration>(2); |
||||
out.add(declaration(EdayunDeclarationType.EXPORT, origin.trim().toUpperCase(), value)); |
||||
out.add(declaration(EdayunDeclarationType.IMPORT, DEFAULT_IMPORT_COUNTRY, value)); |
||||
return out; |
||||
} |
||||
|
||||
/** 进口国默认值;<b>待业务确认</b>。 */ |
||||
private static final String DEFAULT_IMPORT_COUNTRY = "US"; |
||||
|
||||
private static EdayunCreateProductDtos.CreateProductRequest.Declaration declaration( |
||||
EdayunDeclarationType type, String country, Money value) { |
||||
EdayunCreateProductDtos.CreateProductRequest.Declaration d = |
||||
new EdayunCreateProductDtos.CreateProductRequest.Declaration(); |
||||
d.declarationType = type.code(); |
||||
d.country = country; |
||||
d.declaredPrice = value.amount().doubleValue(); |
||||
d.currencyType = value.currency().getCurrencyCode(); |
||||
return d; |
||||
} |
||||
|
||||
private static String skuOf(WarehouseProduct product) { |
||||
String sku = product.providerSku(); |
||||
return sku != null && !sku.trim().isEmpty() ? sku.trim() : product.omsSku(); |
||||
} |
||||
|
||||
static Double gramsToKg(double grams) { |
||||
return grams / GRAMS_PER_KG; |
||||
} |
||||
} |
||||
@ -0,0 +1,217 @@
@@ -0,0 +1,217 @@
|
||||
package common.ecommerce.edayun.auth; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.dto.EdayunTokenDtos; |
||||
import common.ecommerce.edayun.http.EdayunRequestFactory; |
||||
import common.ecommerce.http.HttpRequest; |
||||
import common.ecommerce.http.HttpResponse; |
||||
import common.ecommerce.http.JsonCodec; |
||||
import common.ecommerce.http.HttpTransport; |
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.shared.spi.AccessToken; |
||||
import common.ecommerce.warehouse.error.WarehouseException; |
||||
|
||||
import java.time.Clock; |
||||
import java.time.Instant; |
||||
|
||||
/** |
||||
* 易达云获取 token({@code POST /oauth/token})。 |
||||
* |
||||
* <p>凭据用 OMS 授权账号:{@link common.ecommerce.shared.spi.ChannelSecret#clientId()} |
||||
* / {@link common.ecommerce.shared.spi.ChannelSecret#clientSecret()}。 |
||||
* appKey 不参与这一步(它是业务请求头的字段)。</p> |
||||
* |
||||
* <p><b>实测(2026-11-12,PR 环境)</b>:成功响应的 body 是扁平结构,没有 {@code code}:</p> |
||||
* <pre> |
||||
* HTTP 200 |
||||
* {"access_token":"0dabff46-...","token_type":"bearer","scope":"server"} |
||||
* </pre> |
||||
* |
||||
* <p>token 是<b>永久</b>的(文档:「目前设计上是永久的,建议留个窗口刷新」), |
||||
* 响应里没有有效期字段。所以 {@code expiresAt} 是个估算值——用于让 |
||||
* {@code TokenManager} 定期重登一次,而不是真的到期。</p> |
||||
* |
||||
* <p>兼容分支:若网关把结果包一层 {@code data} 或返回 {@code code}, |
||||
* 也按对应形态解析(生产环境确认后可删)。</p> |
||||
*/ |
||||
public final class EdayunTokenClient { |
||||
|
||||
private static final String OP_FETCH = "token.fetch"; |
||||
|
||||
private final HttpTransport transport; |
||||
private final JsonCodec json; |
||||
private final EdayunRequestFactory requestFactory; |
||||
private final Clock clock; |
||||
|
||||
public EdayunTokenClient(HttpTransport transport, JsonCodec json, Clock clock) { |
||||
this.transport = transport; |
||||
this.json = json; |
||||
this.clock = clock; |
||||
this.requestFactory = new EdayunRequestFactory(json); |
||||
} |
||||
|
||||
/** |
||||
* 换取令牌。 |
||||
* |
||||
* @param baseUrl 本次调用的基址 |
||||
* @param clientId OMS 授权用户名 |
||||
* @param clientSecret OMS 授权密码 |
||||
*/ |
||||
public AccessToken fetch(String baseUrl, String clientId, String clientSecret) { |
||||
HttpRequest req = requestFactory.token(baseUrl, clientId, clientSecret, OP_FETCH); |
||||
HttpResponse resp = transport.execute(req); |
||||
requireHttpOk(resp); |
||||
|
||||
String body = resp.body(); |
||||
EdayunTokenDtos.TokenResponse parsed; |
||||
try { |
||||
parsed = json.fromJson(body, EdayunTokenDtos.TokenResponse.class); |
||||
} catch (RuntimeException e) { |
||||
throw validation("edayun token response is not json", body); |
||||
} |
||||
requireBusinessOk(parsed, body); |
||||
|
||||
String token = tokenOf(parsed, body); |
||||
return AccessToken.builder() |
||||
.value(token) |
||||
.expiresAt(expiresAtOf(parsed)) |
||||
.build(); |
||||
} |
||||
|
||||
/** HTTP 层:非 2xx 直接失败。 */ |
||||
private void requireHttpOk(HttpResponse resp) { |
||||
int status = resp.statusCode(); |
||||
if (status >= 200 && status < 300) { |
||||
return; |
||||
} |
||||
throw toException(status, resp.body()); |
||||
} |
||||
|
||||
private WarehouseException toException(int status, String body) { |
||||
boolean retryable = status >= 500 && status != 504; |
||||
return WarehouseException.builder() |
||||
.message("edayun token request failed: http " + status |
||||
+ ", body=" + truncate(body)) |
||||
.operation(OP_FETCH) |
||||
.provider(EdayunConstants.ADAPTER_ID) |
||||
.platformCode(String.valueOf(status)) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(retryable) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* 业务码:200 成功;500 失败;503 网关无效;504 超时。 |
||||
* |
||||
* <p><b>实测该接口不返回 {@code code}</b>——HTTP 200 + body 里有 access_token |
||||
* 就是成功。所以 {@code code} 缺失时不算失败,交给后续的 token 存在性校验; |
||||
* 只有显式给了非 200 的 code 才判失败。</p> |
||||
* |
||||
* <p>503 通常是网关问题、504 是超时,都值得重试;500 是明确失败,不重试。</p> |
||||
*/ |
||||
private void requireBusinessOk(EdayunTokenDtos.TokenResponse parsed, String body) { |
||||
if (parsed == null) { |
||||
throw validation("edayun token response is empty", body); |
||||
} |
||||
Integer code = parsed.code; |
||||
if (code == null) { |
||||
// 实测:扁平结构没有 code,视为成功,由 tokenOf 校验 token 是否存在
|
||||
return; |
||||
} |
||||
if (code == EdayunConstants.CODE_SUCCESS) { |
||||
return; |
||||
} |
||||
throw WarehouseException.builder() |
||||
.message("edayun token business error: code=" + code |
||||
+ ", message=" + parsed.message) |
||||
.operation(OP_FETCH) |
||||
.provider(EdayunConstants.ADAPTER_ID) |
||||
.platformCode(String.valueOf(code)) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(code == EdayunConstants.CODE_GATEWAY_INVALID |
||||
|| code == EdayunConstants.CODE_TIMEOUT) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* 取 token:实测是顶层 {@code access_token};兼容 {@code data.access_token} |
||||
* 与顶层 {@code token}。都取不到就失败,不猜。 |
||||
*/ |
||||
private String tokenOf(EdayunTokenDtos.TokenResponse parsed, String body) { |
||||
if (hasText(parsed.accessToken)) { |
||||
return parsed.accessToken.trim(); |
||||
} |
||||
if (parsed.data != null && hasText(parsed.data.accessToken)) { |
||||
return parsed.data.accessToken.trim(); |
||||
} |
||||
String topLevel = json.stringAt(body, "token"); |
||||
if (hasText(topLevel)) { |
||||
return topLevel.trim(); |
||||
} |
||||
throw validation("edayun token response has no access token" |
||||
+ " (looked for access_token, data.access_token and token)", body); |
||||
} |
||||
|
||||
/** |
||||
* 过期时刻(<b>估算</b>)。 |
||||
* |
||||
* <p>实测响应<b>没有有效期字段</b>,文档也说 token「目前设计上是永久的, |
||||
* 建议留个窗口刷新」。所以这里返回一个估算值,作用只是让 {@code TokenManager} |
||||
* 定期重登一次,避免真出问题时卡死。</p> |
||||
* |
||||
* <p>若将来响应里出现 {@code data.expires_in} 或 {@code data.expiry}, |
||||
* 优先用真值。</p> |
||||
*/ |
||||
private Instant expiresAtOf(EdayunTokenDtos.TokenResponse parsed) { |
||||
Instant now = Instant.now(clock); |
||||
EdayunTokenDtos.TokenResponse.TokenData data = parsed.data; |
||||
if (data != null && data.expiresIn != null && data.expiresIn > 0) { |
||||
return now.plusSeconds(data.expiresIn); |
||||
} |
||||
if (data != null && hasText(data.expiry)) { |
||||
Instant absolute = parseAbsolute(data.expiry.trim()); |
||||
if (absolute != null) { |
||||
return absolute; |
||||
} |
||||
} |
||||
// 文档:token 永久,建议定期刷新。按兜底周期重登一次。
|
||||
return now.plusSeconds(EdayunConstants.DEFAULT_TOKEN_TTL_SECONDS); |
||||
} |
||||
|
||||
/** 绝对时刻:兼容 ISO-8601 与毫秒 / 秒数字。 */ |
||||
private static Instant parseAbsolute(String raw) { |
||||
try { |
||||
return Instant.parse(raw); |
||||
} catch (RuntimeException ignored) { |
||||
// 继续试数字
|
||||
} |
||||
try { |
||||
long n = Long.parseLong(raw); |
||||
// 10 位按秒、13 位按毫秒
|
||||
return raw.length() <= 10 ? Instant.ofEpochSecond(n) : Instant.ofEpochMilli(n); |
||||
} catch (RuntimeException ignored) { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
private static ValidationException validation(String message, String body) { |
||||
return new ValidationException(WarehouseException.builder() |
||||
.message(message) |
||||
.operation(OP_FETCH) |
||||
.provider(EdayunConstants.ADAPTER_ID) |
||||
.rawResponse(truncate(body)) |
||||
.retryable(false)); |
||||
} |
||||
|
||||
private static boolean hasText(String v) { |
||||
return v != null && !v.trim().isEmpty(); |
||||
} |
||||
|
||||
/** 响应可能含 token 与密码,异常里只留很短一段。 */ |
||||
private static String truncate(String body) { |
||||
if (body == null) { |
||||
return null; |
||||
} |
||||
return body.length() <= 300 ? body : body.substring(0, 300) + "..."; |
||||
} |
||||
} |
||||
@ -0,0 +1,110 @@
@@ -0,0 +1,110 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云报文结构:查询交易明细({@code POST /webApi/accountFlow/list})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构。</p> |
||||
* |
||||
* <p><b>注意</b>:原文说明「同一个单号(ORD-发货单 / REV-收货单)的某个计费项 |
||||
* 有多条数据」——所以不能按单号去重,每条流水都是独立的账目,靠 |
||||
* {@code serialNumber} 区分。</p> |
||||
*/ |
||||
public final class EdayunAccountFlowDtos { |
||||
|
||||
private EdayunAccountFlowDtos() { |
||||
} |
||||
|
||||
/** 查询请求。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ListFlowRequest { |
||||
|
||||
/** 业务单号;支持模糊匹配(文档不建议)。 */ |
||||
public String bizNo; |
||||
/** 服务类型,字典 {@code trading_service_type}。 */ |
||||
public Integer serviceType; |
||||
/** 计费项名称。 */ |
||||
public String billingName; |
||||
/** 计费项编码。 */ |
||||
public String billingCode; |
||||
/** 操作类型,字典 {@code account_operate_type}。 */ |
||||
public Integer operateType; |
||||
/** 账户类型,字典 {@code account_type}。 */ |
||||
public Integer accountType; |
||||
/** 流水号。 */ |
||||
public String serialNumber; |
||||
|
||||
/** |
||||
* 计费时间起点(毫秒)。 |
||||
* |
||||
* <p><b>约束</b>:没给业务单号时时间段必填,且区间不能超过 180 天。</p> |
||||
*/ |
||||
public Long beginBillingTime; |
||||
/** 计费时间终点(毫秒)。 */ |
||||
public Long endBillingTime; |
||||
|
||||
/** 页码,从 1 开始。<b>必填</b>。 */ |
||||
public Integer pageNum; |
||||
/** 每页条数,最大 200。<b>必填</b>。 */ |
||||
public Integer pageSize; |
||||
/** 费收类型:0 标准(默认)/ 1 非标准。 */ |
||||
public Integer expenseType; |
||||
/** 仓库 id 列表。 */ |
||||
public List<Integer> warehouseIdList; |
||||
} |
||||
|
||||
/** 查询响应。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ListFlowResponse { |
||||
|
||||
/** 总条数。 */ |
||||
public Long total; |
||||
public List<FlowRow> rows; |
||||
public Integer code; |
||||
public String msg; |
||||
public String traceId; |
||||
} |
||||
|
||||
/** 一条交易流水。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class FlowRow { |
||||
|
||||
/** 账户流水号;同一计费项的多条记录靠它区分。 */ |
||||
public String serialNumber; |
||||
/** 关联业务单号,如 {@code ORD25037232211}。 */ |
||||
public String relateBusinessCode; |
||||
/** 平台单号。 */ |
||||
public String poNumber; |
||||
/** 操作类型:0 扣费 / 1 充值 / 2 补扣 / 3 退费 / 4 返利 / 5 还款 / 6 调额。 */ |
||||
public Integer operateType; |
||||
/** 账户类型:0 预付款 / 1 固定信用 / 2 临时信用。 */ |
||||
public Integer accountType; |
||||
public Integer businessType; |
||||
public String billingName; |
||||
/** 计费项编码。 */ |
||||
public String billingCode; |
||||
/** 原币。 */ |
||||
public String originalCurrency; |
||||
/** 计费金额;<b>文档标为 string</b>,且可为负数。 */ |
||||
public String billingAmount; |
||||
/** 账户币种。 */ |
||||
public String accountCurrency; |
||||
/** 汇率。 */ |
||||
public Double exchangeRate; |
||||
/** 变动后账户余额。 */ |
||||
public Double accountBalance; |
||||
/** 计费时间(毫秒)。 */ |
||||
public Long billingTime; |
||||
/** 服务类型;文档示例出现 -1(全部)。 */ |
||||
public Integer serviceType; |
||||
/** 计费重量(克)。 */ |
||||
public Long billingWeightG; |
||||
public String serviceTypeName; |
||||
public String operateTypeName; |
||||
public String accountTypeName; |
||||
public String businessTypeName; |
||||
} |
||||
} |
||||
@ -0,0 +1,67 @@
@@ -0,0 +1,67 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
/** |
||||
* 易达云报文结构:取消相关的两个接口。 |
||||
* |
||||
* <ul> |
||||
* <li>{@code POST /webApi/order/v1/checkCancelStatus} —— 取消前校验,判断是否收费</li> |
||||
* <li>{@code POST /webApi/order/v1/cancelOrder} —— 执行取消</li> |
||||
* </ul> |
||||
* |
||||
* <p>两个接口请求体相同({@code orderNo} / {@code poNumber} 二选一), |
||||
* 但响应 {@code data} 类型不同:一个是状态字符串,一个是布尔。</p> |
||||
*/ |
||||
public final class EdayunCancelDtos { |
||||
|
||||
private EdayunCancelDtos() { |
||||
} |
||||
|
||||
/** |
||||
* 取消 / 校验的请求体。 |
||||
* |
||||
* <p>{@code orderNo}(仓侧 ORD 单号)优先级高于 {@code poNumber}。</p> |
||||
*/ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CancelRequest { |
||||
/** EDA 订单号(ORD 开头);优先级更高。 */ |
||||
public String orderNo; |
||||
/** 平台单号(客户单号)。 */ |
||||
public String poNumber; |
||||
} |
||||
|
||||
/** |
||||
* 取消前校验的响应。 |
||||
* |
||||
* <p>{@code data} 是状态字符串:</p> |
||||
* <table> |
||||
* <tr><th>值</th><th>含义</th></tr> |
||||
* <tr><td>Cancelled</td><td>已取消</td></tr> |
||||
* <tr><td>Published</td><td>可以直接取消(<b>不收费</b>)</td></tr> |
||||
* <tr><td>Shipment</td><td>可以取消(<b>收费</b>)</td></tr> |
||||
* <tr><td>InterceptProcessing</td><td>拦截取消中</td></tr> |
||||
* <tr><td>InterceptSuccess</td><td>拦截成功</td></tr> |
||||
* <tr><td>InterceptFailure</td><td>拦截失败(文档误写成两个 InterceptSuccess)</td></tr> |
||||
* <tr><td>UnableCancel</td><td>无法取消(状态不允许)</td></tr> |
||||
* </table> |
||||
*/ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CheckCancelResponse { |
||||
public Integer code; |
||||
public String msg; |
||||
/** 取消资格状态字符串。 */ |
||||
public String data; |
||||
public String traceId; |
||||
} |
||||
|
||||
/** 执行取消的响应。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CancelOrderResponse { |
||||
public Integer code; |
||||
public String msg; |
||||
/** true 取消成功,其他失败。 */ |
||||
public Boolean data; |
||||
public String traceId; |
||||
} |
||||
} |
||||
@ -0,0 +1,214 @@
@@ -0,0 +1,214 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云报文结构:创建出库单({@code POST /webApi/order/v1/createOrder})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构。</p> |
||||
* |
||||
* <p><b>幂等</b>:文档明确「取消重推订单请保证相同订单的平台单号(poNumber)跟之前的一样」, |
||||
* 所以 {@code poNumber} 是仓侧的幂等键。</p> |
||||
*/ |
||||
public final class EdayunCreateOrderDtos { |
||||
|
||||
private EdayunCreateOrderDtos() { |
||||
} |
||||
|
||||
/** 创建出库单请求。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CreateOrderRequest { |
||||
|
||||
/** 平台单号(客户单号),≤190。必填,也是仓侧幂等键。 */ |
||||
public String poNumber; |
||||
/** 订单金额。 */ |
||||
public Double orderCost; |
||||
/** 订单金额币种:USD / CNY / HKD。 */ |
||||
public String currency; |
||||
public String buyerId; |
||||
public String buyerAccountName; |
||||
/** eBay 订单 Transaction ID(订单层面)。 */ |
||||
public String ebayTransactionId; |
||||
|
||||
/** 仓库 id;不传走分仓规则。 */ |
||||
public String warehouseId; |
||||
/** 物流产品 id;不传走分物流规则。 */ |
||||
public Long carrierProductId; |
||||
/** 订单标签,逗号分隔,≤50 字符。 */ |
||||
public String orderTag; |
||||
/** 客户物流账号 id;面单获取方式是「客户物流账号」时必填。 */ |
||||
public Long customerLogisticsAccountId; |
||||
|
||||
/** 承运商编码;自有物流 + 客户上传面单时必填。 */ |
||||
public String carrierName; |
||||
/** 提货类型:1 平台安排车提货 / 2 仓库自交货;自有物流时用。 */ |
||||
public Integer pickUpType; |
||||
/** 跟踪号;自有物流时可传客户跟踪号,多个逗号分隔。 */ |
||||
public String trackingNo; |
||||
/** 面单文件 URL(完整可访问);自有物流时必传,多个逗号分隔。 */ |
||||
public String labels; |
||||
|
||||
/** 物流增值:{@code is_signature} 签收 / {@code is_insurance} 保价。 */ |
||||
public List<String> addService; |
||||
/** 是否 SFP 订单。 */ |
||||
public Boolean primeFlag; |
||||
public String remark; |
||||
|
||||
/** 销售平台名称:Amazon / eBay / Temu / TIKTOK 等。必填。 */ |
||||
public String channelName; |
||||
/** 最晚发货时间(毫秒时间戳)。 */ |
||||
public Long promiseShipTime; |
||||
/** 销售平台单号(亚马逊 buyshipping)。 */ |
||||
public String salesPlatformOrderNo; |
||||
/** 店铺 ID(亚马逊 buyshipping)。 */ |
||||
public String sellerId; |
||||
|
||||
/** 指令订单附件。 */ |
||||
public List<InstructionAttach> instructionOrderAttachFileList; |
||||
|
||||
/** 派送地址。必填。 */ |
||||
public OrderAddress orderAddressVO; |
||||
|
||||
/** 商品明细。必填。 */ |
||||
public List<ProductItem> productItemVOList; |
||||
|
||||
/** 订单层面的增值服务附件。 */ |
||||
public List<AddServiceAttachFile> addServiceAttachFiles; |
||||
|
||||
/** 打包数据(有「定制打包」增值服务时必传)。 */ |
||||
public List<MeteringResult> meteringResultList; |
||||
|
||||
/** 卡车约车信息。 */ |
||||
public TruckAppointment truckAppointment; |
||||
|
||||
/** 指令订单附件。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class InstructionAttach { |
||||
/** 如 {@code package}。 */ |
||||
public String fileType; |
||||
public String filePath; |
||||
} |
||||
|
||||
/** 派送地址。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class OrderAddress { |
||||
public String buyerName; |
||||
public String buyerPhone; |
||||
public String companyName; |
||||
public String zipCode; |
||||
/** 国家二字码,如 US。 */ |
||||
public String destCountryName; |
||||
/** 省 / 州全称,如 California。 */ |
||||
public String destProvinceName; |
||||
public String destCity; |
||||
public String destDistrict; |
||||
public String destSubDistrict; |
||||
public String destFirstAddress; |
||||
public String destSecondAddress; |
||||
public String email; |
||||
public String houseNumber; |
||||
public String remark; |
||||
} |
||||
|
||||
/** 商品行。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ProductItem { |
||||
public String productSku; |
||||
public Integer quantity; |
||||
public Double unitPrice; |
||||
public String currencyCode; |
||||
/** eBay 商品 id(商品层面)。 */ |
||||
public String ebayItemId; |
||||
/** 平台商品 id(亚马逊 buyshipping)。 */ |
||||
public String platformItemId; |
||||
/** 商品层面的增值服务。 */ |
||||
public List<ValueAddedService> valueAddedServiceVOList; |
||||
} |
||||
|
||||
/** 商品层面的增值服务。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ValueAddedService { |
||||
/** 增值服务类型码。 */ |
||||
public Integer type; |
||||
public String fileUrl; |
||||
/** 是否覆盖原面单 0 否 / 1 是。 */ |
||||
public Integer isCoverOldLabel; |
||||
public String customizedInstructions; |
||||
} |
||||
|
||||
/** 订单层面的增值服务附件。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class AddServiceAttachFile { |
||||
public Integer objectType; |
||||
public Attribute attributeDTO; |
||||
|
||||
/** 附件属性。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class Attribute { |
||||
public Integer boxPasteQuantity; |
||||
public List<String> fileUrl; |
||||
public Integer isCoverOldLabel; |
||||
public String customizedInstructions; |
||||
} |
||||
} |
||||
|
||||
/** 打包数据。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class MeteringResult { |
||||
public String boxNo; |
||||
public String materialsId; |
||||
public String packingCode; |
||||
public String packingName; |
||||
public Integer packingType; |
||||
public Integer packingMode; |
||||
public List<MeteringSku> skuList; |
||||
} |
||||
|
||||
/** 打包内的 SKU。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class MeteringSku { |
||||
public String skuCode; |
||||
public String barcode; |
||||
public Integer quantity; |
||||
} |
||||
|
||||
/** 卡车约车。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class TruckAppointment { |
||||
public List<Bol> bolList; |
||||
} |
||||
|
||||
/** BOL。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class Bol { |
||||
public String bolCode; |
||||
public String bolFileUrl; |
||||
public String pickupNum; |
||||
public String pickupTime; |
||||
public String truckCompany; |
||||
} |
||||
} |
||||
|
||||
/** 创建出库单响应。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CreateOrderResponse { |
||||
|
||||
/** 200 成功,其他失败。 */ |
||||
public Integer code; |
||||
public String msg; |
||||
public OrderData data; |
||||
/** 接口响应的唯一 id,排查用。 */ |
||||
public String traceId; |
||||
|
||||
/** 成功时的订单信息。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class OrderData { |
||||
/** 仓侧订单号。 */ |
||||
public String orderNo; |
||||
/** 平台单号(回显请求里的 poNumber)。 */ |
||||
public String poNumber; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,194 @@
@@ -0,0 +1,194 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
import com.fasterxml.jackson.annotation.JsonProperty; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云报文结构:创建产品({@code POST /webApi/skuInfo/v1/createProduct})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构; |
||||
* 与其它接口共用的结构各自复制一份,避免跨接口耦合。</p> |
||||
* |
||||
* <p>字段名是<b>驼峰</b>(与 token 接口的下划线风格不同),照文档原样保留。</p> |
||||
*/ |
||||
public final class EdayunCreateProductDtos { |
||||
|
||||
private EdayunCreateProductDtos() { |
||||
} |
||||
|
||||
/** 创建产品请求。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CreateProductRequest { |
||||
|
||||
/** SKU 编码,长度 ≤32。必填。 */ |
||||
public String skuCode; |
||||
/** 外部条码 1,≤50。 */ |
||||
public String extraBarcode1; |
||||
/** 外部条码 2,≤50。 */ |
||||
public String extraBarcode2; |
||||
/** 外部条码 3,≤50。 */ |
||||
public String extraBarcode3; |
||||
/** SKU 中文名,≤150。必填。 */ |
||||
public String skuName; |
||||
/** SKU 英文名,≤150。必填。 */ |
||||
public String skuNameEn; |
||||
/** 是否品牌:0 是 / 1 否。必填。 */ |
||||
public Integer brandFlag; |
||||
public String brandName; |
||||
/** 销售链接,≤500。 */ |
||||
public String skuUrl; |
||||
/** 用途,≤50。必填(需写清使用场景 / 原理)。 */ |
||||
public String useTo; |
||||
/** 材质,≤50。必填(需具体,不要笼统写「金属」)。 */ |
||||
public String materialQuality; |
||||
public String specificationAttribute; |
||||
|
||||
/** 是否带电:0 带电 / 1 不带电。必填。 */ |
||||
public Integer electricFlag; |
||||
/** 电池类型,字典 sku_electric_type:0 锂电子 / 1 锂金属 / 2 非锂。带电必填。 */ |
||||
public String electricType; |
||||
/** 电池包装,字典 sku_electric_package:0 纯电 / 1 内置 / 2 外置。带电必填。 */ |
||||
public String electricPackage; |
||||
/** 电池功率(W);带电必填,>100W 还要 unNumber。 */ |
||||
public String electricPower; |
||||
/** UN 编码;带电且功率 >100W 必填。 */ |
||||
public String unNumber; |
||||
/** 电池文件地址。 */ |
||||
public String electricUrl; |
||||
|
||||
/** 产品重量 kg,[0.001, 1000]。必填。 */ |
||||
public Double weight; |
||||
/** 长 cm,[0.5, 10000]。必填。 */ |
||||
public Double length; |
||||
public Double width; |
||||
public Double height; |
||||
/** 是否自带物流包装:0 是 / 1 否。必填。 */ |
||||
public Integer logisticsPackagingType; |
||||
|
||||
/** 是否包材。必填。 */ |
||||
public Boolean pmFlag; |
||||
/** 包材长 cm,[0.5, 10000];是包材时必填。 */ |
||||
public Double pmLength; |
||||
public Double pmWidth; |
||||
public Double pmHeight; |
||||
|
||||
/** 批次管理:0 否 / 1 是。需单独申请权限。 */ |
||||
public Integer batchManagementEnabled; |
||||
/** 存储条件:0 常温 / 2 冷藏 / 3 冷冻 / 4 恒温。 */ |
||||
public Integer stockEnvironment; |
||||
|
||||
public String firstCategory; |
||||
public String secondaryCategory; |
||||
public String tertiaryCategory; |
||||
public String quaternaryCategory; |
||||
|
||||
/** 是否含钢铁铝:0 否 / 1 是;为 1 时三个含量至少一项 >0。 */ |
||||
public Integer isMetalMaterial; |
||||
/** 钢含量 0–100。 */ |
||||
public Double steelContent; |
||||
/** 铁含量 0–100;文档标为 string。 */ |
||||
public String ironContent; |
||||
/** 铝含量 0–100;文档标为 string。 */ |
||||
public String aluminumContent; |
||||
|
||||
/** 序列号管理:0 否 / 1 是。 */ |
||||
public Integer collectSerialNumber; |
||||
/** 序列号示例图;序列号管理时必填。 */ |
||||
public String snDiagram; |
||||
/** 序列号使用范围,逗号拼接:SN_REV / SN_ORD / SN_RMA。 */ |
||||
public String snUseScopes; |
||||
/** 序列号格式:1 纯数字 / 2 字母+数字 / 3 数字+字母。 */ |
||||
public Integer snFormat; |
||||
public Integer snTotalCharacter; |
||||
/** 格式为 1 时必填。 */ |
||||
public String snBeginDigit; |
||||
/** 格式为 2 时必填。 */ |
||||
public String snBeginLetter; |
||||
|
||||
public String remark; |
||||
/** 是否组合产品:0 否 / 1 是。 */ |
||||
public Integer skuType; |
||||
/** 组合产品明细;是组合产品时必填。 */ |
||||
public List<CombinationItem> skuCombinationRelationList; |
||||
public List<Certificate> skuCertificate; |
||||
public List<Picture> picList; |
||||
|
||||
/** |
||||
* 申报信息。<b>必填</b>:一个 SKU 至少需要一条出口 + 一条进口。 |
||||
*/ |
||||
public List<Declaration> declarationInfoList; |
||||
|
||||
/** 批次信息。 */ |
||||
public BatchInfo batchInfo; |
||||
|
||||
/** 组合产品明细行。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CombinationItem { |
||||
public String skuCode; |
||||
public String skuQuery; |
||||
} |
||||
|
||||
/** 证书。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class Certificate { |
||||
public String country; |
||||
public String certificateType; |
||||
public String certificateNo; |
||||
public String certificateExplain; |
||||
/** 文档示例是毫秒时间戳。 */ |
||||
public Long certificateDate; |
||||
public String certificateUrl; |
||||
} |
||||
|
||||
/** 图片。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class Picture { |
||||
public String picUrl; |
||||
} |
||||
|
||||
/** 申报信息(出口 / 进口各一条)。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class Declaration { |
||||
/** 0 出口 / 1 进口(文档未明确取值含义,按示例传 0)。 */ |
||||
public Integer declarationType; |
||||
public String country; |
||||
public Double declaredPrice; |
||||
public String currencyType; |
||||
public Integer headStrokeType; |
||||
} |
||||
|
||||
/** 批次信息。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class BatchInfo { |
||||
/** 是否开启效期管理 0 否 / 1 是。 */ |
||||
public Integer expirationEnabled; |
||||
public Integer shelfLifeDays; |
||||
public Integer outboundThreshold; |
||||
public Integer warningDays; |
||||
public Integer inboundThreshold; |
||||
} |
||||
} |
||||
|
||||
/** 创建产品响应。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CreateProductResponse { |
||||
|
||||
/** 200 成功,其他失败。 */ |
||||
public Integer code; |
||||
public String msg; |
||||
public ProductData data; |
||||
|
||||
/** 成功时的数据。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ProductData { |
||||
@JsonProperty("skuId") |
||||
public String skuId; |
||||
@JsonProperty("skuCode") |
||||
public String skuCode; |
||||
@JsonProperty("barcode") |
||||
public String barcode; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,240 @@
@@ -0,0 +1,240 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云报文结构:查询出库单信息({@code POST /webApi/order/v1/getOrderInfo})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构。</p> |
||||
* |
||||
* <p>{@code orderNo} 与 {@code poNumber} 二选一必填。</p> |
||||
*/ |
||||
public final class EdayunGetOrderDtos { |
||||
|
||||
private EdayunGetOrderDtos() { |
||||
} |
||||
|
||||
/** 查询请求。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class GetOrderRequest { |
||||
/** EDA 订单号;与 {@link #poNumber} 二选一。 */ |
||||
public String orderNo; |
||||
/** 平台单号(客户单号);与 {@link #orderNo} 二选一。 */ |
||||
public String poNumber; |
||||
} |
||||
|
||||
/** 查询响应。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class GetOrderResponse { |
||||
public Integer code; |
||||
public String msg; |
||||
public OrderInfo data; |
||||
/** 响应 id,排查用。 */ |
||||
public String traceId; |
||||
} |
||||
|
||||
/** 订单信息。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class OrderInfo { |
||||
|
||||
/** EDA 订单号。 */ |
||||
public String orderNo; |
||||
/** 平台单号。 */ |
||||
public String poNumber; |
||||
/** |
||||
* 订单状态,字典 {@code oms_order_status}。 |
||||
* |
||||
* <p>ReadyToShip / Shipment / Cancelled / Shipped / Online / Delivered / Returns / |
||||
* VerifyNotPass / DistrError / NoCarrier / NoMapping / ShipmentError / LabelError / |
||||
* InterceptProcessing / InterceptFailure / InterceptSuccess / ManualReview / |
||||
* InvError / BillLate / BalanceNotEnough / LogisticsVerificationFailed / |
||||
* UnableRequestTrackingNumber / StockException / StockLack</p> |
||||
*/ |
||||
public String orderStatus; |
||||
/** 跟踪号回传状态:READY / UPLOADING / ERROR / COMPLETED。 */ |
||||
public String trackingNoStatus; |
||||
|
||||
public String warehouseId; |
||||
public String warehouseName; |
||||
public String warehouseCode; |
||||
public String carrierProductName; |
||||
public String carrierProductId; |
||||
public String channelAccountName; |
||||
public String channelAccountId; |
||||
/** 发货物流:0 海外仓物流 / 1 自选物流。 */ |
||||
public Integer carrierType; |
||||
public String carrierName; |
||||
public String carrierId; |
||||
/** 跟踪号;多包裹用英文逗号拼接。 */ |
||||
public String trackingNo; |
||||
/** 异常原因;状态异常时有值。 */ |
||||
public String errorMsg; |
||||
|
||||
public String currency; |
||||
public Double orderCost; |
||||
public Double estimatedCost; |
||||
public String channelName; |
||||
public String ebayTransactionId; |
||||
public String buyerId; |
||||
public String buyerAccountName; |
||||
|
||||
/** 创建时间(毫秒时间戳,文档标为 string)。 */ |
||||
public String createTime; |
||||
/** 最后修改时间(毫秒时间戳)。 */ |
||||
public String updateTime; |
||||
public String remark; |
||||
/** 发货方式:0 快递 / 1 卡车。 */ |
||||
public Integer deliveryType; |
||||
/** 物流增值:is_signature / is_insurance。 */ |
||||
public List<String> addService; |
||||
/** 出库后的实际总费用。 */ |
||||
public Double actualTotalFee; |
||||
public String actualTotalFeeCurrency; |
||||
public Long customerLogisticsAccountId; |
||||
/** 拦截成功时仓库是否已还货。 */ |
||||
public Boolean hasGoodsReturned; |
||||
|
||||
/** 最晚发货时间(毫秒)。 */ |
||||
public Long promiseShipTime; |
||||
/** 发货时间(毫秒)。 */ |
||||
public Long shippedTime; |
||||
/** 交货时间(毫秒)。 */ |
||||
public Long expressDeliveryTime; |
||||
|
||||
public String salesPlatformOrderNo; |
||||
public String sellerId; |
||||
/** 是否指令订单。 */ |
||||
public Integer isInstructionOrder; |
||||
|
||||
public List<InstructionAttach> instructionOrderAttachFileList; |
||||
public List<ProductItem> productItemVOList; |
||||
public List<AddServiceAttachFile> addServiceAttachFiles; |
||||
public OrderAddress orderAddressVO; |
||||
public OrderAttribute orderAttribute; |
||||
/** 包裹信息集合。 */ |
||||
public List<CarrierInfo> carrierInfoList; |
||||
public List<OrderTag> orderTagList; |
||||
|
||||
/** 指令订单附件。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class InstructionAttach { |
||||
public String fileType; |
||||
public String filePath; |
||||
} |
||||
|
||||
/** 商品行。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ProductItem { |
||||
public String orderNo; |
||||
public String productSku; |
||||
public String barcode; |
||||
public String productCnName; |
||||
public String productName; |
||||
public Integer quantity; |
||||
public Double unitPrice; |
||||
public String ebayItemId; |
||||
public String ebayTransactionId; |
||||
public Double length; |
||||
public Double width; |
||||
public Double height; |
||||
/** 文档标为 string。 */ |
||||
public String weight; |
||||
public String attachment; |
||||
public String remark; |
||||
/** 采集到的序列号。 */ |
||||
public List<String> snCodeList; |
||||
public String platformItemId; |
||||
public List<ValueAddedService> valueAddedServiceVOList; |
||||
} |
||||
|
||||
/** 商品层面的增值服务。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ValueAddedService { |
||||
public Integer type; |
||||
public String fileUrl; |
||||
/** 文档标为 string。 */ |
||||
public String isCoverOldLabel; |
||||
public String customizedInstructions; |
||||
} |
||||
|
||||
/** 订单层面的增值服务附件。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class AddServiceAttachFile { |
||||
/** 文档标为 string。 */ |
||||
public String objectType; |
||||
public Attribute attributeDTO; |
||||
|
||||
/** 附件属性。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class Attribute { |
||||
public Integer boxPasteQuantity; |
||||
public List<String> fileUrl; |
||||
public Integer isCoverOldLabel; |
||||
public String customizedInstructions; |
||||
} |
||||
} |
||||
|
||||
/** 收件地址。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class OrderAddress { |
||||
public String orderNo; |
||||
public String buyerName; |
||||
public String buyerPhone; |
||||
public String companyName; |
||||
public String zipCode; |
||||
/** 国家二字码。 */ |
||||
public String destCountry; |
||||
public String destCountryName; |
||||
/** 州二字码。 */ |
||||
public String destProvince; |
||||
/** 州全称。 */ |
||||
public String destProvinceName; |
||||
public String destCity; |
||||
public String destCityName; |
||||
public String destDistrict; |
||||
public String destSubDistrict; |
||||
public String destFirstAddress; |
||||
public String destSecondAddress; |
||||
public String email; |
||||
public String houseNumber; |
||||
public String remark; |
||||
} |
||||
|
||||
/** 订单属性。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class OrderAttribute { |
||||
public Integer signatureFlag; |
||||
public Integer insuranceFlag; |
||||
public Integer trackingNoFlag; |
||||
public Integer pickUpType; |
||||
public Boolean primeFlag; |
||||
} |
||||
|
||||
/** 包裹信息。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class CarrierInfo { |
||||
public String orderNo; |
||||
public Double lengthCm; |
||||
public Double widthCm; |
||||
public Double heightCm; |
||||
public Double weightG; |
||||
public String carrierId; |
||||
public String carrierName; |
||||
public String trackingNo; |
||||
/** 面单文件地址。 */ |
||||
public String fileUrl; |
||||
public String fileName; |
||||
/** 预计提货时间(毫秒)。 */ |
||||
public Long expPickupTimeSystem; |
||||
} |
||||
|
||||
/** 订单标签。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class OrderTag { |
||||
public String tagCode; |
||||
public String tagName; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,47 @@
@@ -0,0 +1,47 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
/** |
||||
* 易达云报文结构:查询出库单面单信息({@code POST /webApi/order/v1/getOrderLabel})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构。</p> |
||||
* |
||||
* <p>{@code orderNo} 与 {@code poNumber} 二选一必填。</p> |
||||
*/ |
||||
public final class EdayunGetOrderLabelDtos { |
||||
|
||||
private EdayunGetOrderLabelDtos() { |
||||
} |
||||
|
||||
/** 查询请求。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class GetLabelRequest { |
||||
/** EDA 订单号;与 {@link #poNumber} 二选一。 */ |
||||
public String orderNo; |
||||
/** 平台单号(客户单号);与 {@link #orderNo} 二选一。 */ |
||||
public String poNumber; |
||||
} |
||||
|
||||
/** 查询响应。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class GetLabelResponse { |
||||
public Integer code; |
||||
public String msg; |
||||
public LabelData data; |
||||
public String traceId; |
||||
} |
||||
|
||||
/** 面单信息。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class LabelData { |
||||
public String orderNo; |
||||
public String poNumber; |
||||
public String carrierName; |
||||
public String carrierId; |
||||
/** 跟踪号;多包裹用英文逗号拼接。 */ |
||||
public String trackingNo; |
||||
/** 面单文件 URL;多个用英文逗号拼接,与 {@link #trackingNo} 一一对应。 */ |
||||
public String labels; |
||||
} |
||||
} |
||||
@ -0,0 +1,151 @@
@@ -0,0 +1,151 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* 易达云报文结构:查询订单费用明细 |
||||
* ({@code POST /webApi/order/cost/v1/selectOrderCostInfoList})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构。</p> |
||||
* |
||||
* <p>与「交易明细」({@code accountFlow/list})的区别:那个是<b>账户流水</b> |
||||
* (充值 / 扣费 / 退费,带账户余额),这个是<b>按订单的费用拆分</b> |
||||
* (应收 / 折扣 / 实付,带计费重与分区)。</p> |
||||
*/ |
||||
public final class EdayunOrderCostDtos { |
||||
|
||||
private EdayunOrderCostDtos() { |
||||
} |
||||
|
||||
/** 查询请求。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class SelectOrderCostRequest { |
||||
|
||||
/** 页码,从 1 开始。必填。 */ |
||||
public Integer pageNum; |
||||
/** 每页条数,最大 200。必填。 */ |
||||
public Integer pageSize; |
||||
/** 物流产品 id。 */ |
||||
public Long carrierProductId; |
||||
|
||||
/** 单号类型:0 订单号 / 1 平台单号 / 2 追踪号。 */ |
||||
public Integer type; |
||||
/** 订单号 / 平台单号 / 追踪号;配合 {@link #type}。 */ |
||||
public String orderNo; |
||||
/** 仓库 id。 */ |
||||
public String warehouseId; |
||||
/** 国家二字码。 */ |
||||
public String countryCode; |
||||
/** SKU。 */ |
||||
public String skuCode; |
||||
|
||||
/** 计费时间开始(毫秒);<b>最大查询 3 个月</b>。 */ |
||||
public Long beginBillingTime; |
||||
/** 计费时间结束(毫秒)。 */ |
||||
public Long endBillingTime; |
||||
} |
||||
|
||||
/** 查询响应。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class SelectOrderCostResponse { |
||||
public Long total; |
||||
public List<OrderCostRow> rows; |
||||
public Integer code; |
||||
public String msg; |
||||
/** 文档标为 object,实际可能是字符串;保留 Object 避免解析失败。 */ |
||||
public Object traceId; |
||||
} |
||||
|
||||
/** 一条订单费用记录。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class OrderCostRow { |
||||
|
||||
public String customerCode; |
||||
/** 仓侧订单号。 */ |
||||
public String orderCode; |
||||
/** 销售平台。 */ |
||||
public String channelName; |
||||
public String channelAccountName; |
||||
/** 平台订单号。 */ |
||||
public String poNumber; |
||||
public String warehouseId; |
||||
public String warehouseName; |
||||
public String carrierProductId; |
||||
public String carrierProductName; |
||||
public String trackingNo; |
||||
|
||||
/** 订单发货时间(毫秒)。 */ |
||||
public Long beginOutboundTime; |
||||
/** 计费时间(毫秒)。 */ |
||||
public Long billingTime; |
||||
/** 创建时间(毫秒)。 */ |
||||
public Long createTime; |
||||
|
||||
public String buyerName; |
||||
public String buyerPhone; |
||||
public String email; |
||||
public String destCountry; |
||||
public String destProvince; |
||||
public String zipCode; |
||||
|
||||
/** 包裹信息,格式 {@code 长*宽*高*重}。 */ |
||||
public String outboundParcel; |
||||
/** SKU 和数量,格式 {@code sku*数量}。 */ |
||||
public String productSkuNumber; |
||||
/** 燃油附加费费率。 */ |
||||
public Double fuelfee; |
||||
|
||||
/** 运费计费重;文档标为 string。 */ |
||||
public String freightBillingWeight; |
||||
/** 运费计费重单位,如 {@code g}。 */ |
||||
public String freightUnitType; |
||||
/** 出库处理费计费重。 */ |
||||
public String processBillingWeight; |
||||
/** 出库处理费计费重单位,如 {@code kg}。 */ |
||||
public String processUnitType; |
||||
|
||||
/** 计费分区。 */ |
||||
public String billingZone; |
||||
/** 是否偏远地区:0 否 / 1 是。 */ |
||||
public Integer isFaraway; |
||||
|
||||
/** 计费详情。 */ |
||||
public List<ChargeDetail> chargeDetails; |
||||
} |
||||
|
||||
/** 计费详情:一个报价单元(可能含多条费用明细)。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class ChargeDetail { |
||||
|
||||
/** 应收金额。 */ |
||||
public Double amountReceivable; |
||||
/** 报价币种。 */ |
||||
public String quotationCurrency; |
||||
/** 折扣金额。 */ |
||||
public Double discountPrice; |
||||
/** 实付金额。 */ |
||||
public Double realPayPrice; |
||||
/** 结算币种。 */ |
||||
public String currencyCode; |
||||
|
||||
/** 费用明细(逐计费项)。 */ |
||||
public List<FeeDetail> feeDetails; |
||||
} |
||||
|
||||
/** 单条计费项。 */ |
||||
@JsonInclude(JsonInclude.Include.NON_NULL) |
||||
public static final class FeeDetail { |
||||
|
||||
/** 计费项 id。 */ |
||||
public String billingId; |
||||
/** 计费项名称,如「尾程-出库处理费」。 */ |
||||
public String billingName; |
||||
public Double amountReceivable; |
||||
public String quotationCurrency; |
||||
public Double discountPrice; |
||||
public Double realPayPrice; |
||||
public String currencyCode; |
||||
} |
||||
} |
||||
@ -0,0 +1,91 @@
@@ -0,0 +1,91 @@
|
||||
package common.ecommerce.edayun.dto; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty; |
||||
|
||||
/** |
||||
* 易达云报文结构:获取 token({@code POST /oauth/token})。 |
||||
* |
||||
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构; |
||||
* 与其它接口共用的结构各自复制一份,避免跨接口耦合。</p> |
||||
*/ |
||||
public final class EdayunTokenDtos { |
||||
|
||||
private EdayunTokenDtos() { |
||||
} |
||||
|
||||
/** |
||||
* 获取 token 请求体。 |
||||
* |
||||
* <p>字段名是下划线风格,与易达云其它接口的驼峰不同,照文档原样保留。</p> |
||||
* |
||||
* <p><b>注意</b>:{@code client_id} / {@code client_secret} 是<b>易达云 OMS 系统的 |
||||
* 授权账号</b>,不是 appKey / appSecret。appKey 走请求头。</p> |
||||
*/ |
||||
public static final class TokenRequest { |
||||
|
||||
/** 用户名(oms 系统授权)。 */ |
||||
@JsonProperty("client_id") |
||||
public String clientId; |
||||
/** 密码(oms 系统授权)。 */ |
||||
@JsonProperty("client_secret") |
||||
public String clientSecret; |
||||
} |
||||
|
||||
/** |
||||
* 获取 token 响应。 |
||||
* |
||||
* <p><b>实测(2026-11-12,PR 环境)</b>:响应是<b>扁平结构</b>,没有 {@code code} |
||||
* 也没有 {@code data} 包裹:</p> |
||||
* <pre> |
||||
* {"access_token":"0dabff46-...","token_type":"bearer","scope":"server"} |
||||
* </pre> |
||||
* |
||||
* <p>token 是<b>永久</b>的(文档原话「目前设计上是永久的,建议留个窗口刷新」), |
||||
* 响应里<b>没有有效期字段</b>,所以过期时刻只能按兜底值估算。</p> |
||||
* |
||||
* <p>{@code data} 保留为兼容分支:万一生产环境走了网关包装也能解析。</p> |
||||
*/ |
||||
public static final class TokenResponse { |
||||
|
||||
/** 业务码;实测该接口不返回,仅在网关包装的场景出现。 */ |
||||
public Integer code; |
||||
public String message; |
||||
|
||||
/** 实测的顶层字段:access token。 */ |
||||
@JsonProperty("access_token") |
||||
public String accessToken; |
||||
/** |
||||
* 实测的顶层字段:{@code bearer}(小写)。 |
||||
* |
||||
* <p>{@code AccessToken} 的默认值是 {@code Bearer}(首字母大写);业务请求里 |
||||
* 易达云用的是独立的 {@code token} 头而不是 {@code Authorization} 头, |
||||
* 所以这个类型值目前不参与签名,原样保留即可。</p> |
||||
*/ |
||||
@JsonProperty("token_type") |
||||
public String tokenType; |
||||
/** 实测的顶层字段:scope,如 {@code server}。 */ |
||||
public String scope; |
||||
/** 刷新令牌;该接口不返回。 */ |
||||
@JsonProperty("refresh_token") |
||||
public String refreshToken; |
||||
|
||||
/** 兼容分支:网关把结果包一层 data 时使用。 */ |
||||
public TokenData data; |
||||
|
||||
/** token 载荷。 */ |
||||
public static final class TokenData { |
||||
/** access token。 */ |
||||
@JsonProperty("access_token") |
||||
public String accessToken; |
||||
/** 有效期(秒)。 */ |
||||
@JsonProperty("expires_in") |
||||
public Long expiresIn; |
||||
/** 绝对过期时刻;单位与格式待确认。 */ |
||||
@JsonProperty("expiry") |
||||
public String expiry; |
||||
/** 刷新令牌;易达云是否提供待确认。 */ |
||||
@JsonProperty("refresh_token") |
||||
public String refreshToken; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,84 @@
@@ -0,0 +1,84 @@
|
||||
package common.ecommerce.edayun.enums; |
||||
|
||||
import common.ecommerce.warehouse.enums.CancelEligibility; |
||||
|
||||
/** |
||||
* 易达云取消资格({@code checkCancelStatus} 的 {@code data})。 |
||||
* |
||||
* <p>文档口径:</p> |
||||
* <ul> |
||||
* <li>{@code Published} —— 可以直接取消,<b>不收费</b></li> |
||||
* <li>{@code Shipment} —— 可以取消,<b>收费</b></li> |
||||
* <li>{@code UnableCancel} —— 无法取消(状态不允许)</li> |
||||
* <li>{@code Cancelled} —— 已取消(无需再取消)</li> |
||||
* <li>拦截类三态 —— 取消动作已在进行中或已完成</li> |
||||
* </ul> |
||||
* |
||||
* <p><b>注意文档笔误</b>:响应说明里 `InterceptSuccess` 出现了两次 |
||||
* (一次是「拦截取消成功」、一次是「拦截取消失败」)。这里按 |
||||
* {@code InterceptFailure} 处理失败——与订单状态字典的命名一致。</p> |
||||
*/ |
||||
public enum EdayunCancelStatus { |
||||
|
||||
/** 可以直接取消(不收费)。 */ |
||||
PUBLISHED("Published", CancelEligibility.FREE), |
||||
/** 可以取消(收费)。 */ |
||||
SHIPMENT("Shipment", CancelEligibility.CHARGED), |
||||
/** 已取消;再取消没有意义,按不可取消处理。 */ |
||||
CANCELLED("Cancelled", CancelEligibility.BLOCKED), |
||||
/** 拦截取消中。 */ |
||||
INTERCEPT_PROCESSING("InterceptProcessing", CancelEligibility.BLOCKED), |
||||
/** 拦截取消成功;同「已取消」。 */ |
||||
INTERCEPT_SUCCESS("InterceptSuccess", CancelEligibility.BLOCKED), |
||||
/** 拦截取消失败(文档误写成两个 InterceptSuccess)。 */ |
||||
INTERCEPT_FAILURE("InterceptFailure", CancelEligibility.BLOCKED), |
||||
/** 无法取消(订单状态不允许)。 */ |
||||
UNABLE_CANCEL("UnableCancel", CancelEligibility.BLOCKED), |
||||
/** 无法识别。 */ |
||||
UNKNOWN(null, CancelEligibility.BLOCKED); |
||||
|
||||
private final String rawValue; |
||||
private final CancelEligibility core; |
||||
|
||||
EdayunCancelStatus(String rawValue, CancelEligibility core) { |
||||
this.rawValue = rawValue; |
||||
this.core = core; |
||||
} |
||||
|
||||
/** 易达云原值;null 表示无法识别。 */ |
||||
public String rawValue() { |
||||
return rawValue; |
||||
} |
||||
|
||||
/** 对应的底层资格。 */ |
||||
public CancelEligibility toCore() { |
||||
return core; |
||||
} |
||||
|
||||
/** |
||||
* 易达云原值 → 平台枚举。 |
||||
* |
||||
* <p><b>未知一律归 BLOCKED</b>:取消是有代价的操作(可能收费、且不可逆), |
||||
* 认不出时宁可拒绝也不能贸然放行。</p> |
||||
*/ |
||||
public static EdayunCancelStatus of(String rawStatus) { |
||||
if (rawStatus == null) { |
||||
return UNKNOWN; |
||||
} |
||||
String s = rawStatus.trim(); |
||||
if (s.isEmpty()) { |
||||
return UNKNOWN; |
||||
} |
||||
for (EdayunCancelStatus v : values()) { |
||||
if (v.rawValue != null && s.equalsIgnoreCase(v.rawValue)) { |
||||
return v; |
||||
} |
||||
} |
||||
return UNKNOWN; |
||||
} |
||||
|
||||
/** 易达云原值 → 底层资格。 */ |
||||
public static CancelEligibility toCore(String rawStatus) { |
||||
return of(rawStatus).toCore(); |
||||
} |
||||
} |
||||
@ -0,0 +1,25 @@
@@ -0,0 +1,25 @@
|
||||
package common.ecommerce.edayun.enums; |
||||
|
||||
/** |
||||
* 易达云申报类型({@code declarationInfoList[].declarationType})。 |
||||
* |
||||
* <p>文档要求一个 SKU 至少一条出口 + 一条进口,但没说码值。 |
||||
* 示例里只出现 {@code 0},<b>按 0 出口、1 进口推断</b>——待联调确认。</p> |
||||
*/ |
||||
public enum EdayunDeclarationType { |
||||
|
||||
/** 出口申报。 */ |
||||
EXPORT(0), |
||||
/** 进口申报。 */ |
||||
IMPORT(1); |
||||
|
||||
private final int code; |
||||
|
||||
EdayunDeclarationType(int code) { |
||||
this.code = code; |
||||
} |
||||
|
||||
public int code() { |
||||
return code; |
||||
} |
||||
} |
||||
@ -0,0 +1,141 @@
@@ -0,0 +1,141 @@
|
||||
package common.ecommerce.edayun.enums; |
||||
|
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
|
||||
import java.util.Arrays; |
||||
import java.util.HashSet; |
||||
import java.util.Set; |
||||
|
||||
/** |
||||
* 易达云出库单状态({@code orderStatus},字典 {@code oms_order_status})。 |
||||
* |
||||
* <p>文档给了 24 个取值,按「宿主是否需要区分」折叠到统一的 {@link OutboundStatus}:</p> |
||||
* |
||||
* <table> |
||||
* <tr><th>易达云</th><th>含义</th><th>统一状态</th></tr> |
||||
* <tr><td>ReadyToShip</td><td>待发货</td><td>SUBMITTED</td></tr> |
||||
* <tr><td>Shipment</td><td>发货中</td><td>PICKING</td></tr> |
||||
* <tr><td>Shipped</td><td>已出库</td><td>SHIPPED</td></tr> |
||||
* <tr><td>Online</td><td>已上网</td><td>SHIPPED</td></tr> |
||||
* <tr><td>Delivered</td><td>已妥投</td><td>SHIPPED</td></tr> |
||||
* <tr><td>Returns</td><td>退件</td><td>SHIPPED</td></tr> |
||||
* <tr><td>Cancelled</td><td>已取消</td><td>CANCELLED</td></tr> |
||||
* <tr><td>InterceptSuccess</td><td>拦截成功</td><td>CANCELLED</td></tr> |
||||
* <tr><td>其余异常类</td><td>分仓失败 / 缺货 / 面单异常等</td><td>EXCEPTION</td></tr> |
||||
* </table> |
||||
* |
||||
* <p><b>为什么异常类都归 EXCEPTION</b>:宿主对它们的处理都是「人工介入」, |
||||
* 具体原因在 {@code errorMsg} 与 {@code rawStatus} 里,不需要 19 个细分状态。 |
||||
* 若将来业务要按原因分流,再加枚举值不迟。</p> |
||||
*/ |
||||
public enum EdayunOrderStatus { |
||||
|
||||
/** 待发货。 */ |
||||
READY_TO_SHIP("ReadyToShip", OutboundStatus.SUBMITTED), |
||||
/** 发货中。 */ |
||||
SHIPMENT("Shipment", OutboundStatus.PICKING), |
||||
/** 已出库。 */ |
||||
SHIPPED("Shipped", OutboundStatus.SHIPPED), |
||||
/** 已上网。 */ |
||||
ONLINE("Online", OutboundStatus.SHIPPED), |
||||
/** 已妥投。 */ |
||||
DELIVERED("Delivered", OutboundStatus.SHIPPED), |
||||
/** 退件。 */ |
||||
RETURNS("Returns", OutboundStatus.SHIPPED), |
||||
/** 已取消。 */ |
||||
CANCELLED("Cancelled", OutboundStatus.CANCELLED), |
||||
/** 拦截成功。 */ |
||||
INTERCEPT_SUCCESS("InterceptSuccess", OutboundStatus.CANCELLED), |
||||
/** 拦截中。 */ |
||||
INTERCEPT_PROCESSING("InterceptProcessing", OutboundStatus.EXCEPTION), |
||||
/** 拦截失败。 */ |
||||
INTERCEPT_FAILURE("InterceptFailure", OutboundStatus.EXCEPTION), |
||||
/** 信息异常。 */ |
||||
VERIFY_NOT_PASS("VerifyNotPass", OutboundStatus.EXCEPTION), |
||||
/** 分仓失败。 */ |
||||
DISTR_ERROR("DistrError", OutboundStatus.EXCEPTION), |
||||
/** 分物流失败。 */ |
||||
NO_CARRIER("NoCarrier", OutboundStatus.EXCEPTION), |
||||
/** 产品未关联。 */ |
||||
NO_MAPPING("NoMapping", OutboundStatus.EXCEPTION), |
||||
/** 推仓失败。 */ |
||||
SHIPMENT_ERROR("ShipmentError", OutboundStatus.EXCEPTION), |
||||
/** 面单异常。 */ |
||||
LABEL_ERROR("LabelError", OutboundStatus.EXCEPTION), |
||||
/** 人工审核。 */ |
||||
MANUAL_REVIEW("ManualReview", OutboundStatus.EXCEPTION), |
||||
/** 缺货。 */ |
||||
INV_ERROR("InvError", OutboundStatus.EXCEPTION), |
||||
/** 库存不足。 */ |
||||
STOCK_LACK("StockLack", OutboundStatus.EXCEPTION), |
||||
/** 库存异常。 */ |
||||
STOCK_EXCEPTION("StockException", OutboundStatus.EXCEPTION), |
||||
/** 账单逾期。 */ |
||||
BILL_LATE("BillLate", OutboundStatus.EXCEPTION), |
||||
/** 余额不足。 */ |
||||
BALANCE_NOT_ENOUGH("BalanceNotEnough", OutboundStatus.EXCEPTION), |
||||
/** 物流校验不通过。 */ |
||||
LOGISTICS_VERIFICATION_FAILED("LogisticsVerificationFailed", OutboundStatus.EXCEPTION), |
||||
/** 请求追踪号失败。 */ |
||||
UNABLE_REQUEST_TRACKING_NUMBER("UnableRequestTrackingNumber", OutboundStatus.EXCEPTION), |
||||
/** 无法识别。 */ |
||||
UNKNOWN(null, OutboundStatus.UNKNOWN); |
||||
|
||||
/** 已发货类(含退件)——文档定义。 */ |
||||
private static final Set<String> SHIPPED_SET = new HashSet<String>(Arrays.asList( |
||||
"Shipped", "Online", "Delivered", "Returns")); |
||||
|
||||
/** 已取消类(含拦截成功)——文档定义。 */ |
||||
private static final Set<String> CANCELLED_SET = new HashSet<String>(Arrays.asList( |
||||
"Cancelled", "InterceptSuccess")); |
||||
|
||||
private final String rawValue; |
||||
private final OutboundStatus core; |
||||
|
||||
EdayunOrderStatus(String rawValue, OutboundStatus core) { |
||||
this.rawValue = rawValue; |
||||
this.core = core; |
||||
} |
||||
|
||||
/** 易达云原值;null 表示无法识别。 */ |
||||
public String rawValue() { |
||||
return rawValue; |
||||
} |
||||
|
||||
/** 对应的底层状态。 */ |
||||
public OutboundStatus toCore() { |
||||
return core; |
||||
} |
||||
|
||||
/** 是否属于「已发货」(文档口径:Shipped / Online / Delivered / Returns)。 */ |
||||
public static boolean isShipped(String rawStatus) { |
||||
return rawStatus != null && SHIPPED_SET.contains(rawStatus.trim()); |
||||
} |
||||
|
||||
/** 是否属于「已取消」(文档口径:Cancelled / InterceptSuccess)。 */ |
||||
public static boolean isCancelled(String rawStatus) { |
||||
return rawStatus != null && CANCELLED_SET.contains(rawStatus.trim()); |
||||
} |
||||
|
||||
/** 易达云原值 → 平台枚举;<b>精确匹配</b>,未知归 UNKNOWN。 */ |
||||
public static EdayunOrderStatus of(String rawStatus) { |
||||
if (rawStatus == null) { |
||||
return UNKNOWN; |
||||
} |
||||
String s = rawStatus.trim(); |
||||
if (s.isEmpty()) { |
||||
return UNKNOWN; |
||||
} |
||||
for (EdayunOrderStatus v : values()) { |
||||
if (v.rawValue != null && s.equalsIgnoreCase(v.rawValue)) { |
||||
return v; |
||||
} |
||||
} |
||||
return UNKNOWN; |
||||
} |
||||
|
||||
/** 易达云原值 → 底层状态。 */ |
||||
public static OutboundStatus toCore(String rawStatus) { |
||||
return of(rawStatus).toCore(); |
||||
} |
||||
} |
||||
@ -0,0 +1,64 @@
@@ -0,0 +1,64 @@
|
||||
package common.ecommerce.edayun.enums; |
||||
|
||||
/** |
||||
* 易达云布尔标志的码值:<b>0 是 / 1 否</b>——与直觉相反。 |
||||
* |
||||
* <p>多处复用:{@code brandFlag} / {@code logisticsPackagingType} / |
||||
* {@code electricFlag} / {@code isMetalMaterial} 等都是这个口径。 |
||||
* 单独成枚举是为了让 {@link #codeOf(Boolean)} 成为唯一入口, |
||||
* 避免各处手写 {@code x ? 0 : 1} 时把方向写反。</p> |
||||
*/ |
||||
public enum EdayunYesNo { |
||||
|
||||
/** 是。 */ |
||||
YES(0, true), |
||||
/** 否。 */ |
||||
NO(1, false); |
||||
|
||||
private final int code; |
||||
private final boolean value; |
||||
|
||||
EdayunYesNo(int code, boolean value) { |
||||
this.code = code; |
||||
this.value = value; |
||||
} |
||||
|
||||
public int code() { |
||||
return code; |
||||
} |
||||
|
||||
public boolean value() { |
||||
return value; |
||||
} |
||||
|
||||
/** 业务布尔 → 易达云码;null 透传(由调用方决定是否必填)。 */ |
||||
public static Integer codeOf(Boolean value) { |
||||
if (value == null) { |
||||
return null; |
||||
} |
||||
return value ? YES.code : NO.code; |
||||
} |
||||
|
||||
/** 易达云码 → 业务布尔;未知码返回 null,不猜。 */ |
||||
public static Boolean valueOf(Integer code) { |
||||
if (code == null) { |
||||
return null; |
||||
} |
||||
if (code == YES.code) { |
||||
return Boolean.TRUE; |
||||
} |
||||
if (code == NO.code) { |
||||
return Boolean.FALSE; |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
/** |
||||
* 「有值即为是」的辅助:{@code nullableHasValue(true)} → 0(是)。 |
||||
* |
||||
* <p>给 {@code brandFlag} 这类「只要给了品牌信息就算有品牌」的字段用。</p> |
||||
*/ |
||||
public static Integer noOf(boolean hasValue) { |
||||
return hasValue ? YES.code : NO.code; |
||||
} |
||||
} |
||||
@ -0,0 +1,162 @@
@@ -0,0 +1,162 @@
|
||||
package common.ecommerce.edayun.http; |
||||
|
||||
import common.ecommerce.http.HttpRequest; |
||||
import common.ecommerce.http.JsonCodec; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.dto.EdayunTokenDtos; |
||||
|
||||
import java.net.URLEncoder; |
||||
import java.nio.charset.StandardCharsets; |
||||
import java.security.MessageDigest; |
||||
import java.util.LinkedHashMap; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* 构造易达云请求。 |
||||
* |
||||
* <p>鉴权分两段:</p> |
||||
* <ol> |
||||
* <li>先 {@code POST /oauth/token} 换 token(用 OMS 授权账号 client_id / client_secret)</li> |
||||
* <li>业务请求带 {@code Authorization: Bearer <token>} 与 {@code appKey} / {@code timestamp} / {@code sign}</li> |
||||
* </ol> |
||||
* |
||||
* <p>凭据映射(复用 {@link ChannelSecret}):</p> |
||||
* <table> |
||||
* <tr><th>易达云</th><th>ChannelSecret</th></tr> |
||||
* <tr><td>appKey(请求头)</td><td>{@link ChannelSecret#appKey()}</td></tr> |
||||
* <tr><td>appSecret(签名用)</td><td>{@link ChannelSecret#appSecret()}</td></tr> |
||||
* <tr><td>client_id</td><td>{@link ChannelSecret#clientId()}</td></tr> |
||||
* <tr><td>client_secret</td><td>{@link ChannelSecret#clientSecret()}</td></tr> |
||||
* </table> |
||||
*/ |
||||
public final class EdayunRequestFactory { |
||||
|
||||
private final JsonCodec json; |
||||
|
||||
public EdayunRequestFactory(JsonCodec json) { |
||||
this.json = json; |
||||
} |
||||
|
||||
/** |
||||
* 获取 token:{@code POST /oauth/token}。 |
||||
* |
||||
* <p>文档要求<b>不需要 header 参数</b>(除了 Content-Type)。</p> |
||||
* |
||||
* @param clientId 易达云 OMS 授权用户名 |
||||
* @param clientSecret 易达云 OMS 授权密码 |
||||
*/ |
||||
public HttpRequest token(String baseUrl, String clientId, String clientSecret, String operation) { |
||||
EdayunTokenDtos.TokenRequest body = new EdayunTokenDtos.TokenRequest(); |
||||
body.clientId = requireText(clientId, "edayun requires ChannelSecret.clientId()"); |
||||
body.clientSecret = requireText(clientSecret, "edayun requires ChannelSecret.clientSecret()"); |
||||
|
||||
return HttpRequest.builder() |
||||
.method("POST") |
||||
.url(join(baseUrl, EdayunConstants.PATH_TOKEN)) |
||||
.contentType(EdayunConstants.CONTENT_TYPE_JSON) |
||||
.body(json.toJson(body)) |
||||
.operation(operation) |
||||
.build(); |
||||
} |
||||
|
||||
/** |
||||
* 业务请求:带 {@code Authorization: Bearer <token>} 与 appKey / timestamp / sign。 |
||||
* |
||||
* <p>{@code sign = MD5(body + "." + appSecret)},小写十六进制。 |
||||
* 测试环境传 {@code openApiAdminSecret} 可免签,但生产必须算。</p> |
||||
* |
||||
* @param token {@code /oauth/token} 拿到的 token |
||||
* @param appKey {@code ChannelSecret.appKey()} |
||||
* @param appSecret {@code ChannelSecret.appSecret()} |
||||
* @param timestamp 毫秒时间戳;5 分钟内有效 |
||||
* @param bodyJson 请求体(GET 时为空串) |
||||
*/ |
||||
public HttpRequest business(String baseUrl, String path, String method, |
||||
String token, String appKey, String appSecret, |
||||
long timestamp, String bodyJson, String operation) { |
||||
return buildBusiness(baseUrl, path, method, token, appKey, |
||||
sign(bodyJson, appSecret), timestamp, bodyJson, operation); |
||||
} |
||||
|
||||
private HttpRequest buildBusiness(String baseUrl, String path, String method, |
||||
String token, String appKey, String signValue, |
||||
long timestamp, String bodyJson, String operation) { |
||||
Map<String, String> headers = new LinkedHashMap<String, String>(); |
||||
headers.put(EdayunConstants.HEADER_AUTHORIZATION, |
||||
"Bearer " + requireText(token, "edayun requires a token")); |
||||
headers.put(EdayunConstants.HEADER_APP_KEY, requireText(appKey, |
||||
"edayun requires ChannelSecret.appKey()")); |
||||
headers.put(EdayunConstants.HEADER_TIMESTAMP, String.valueOf(timestamp)); |
||||
headers.put(EdayunConstants.HEADER_SIGN, signValue); |
||||
|
||||
HttpRequest.Builder builder = HttpRequest.builder() |
||||
.method(method) |
||||
.url(join(baseUrl, path)) |
||||
.headers(headers) |
||||
.operation(operation); |
||||
if (bodyJson != null && !bodyJson.isEmpty()) { |
||||
builder.contentType(EdayunConstants.CONTENT_TYPE_JSON).body(bodyJson); |
||||
} |
||||
return builder.build(); |
||||
} |
||||
|
||||
/** |
||||
* 业务请求(测试环境免签版本)。 |
||||
* |
||||
* <p>文档说明:测试环境可把 {@code openApiAdminSecret} 直接当 {@code sign} 传, |
||||
* 不必计算 MD5。生产环境请用带 {@code appSecret} 的重载。</p> |
||||
*/ |
||||
public HttpRequest businessUnsigned(String baseUrl, String path, String method, |
||||
String token, String appKey, String openApiAdminSecret, |
||||
long timestamp, String bodyJson, String operation) { |
||||
return buildBusiness(baseUrl, path, method, token, appKey, |
||||
requireText(openApiAdminSecret, "edayun requires openApiAdminSecret"), timestamp, |
||||
bodyJson, operation); |
||||
} |
||||
|
||||
/** |
||||
* 签名:{@code MD5(body + "." + appSecret)},小写十六进制。 |
||||
* |
||||
* <p>注意是 <b>body 原文</b>参与签名——所以业务方法要把「即将发出的那个字符串」 |
||||
* 传进来,不能传反序列化后再序列化的结果(字段顺序变了签名就对不上)。</p> |
||||
*/ |
||||
public static String sign(String bodyJson, String appSecret) { |
||||
String secret = requireText(appSecret, "edayun requires ChannelSecret.appSecret()"); |
||||
String raw = (bodyJson == null ? "" : bodyJson) + "." + secret; |
||||
try { |
||||
MessageDigest md = MessageDigest.getInstance("MD5"); |
||||
byte[] digest = md.digest(raw.getBytes(StandardCharsets.UTF_8)); |
||||
StringBuilder sb = new StringBuilder(digest.length * 2); |
||||
for (byte b : digest) { |
||||
sb.append(Character.forDigit((b >> 4) & 0xF, 16)); |
||||
sb.append(Character.forDigit(b & 0xF, 16)); |
||||
} |
||||
return sb.toString(); |
||||
} catch (java.security.NoSuchAlgorithmException e) { |
||||
throw new IllegalStateException("MD5 not available", e); |
||||
} |
||||
} |
||||
|
||||
private static String join(String baseUrl, String path) { |
||||
String base = requireText(baseUrl, "edayun requires an endpoint base url"); |
||||
return base.endsWith("/") ? base + (path.startsWith("/") ? path.substring(1) : path) |
||||
: base + (path.startsWith("/") ? path : "/" + path); |
||||
} |
||||
|
||||
private static String requireText(String value, String message) { |
||||
if (value == null || value.trim().isEmpty()) { |
||||
throw new IllegalArgumentException(message); |
||||
} |
||||
return value.trim(); |
||||
} |
||||
|
||||
/** 供将来带 query 参数的接口使用。 */ |
||||
static String encode(String v) { |
||||
try { |
||||
return URLEncoder.encode(v, "UTF-8"); |
||||
} catch (java.io.UnsupportedEncodingException e) { |
||||
throw new IllegalStateException(e); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,62 @@
@@ -0,0 +1,62 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.enums.EdayunCancelStatus; |
||||
import common.ecommerce.warehouse.enums.CancelEligibility; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
|
||||
/** |
||||
* 取消资格映射({@code checkCancelStatus} 的 {@code data})。 |
||||
* |
||||
* <p>核心原则:取消有代价(可能收费且不可逆),<b>认不出时归 BLOCKED</b>, |
||||
* 不贸然放行。</p> |
||||
*/ |
||||
class EdayunCancelStatusTest { |
||||
|
||||
/** 文档定义的两个「可取消」:Published 免费 / Shipment 收费。 */ |
||||
@Test |
||||
void cancelableStatuses() { |
||||
assertEquals(CancelEligibility.FREE, EdayunCancelStatus.toCore("Published")); |
||||
assertEquals(CancelEligibility.CHARGED, EdayunCancelStatus.toCore("Shipment")); |
||||
} |
||||
|
||||
/** 其余一律不可取消。 */ |
||||
@Test |
||||
void blockingStatuses() { |
||||
for (String s : new String[] {"Cancelled", "InterceptProcessing", "InterceptSuccess", |
||||
"InterceptFailure", "UnableCancel"}) { |
||||
assertEquals(CancelEligibility.BLOCKED, EdayunCancelStatus.toCore(s), s); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 未知状态必须归 BLOCKED,不能因为「不认识」就放行。 |
||||
* |
||||
* <p>反之若这里返回 FREE,宿主会在不确定的情况下发出取消请求—— |
||||
* 可能产生取消费,且取消不可逆。</p> |
||||
*/ |
||||
@Test |
||||
void unknownIsBlockedNotFree() { |
||||
assertEquals(CancelEligibility.BLOCKED, EdayunCancelStatus.toCore("SomeNewStatus")); |
||||
assertEquals(CancelEligibility.BLOCKED, EdayunCancelStatus.toCore(null)); |
||||
assertEquals(CancelEligibility.BLOCKED, EdayunCancelStatus.toCore("")); |
||||
assertEquals(CancelEligibility.BLOCKED, EdayunCancelStatus.toCore(" ")); |
||||
} |
||||
|
||||
/** 大小写不敏感,但仍是精确匹配。 */ |
||||
@Test |
||||
void caseInsensitiveExactMatch() { |
||||
assertEquals(CancelEligibility.FREE, EdayunCancelStatus.toCore("published")); |
||||
assertEquals(CancelEligibility.CHARGED, EdayunCancelStatus.toCore("SHIPMENT")); |
||||
// 子串不算:Published 之外的 xxPublishedxx 不应命中
|
||||
assertEquals(CancelEligibility.BLOCKED, EdayunCancelStatus.toCore("NotPublished")); |
||||
} |
||||
|
||||
/** 文档笔误:InterceptSuccess 出现了两次,失败按 InterceptFailure 处理。 */ |
||||
@Test |
||||
void interceptFailureIsRecognised() { |
||||
assertEquals(CancelEligibility.BLOCKED, EdayunCancelStatus.toCore("InterceptFailure")); |
||||
assertEquals("InterceptFailure", EdayunCancelStatus.INTERCEPT_FAILURE.rawValue()); |
||||
} |
||||
} |
||||
@ -0,0 +1,183 @@
@@ -0,0 +1,183 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.dto.EdayunCancelDtos; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.warehouse.model.CancelCommand; |
||||
import common.ecommerce.warehouse.model.CancelResult; |
||||
import common.ecommerce.warehouse.model.OutboundRef; |
||||
import common.ecommerce.warehouse.enums.CancelEligibility; |
||||
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
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.assertFalse; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 取消前校验与取消订单的请求构造与响应映射。 |
||||
* |
||||
* <p>不实际发请求——用 RecordingTransport 打桩。</p> |
||||
*/ |
||||
class EdayunCancelTest { |
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-12T00:00:00Z"), ZoneOffset.UTC); |
||||
private static final String BASE = "https://api.edayun.test"; |
||||
|
||||
private static WarehouseContext ctx() { |
||||
return WarehouseContext.of("EDY-WH-1", WarehouseProvider.EDAYUN, "2", |
||||
WarehouseConnection.of(BASE, |
||||
ChannelSecret.builder() |
||||
.appKey("ak").appSecret("sk") |
||||
.clientId("u").clientSecret("p").build()), |
||||
"req-1", CLOCK); |
||||
} |
||||
|
||||
/** 每次业务调用前会先取 token,所以桩里要同时路由 /oauth/token。 */ |
||||
private static EdayunAdapter adapter(RecordingTransport transport) { |
||||
return new EdayunAdapter(transport, new JacksonJsonCodec()); |
||||
} |
||||
|
||||
/** 带 token 路由的传输层。 */ |
||||
private static RecordingTransport transport() { |
||||
return RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"access_token\":\"T1\",\"token_type\":\"bearer\"}")); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 校验
|
||||
|
||||
@Test |
||||
void checkCancelMapsPublishedToFree() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CHECK_CANCEL, req -> Responses.ok( |
||||
"{\"code\":200,\"msg\":\"ok\",\"data\":\"Published\",\"traceId\":\"t\"}")); |
||||
|
||||
CancelEligibility eligibility = adapter(transport) |
||||
.checkCancel(ctx(), OutboundRef.ofRequestNo("P-20261112")); |
||||
|
||||
assertEquals(CancelEligibility.FREE, eligibility); |
||||
String body = transport.lastDataRequest().body(); |
||||
assertTrue(body.contains("\"poNumber\":\"P-20261112\""), body); |
||||
} |
||||
|
||||
@Test |
||||
void checkCancelMapsShipmentToCharged() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CHECK_CANCEL, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":\"Shipment\"}")); |
||||
|
||||
assertEquals(CancelEligibility.CHARGED, adapter(transport) |
||||
.checkCancel(ctx(), OutboundRef.ofRequestNo("P-1"))); |
||||
} |
||||
|
||||
@Test |
||||
void checkCancelMapsUnableCancelToBlocked() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CHECK_CANCEL, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":\"UnableCancel\"}")); |
||||
|
||||
assertEquals(CancelEligibility.BLOCKED, adapter(transport) |
||||
.checkCancel(ctx(), OutboundRef.ofRequestNo("P-1"))); |
||||
} |
||||
|
||||
/** 按仓单号引用时走 orderNo(文档说优先级更高)。 */ |
||||
@Test |
||||
void checkCancelSendsOrderNoWhenGivenProviderOrderId() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CHECK_CANCEL, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":\"Published\"}")); |
||||
|
||||
adapter(transport).checkCancel(ctx(), OutboundRef.ofProviderOrderId("ORD-9")); |
||||
|
||||
String body = transport.lastDataRequest().body(); |
||||
assertTrue(body.contains("\"orderNo\":\"ORD-9\""), body); |
||||
org.junit.jupiter.api.Assertions.assertFalse(body.contains("poNumber"), body); |
||||
} |
||||
|
||||
/** OutboundRef 本身要求两个单号至少给一个。 */ |
||||
@Test |
||||
void checkCancelRejectsWithoutAnyNumber() { |
||||
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, |
||||
() -> OutboundRef.ofRequestNo("")); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 取消
|
||||
|
||||
@Test |
||||
void cancelSucceeds() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CANCEL, req -> Responses.ok( |
||||
"{\"code\":200,\"msg\":\"ok\",\"data\":true}")); |
||||
|
||||
CancelResult result = adapter(transport).cancel(ctx(), |
||||
CancelCommand.builder().outboundRequestNo("P-1").build()); |
||||
|
||||
assertTrue(result.cancelled()); |
||||
assertEquals(CancelEligibility.FREE, result.eligibility()); |
||||
assertEquals("ok", result.rawStatus()); |
||||
} |
||||
|
||||
/** data=false 表示仓侧拒绝,不是异常;msg 带原因。 */ |
||||
@Test |
||||
void cancelRejectedByWarehouse() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CANCEL, req -> Responses.ok( |
||||
"{\"code\":200,\"msg\":\"订单已出库\",\"data\":false}")); |
||||
|
||||
CancelResult result = adapter(transport).cancel(ctx(), |
||||
CancelCommand.builder().outboundRequestNo("P-1").build()); |
||||
|
||||
assertFalse(result.cancelled()); |
||||
assertEquals(CancelEligibility.BLOCKED, result.eligibility()); |
||||
assertEquals("订单已出库", result.rawStatus()); |
||||
} |
||||
|
||||
/** 业务码非 200 要抛,而不是当成「取消失败」。 */ |
||||
@Test |
||||
void nonSuccessBusinessCodeThrows() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CANCEL, req -> Responses.ok( |
||||
"{\"code\":500,\"msg\":\"参数错误\"}")); |
||||
|
||||
org.junit.jupiter.api.Assertions.assertThrows(RuntimeException.class, |
||||
() -> adapter(transport).cancel(ctx(), |
||||
CancelCommand.builder().outboundRequestNo("P-1").build())); |
||||
} |
||||
|
||||
/** 请求体字段是 orderNo / poNumber。 */ |
||||
@Test |
||||
void cancelUsesSameRequestBodyShape() { |
||||
RecordingTransport transport = transport() |
||||
.route(EdayunConstants.PATH_ORDER_CANCEL, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":true}")); |
||||
|
||||
adapter(transport).cancel(ctx(), |
||||
CancelCommand.builder().outboundRequestNo("P-1").build()); |
||||
|
||||
String body = transport.lastDataRequest().body(); |
||||
assertTrue(body.contains("\"poNumber\":\"P-1\""), body); |
||||
org.junit.jupiter.api.Assertions.assertFalse(body.contains("acceptCharge")); |
||||
} |
||||
|
||||
/** 校验与取消的请求体同构(复用 CancelRequest)。 */ |
||||
@Test |
||||
void bothEndpointsShareRequestShape() { |
||||
EdayunCancelDtos.CancelRequest req = new EdayunCancelDtos.CancelRequest(); |
||||
req.orderNo = "ORD-1"; |
||||
req.poNumber = "P-1"; |
||||
|
||||
String json = new JacksonJsonCodec().toJson(req); |
||||
assertTrue(json.contains("\"orderNo\":\"ORD-1\""), json); |
||||
assertTrue(json.contains("\"poNumber\":\"P-1\""), json); |
||||
} |
||||
} |
||||
@ -0,0 +1,174 @@
@@ -0,0 +1,174 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunAccountFlowDtos; |
||||
import common.ecommerce.warehouse.enums.WarehouseFeeType; |
||||
import common.ecommerce.warehouse.model.BillingDocument; |
||||
import common.ecommerce.warehouse.model.FeeQuery; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.time.Instant; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertNull; |
||||
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 交易明细({@code POST /webApi/accountFlow/list})映射。 |
||||
* |
||||
* <p>重点:不按单号去重、金额是 string 可为负、无业务单号时时间段必填且 ≤180 天。</p> |
||||
*/ |
||||
class EdayunFeeTest { |
||||
|
||||
// ------------------------------------------------------------ 请求
|
||||
|
||||
/** 有业务单号时不强制时间段。 */ |
||||
@Test |
||||
void bizNoAloneIsEnough() { |
||||
EdayunAccountFlowDtos.ListFlowRequest req = EdayunFeeMapper.toRequest( |
||||
FeeQuery.builder().externalOrderNo("ORD25037232211").build()); |
||||
|
||||
assertEquals("ORD25037232211", req.bizNo); |
||||
assertNull(req.beginBillingTime); |
||||
assertEquals(Integer.valueOf(1), req.pageNum); |
||||
assertEquals(Integer.valueOf(200), req.pageSize); |
||||
} |
||||
|
||||
/** 没业务单号时必须给时间段。 */ |
||||
@Test |
||||
void withoutBizNoRangeIsRequired() { |
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, |
||||
() -> EdayunFeeMapper.toRequest(FeeQuery.builder().build())); |
||||
assertTrue(ex.getMessage().contains("bizNo or a billing time range"), ex.getMessage()); |
||||
} |
||||
|
||||
/** 没业务单号时时间段不能超过 180 天。 */ |
||||
@Test |
||||
void rangeOver180DaysWithoutBizNoIsRejected() { |
||||
FeeQuery tooLong = FeeQuery.builder() |
||||
.settledAfter(Instant.parse("2026-01-01T00:00:00Z")) |
||||
.settledBefore(Instant.parse("2026-12-31T00:00:00Z")) |
||||
.build(); |
||||
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, |
||||
() -> EdayunFeeMapper.toRequest(tooLong)); |
||||
assertTrue(ex.getMessage().contains("180"), ex.getMessage()); |
||||
} |
||||
|
||||
/** 有业务单号时时间段可以长一些(文档只说「没有业务单号时」有 180 天限制)。 */ |
||||
@Test |
||||
void rangeOver180DaysAllowedWithBizNo() { |
||||
EdayunAccountFlowDtos.ListFlowRequest req = EdayunFeeMapper.toRequest(FeeQuery.builder() |
||||
.externalOrderNo("ORD-1") |
||||
.settledAfter(Instant.parse("2026-01-01T00:00:00Z")) |
||||
.settledBefore(Instant.parse("2026-12-31T00:00:00Z")) |
||||
.build()); |
||||
|
||||
assertEquals("ORD-1", req.bizNo); |
||||
assertEquals(Long.valueOf(Instant.parse("2026-01-01T00:00:00Z").toEpochMilli()), |
||||
req.beginBillingTime); |
||||
} |
||||
|
||||
/** 时间是毫秒。 */ |
||||
@Test |
||||
void rangeIsInMillis() { |
||||
EdayunAccountFlowDtos.ListFlowRequest req = EdayunFeeMapper.toRequest(FeeQuery.builder() |
||||
.settledAfter(Instant.parse("2026-11-01T00:00:00Z")) |
||||
.settledBefore(Instant.parse("2026-11-10T00:00:00Z")) |
||||
.build()); |
||||
|
||||
assertEquals(Long.valueOf(Instant.parse("2026-11-10T00:00:00Z").toEpochMilli()), |
||||
req.endBillingTime); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 响应
|
||||
|
||||
private static EdayunAccountFlowDtos.FlowRow chargeRow() { |
||||
EdayunAccountFlowDtos.FlowRow row = new EdayunAccountFlowDtos.FlowRow(); |
||||
row.serialNumber = "LF-1741871641090"; |
||||
row.relateBusinessCode = "ORD25037232211"; |
||||
row.poNumber = "P-20261112"; |
||||
row.operateType = 0; |
||||
row.accountType = 0; |
||||
row.billingName = "运费附加费计费项-偏远附加费"; |
||||
row.billingCode = "farawayFee"; |
||||
row.originalCurrency = "USD"; |
||||
row.billingAmount = "-0.500"; |
||||
row.accountCurrency = "USD"; |
||||
row.exchangeRate = 1.1; |
||||
row.accountBalance = 998869.12; |
||||
row.billingTime = 1741145821000L; |
||||
return row; |
||||
} |
||||
|
||||
@Test |
||||
void mapsDocument() { |
||||
BillingDocument doc = EdayunFeeMapper.toDocument(chargeRow(), "EDY-WH-1"); |
||||
|
||||
assertEquals("ORD25037232211", doc.documentNo()); |
||||
assertEquals("LF-1741871641090", doc.serialNumber()); |
||||
assertEquals("运费附加费计费项-偏远附加费", doc.feeName()); |
||||
assertEquals(Instant.ofEpochMilli(1741145821000L), doc.settledAt()); |
||||
assertEquals("P-20261112", doc.saleOrderNo()); |
||||
// 交易明细是已发生账目,不是预估
|
||||
assertEquals(Boolean.FALSE, doc.estimated()); |
||||
assertEquals(new BigDecimal("998869.12"), |
||||
doc.accountBalance().amount()); |
||||
} |
||||
|
||||
/** 金额是 string 且可为负——扣费是负数,不能取绝对值。 */ |
||||
@Test |
||||
void amountKeepsSign() { |
||||
BillingDocument charge = EdayunFeeMapper.toDocument(chargeRow(), "W"); |
||||
assertEquals(new BigDecimal("-0.500"), charge.amount().amount()); |
||||
assertEquals("USD", charge.amount().currency().getCurrencyCode()); |
||||
|
||||
EdayunAccountFlowDtos.FlowRow refund = chargeRow(); |
||||
refund.billingAmount = "12.30"; |
||||
assertEquals(new BigDecimal("12.30"), |
||||
EdayunFeeMapper.toDocument(refund, "W").amount().amount()); |
||||
} |
||||
|
||||
/** 币种优先账户币种,缺失才用原币。 */ |
||||
@Test |
||||
void amountCurrencyPrefersAccountCurrency() { |
||||
EdayunAccountFlowDtos.FlowRow row = chargeRow(); |
||||
row.accountCurrency = "CNY"; |
||||
row.originalCurrency = "USD"; |
||||
|
||||
assertEquals("CNY", EdayunFeeMapper.toDocument(row, "W").amount().currency().getCurrencyCode()); |
||||
|
||||
row.accountCurrency = null; |
||||
assertEquals("USD", EdayunFeeMapper.toDocument(row, "W").amount().currency().getCurrencyCode()); |
||||
} |
||||
|
||||
/** 计费项按编码关键字推断;认不出返回 null,不猜。 */ |
||||
@Test |
||||
void feeTypeIsInferredFromCode() { |
||||
assertEquals(WarehouseFeeType.STORAGE, EdayunFeeMapper.feeTypeOf("storageFee")); |
||||
assertEquals(WarehouseFeeType.OPERATION, EdayunFeeMapper.feeTypeOf("handlingFee")); |
||||
assertEquals(WarehouseFeeType.LAST_MILE, EdayunFeeMapper.feeTypeOf("farawayFee")); |
||||
assertEquals(WarehouseFeeType.VALUE_ADDED, EdayunFeeMapper.feeTypeOf("labelServiceFee")); |
||||
// 认不出不猜
|
||||
assertNull(EdayunFeeMapper.feeTypeOf("someUnknownCode")); |
||||
assertNull(EdayunFeeMapper.feeTypeOf(null)); |
||||
} |
||||
|
||||
/** 同一单号的同一计费项多条流水——每条都要保留,不能去重。 */ |
||||
@Test |
||||
void multipleRowsForSameOrderAreKept() { |
||||
EdayunAccountFlowDtos.FlowRow a = chargeRow(); |
||||
a.serialNumber = "LF-1"; |
||||
EdayunAccountFlowDtos.FlowRow b = chargeRow(); |
||||
b.serialNumber = "LF-2"; |
||||
|
||||
BillingDocument d1 = EdayunFeeMapper.toDocument(a, "W"); |
||||
BillingDocument d2 = EdayunFeeMapper.toDocument(b, "W"); |
||||
|
||||
// 单号与计费项都相同,但流水号不同 → 是两笔
|
||||
assertEquals(d1.documentNo(), d2.documentNo()); |
||||
assertEquals(d1.feeName(), d2.feeName()); |
||||
assertTrue(!d1.serialNumber().equals(d2.serialNumber())); |
||||
} |
||||
} |
||||
@ -0,0 +1,197 @@
@@ -0,0 +1,197 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunOrderCostDtos; |
||||
import common.ecommerce.warehouse.enums.FeeQueryNoType; |
||||
import common.ecommerce.warehouse.enums.WarehouseFeeType; |
||||
import common.ecommerce.warehouse.model.BillingDocument; |
||||
import common.ecommerce.warehouse.model.FeeQuery; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.time.Instant; |
||||
import java.util.List; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertNull; |
||||
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 订单费用明细({@code selectOrderCostInfoList})映射。 |
||||
* |
||||
* <p>重点:金额取<b>实付</b>、按计费项展开成多条、单号类型要配合、时间窗 ≤3 个月。</p> |
||||
*/ |
||||
class EdayunOrderCostTest { |
||||
|
||||
// ------------------------------------------------------------ 请求
|
||||
|
||||
@Test |
||||
void mapsOrderNumberAndType() { |
||||
EdayunOrderCostDtos.SelectOrderCostRequest req = EdayunOrderCostMapper.toRequest( |
||||
FeeQuery.builder() |
||||
.externalOrderNo("60044642") |
||||
.noType(FeeQueryNoType.PLATFORM_ORDER_NO) |
||||
.build()); |
||||
|
||||
assertEquals("60044642", req.orderNo); |
||||
assertEquals(Integer.valueOf(1), req.type); // 1 平台单号
|
||||
assertEquals(Integer.valueOf(1), req.pageNum); |
||||
assertEquals(Integer.valueOf(200), req.pageSize); |
||||
} |
||||
|
||||
/** 三种单号类型都要映射对。 */ |
||||
@Test |
||||
void allNoTypesMap() { |
||||
assertEquals(Integer.valueOf(0), |
||||
EdayunOrderCostMapper.typeOf(FeeQueryNoType.PROVIDER_ORDER_NO)); |
||||
assertEquals(Integer.valueOf(1), |
||||
EdayunOrderCostMapper.typeOf(FeeQueryNoType.PLATFORM_ORDER_NO)); |
||||
assertEquals(Integer.valueOf(2), |
||||
EdayunOrderCostMapper.typeOf(FeeQueryNoType.TRACKING_NO)); |
||||
assertNull(EdayunOrderCostMapper.typeOf(null)); |
||||
} |
||||
|
||||
/** 既不传单号也不传时间窗时本地拒绝。 */ |
||||
@Test |
||||
void withoutOrderNoOrRangeIsRejected() { |
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, |
||||
() -> EdayunOrderCostMapper.toRequest(FeeQuery.builder().build())); |
||||
assertTrue(ex.getMessage().contains("order number or a billing time range"), ex.getMessage()); |
||||
} |
||||
|
||||
/** 时间窗不能超过 3 个月。 */ |
||||
@Test |
||||
void rangeOver3MonthsIsRejected() { |
||||
FeeQuery tooLong = FeeQuery.builder() |
||||
.settledAfter(Instant.parse("2026-01-01T00:00:00Z")) |
||||
.settledBefore(Instant.parse("2026-06-01T00:00:00Z")) |
||||
.build(); |
||||
|
||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, |
||||
() -> EdayunOrderCostMapper.toRequest(tooLong)); |
||||
assertTrue(ex.getMessage().contains("3 months"), ex.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void rangeWithin3MonthsIsAccepted() { |
||||
EdayunOrderCostDtos.SelectOrderCostRequest req = EdayunOrderCostMapper.toRequest( |
||||
FeeQuery.builder() |
||||
.settledAfter(Instant.parse("2026-01-01T00:00:00Z")) |
||||
.settledBefore(Instant.parse("2026-02-15T00:00:00Z")) |
||||
.build()); |
||||
|
||||
assertEquals(Long.valueOf(Instant.parse("2026-01-01T00:00:00Z").toEpochMilli()), |
||||
req.beginBillingTime); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 响应
|
||||
|
||||
private static EdayunOrderCostDtos.OrderCostRow twoFeeRow() { |
||||
EdayunOrderCostDtos.OrderCostRow row = new EdayunOrderCostDtos.OrderCostRow(); |
||||
row.orderCode = "ORD26091260233"; |
||||
row.poNumber = "60044642"; |
||||
row.warehouseName = "美西1仓"; |
||||
row.trackingNo = "877399075299"; |
||||
row.billingTime = 1789781258000L; |
||||
|
||||
EdayunOrderCostDtos.FeeDetail freight = new EdayunOrderCostDtos.FeeDetail(); |
||||
freight.billingName = "尾程-运费"; |
||||
freight.amountReceivable = 20.0; |
||||
freight.discountPrice = 5.0; |
||||
freight.realPayPrice = 15.0; |
||||
freight.currencyCode = "USD"; |
||||
|
||||
EdayunOrderCostDtos.FeeDetail handling = new EdayunOrderCostDtos.FeeDetail(); |
||||
handling.billingName = "尾程-出库处理费"; |
||||
handling.amountReceivable = 0.54; |
||||
handling.discountPrice = 0.162; |
||||
handling.realPayPrice = 0.378; |
||||
handling.currencyCode = "USD"; |
||||
|
||||
EdayunOrderCostDtos.ChargeDetail charge = new EdayunOrderCostDtos.ChargeDetail(); |
||||
charge.currencyCode = "USD"; |
||||
charge.feeDetails = java.util.Arrays.asList(freight, handling); |
||||
row.chargeDetails = java.util.Collections.singletonList(charge); |
||||
return row; |
||||
} |
||||
|
||||
/** 一层 chargeDetails 里多个 feeDetails → 展开成多条记录。 */ |
||||
@Test |
||||
void expandsToMultipleDocuments() { |
||||
List<BillingDocument> docs = EdayunOrderCostMapper.toDocuments(twoFeeRow(), "EDY-WH"); |
||||
|
||||
assertEquals(2, docs.size()); |
||||
assertEquals("尾程-运费", docs.get(0).feeName()); |
||||
assertEquals("尾程-出库处理费", docs.get(1).feeName()); |
||||
} |
||||
|
||||
/** 落库金额取实付(应收 - 折扣),不是应收。 */ |
||||
@Test |
||||
void amountIsRealPayNotReceivable() { |
||||
List<BillingDocument> docs = EdayunOrderCostMapper.toDocuments(twoFeeRow(), "W"); |
||||
|
||||
assertEquals(new BigDecimal("15.0"), docs.get(0).amount().amount()); |
||||
assertEquals(new BigDecimal("0.378"), docs.get(1).amount().amount()); |
||||
} |
||||
|
||||
@Test |
||||
void mapsHeaderFields() { |
||||
List<BillingDocument> docs = EdayunOrderCostMapper.toDocuments(twoFeeRow(), "W"); |
||||
BillingDocument first = docs.get(0); |
||||
|
||||
assertEquals("ORD26091260233", first.documentNo()); |
||||
assertEquals("60044642", first.saleOrderNo()); |
||||
assertEquals("877399075299", first.serialNumber()); |
||||
assertEquals(Instant.ofEpochMilli(1789781258000L), first.settledAt()); |
||||
// 实际发生,不是预估
|
||||
assertEquals(Boolean.FALSE, first.estimated()); |
||||
} |
||||
|
||||
/** 费用类型按中文名推断;认不出不猜。 */ |
||||
@Test |
||||
void feeTypeIsInferredFromChineseName() { |
||||
assertEquals(WarehouseFeeType.LAST_MILE, EdayunOrderCostMapper.feeTypeOf("尾程-运费")); |
||||
assertEquals(WarehouseFeeType.OPERATION, EdayunOrderCostMapper.feeTypeOf("尾程-出库处理费")); |
||||
assertEquals(WarehouseFeeType.STORAGE, EdayunOrderCostMapper.feeTypeOf("仓储费")); |
||||
assertEquals(WarehouseFeeType.VALUE_ADDED, EdayunOrderCostMapper.feeTypeOf("增值服务-贴标")); |
||||
assertNull(EdayunOrderCostMapper.feeTypeOf("某个新费用")); |
||||
assertNull(EdayunOrderCostMapper.feeTypeOf(null)); |
||||
} |
||||
|
||||
/** 没有 feeDetails 但有 chargeDetails 汇总时,按汇总记一条。 */ |
||||
@Test |
||||
void fallsBackToChargeSummary() { |
||||
EdayunOrderCostDtos.OrderCostRow row = twoFeeRow(); |
||||
EdayunOrderCostDtos.ChargeDetail onlySummary = new EdayunOrderCostDtos.ChargeDetail(); |
||||
onlySummary.realPayPrice = 14.442; |
||||
onlySummary.currencyCode = "USD"; |
||||
row.chargeDetails = java.util.Collections.singletonList(onlySummary); |
||||
|
||||
List<BillingDocument> docs = EdayunOrderCostMapper.toDocuments(row, "W"); |
||||
|
||||
assertEquals(1, docs.size()); |
||||
assertEquals("订单费用", docs.get(0).feeName()); |
||||
assertEquals(new BigDecimal("14.442"), docs.get(0).amount().amount()); |
||||
} |
||||
|
||||
/** 完全没有 chargeDetails 时不抛异常,返回一条零金额占位。 */ |
||||
@Test |
||||
void noChargeDetailsYieldsZeroPlaceholder() { |
||||
EdayunOrderCostDtos.OrderCostRow row = twoFeeRow(); |
||||
row.chargeDetails = null; |
||||
|
||||
List<BillingDocument> docs = EdayunOrderCostMapper.toDocuments(row, "W"); |
||||
|
||||
assertEquals(1, docs.size()); |
||||
assertEquals(BigDecimal.ZERO, docs.get(0).amount().amount()); |
||||
} |
||||
|
||||
/** 一个订单的多个 feeDetail 都挂同一个 documentNo,靠 feeName 区分。 */ |
||||
@Test |
||||
void documentsShareOrderNumberButDifferByFeeName() { |
||||
List<BillingDocument> docs = EdayunOrderCostMapper.toDocuments(twoFeeRow(), "W"); |
||||
|
||||
assertEquals(docs.get(0).documentNo(), docs.get(1).documentNo()); |
||||
assertTrue(!docs.get(0).feeName().equals(docs.get(1).feeName())); |
||||
} |
||||
} |
||||
@ -0,0 +1,248 @@
@@ -0,0 +1,248 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunGetOrderDtos; |
||||
import common.ecommerce.edayun.dto.EdayunGetOrderLabelDtos; |
||||
import common.ecommerce.edayun.enums.EdayunOrderStatus; |
||||
import common.ecommerce.warehouse.enums.OutboundStatus; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
import common.ecommerce.warehouse.model.OutboundOrder; |
||||
import common.ecommerce.warehouse.model.PackageResult; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Instant; |
||||
import java.util.List; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertNull; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 查询出库单({@code getOrderInfo})与面单({@code getOrderLabel})的映射。 |
||||
*/ |
||||
class EdayunOrderQueryTest { |
||||
|
||||
// ------------------------------------------------------------ 状态映射
|
||||
|
||||
/** 文档口径:已发货 = Shipped / Online / Delivered / Returns。 */ |
||||
@Test |
||||
void shippedStatuses() { |
||||
for (String s : new String[] {"Shipped", "Online", "Delivered", "Returns"}) { |
||||
assertEquals(OutboundStatus.SHIPPED, EdayunOrderStatus.toCore(s), s); |
||||
assertTrue(EdayunOrderStatus.isShipped(s), s); |
||||
} |
||||
} |
||||
|
||||
/** 文档口径:已取消 = Cancelled / InterceptSuccess。 */ |
||||
@Test |
||||
void cancelledStatuses() { |
||||
for (String s : new String[] {"Cancelled", "InterceptSuccess"}) { |
||||
assertEquals(OutboundStatus.CANCELLED, EdayunOrderStatus.toCore(s), s); |
||||
assertTrue(EdayunOrderStatus.isCancelled(s), s); |
||||
} |
||||
} |
||||
|
||||
/** 异常类全部折叠到 EXCEPTION,具体原因看 errorMsg / rawStatus。 */ |
||||
@Test |
||||
void exceptionStatuses() { |
||||
for (String s : new String[] {"DistrError", "NoCarrier", "NoMapping", "ShipmentError", |
||||
"LabelError", "ManualReview", "InvError", "StockLack", "BillLate", |
||||
"BalanceNotEnough", "VerifyNotPass", "StockException"}) { |
||||
assertEquals(OutboundStatus.EXCEPTION, EdayunOrderStatus.toCore(s), s); |
||||
} |
||||
} |
||||
|
||||
@Test |
||||
void unknownStatusIsNotGuessed() { |
||||
assertEquals(OutboundStatus.UNKNOWN, EdayunOrderStatus.toCore("SomeNewStatus")); |
||||
assertEquals(OutboundStatus.UNKNOWN, EdayunOrderStatus.toCore(null)); |
||||
assertEquals(OutboundStatus.UNKNOWN, EdayunOrderStatus.toCore("")); |
||||
} |
||||
|
||||
/** 大小写不敏感,但仍是精确匹配(不是子串)。 */ |
||||
@Test |
||||
void matchingIsExactButCaseInsensitive() { |
||||
assertEquals(OutboundStatus.SHIPPED, EdayunOrderStatus.toCore("shipped")); |
||||
// 子串不算:Shipment 是「发货中」,不能因为含 Ship 就判已发货
|
||||
assertEquals(OutboundStatus.PICKING, EdayunOrderStatus.toCore("Shipment")); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 订单映射
|
||||
|
||||
private static EdayunGetOrderDtos.OrderInfo fullOrder() { |
||||
EdayunGetOrderDtos.OrderInfo info = new EdayunGetOrderDtos.OrderInfo(); |
||||
info.orderNo = "EDA-1"; |
||||
info.poNumber = "P-20261112"; |
||||
info.orderStatus = "Shipped"; |
||||
info.warehouseCode = "US-WH-1"; |
||||
info.carrierName = "UPS"; |
||||
info.carrierId = "3"; |
||||
info.trackingNo = "1Z999"; |
||||
info.currency = "USD"; |
||||
info.estimatedCost = 8.5; |
||||
info.createTime = "1762764000000"; |
||||
info.shippedTime = 1762800000000L; |
||||
info.errorMsg = null; |
||||
|
||||
EdayunGetOrderDtos.OrderInfo.OrderAddress addr = |
||||
new EdayunGetOrderDtos.OrderInfo.OrderAddress(); |
||||
addr.buyerName = "张三"; |
||||
addr.buyerPhone = "+1-555-0100"; |
||||
addr.email = "a@b.com"; |
||||
addr.destCountry = "US"; |
||||
addr.destProvince = "CA"; |
||||
addr.destProvinceName = "California"; |
||||
addr.destCity = "LA"; |
||||
addr.destFirstAddress = "1 Main St"; |
||||
addr.destSecondAddress = "Apt 2"; |
||||
addr.zipCode = "90001"; |
||||
info.orderAddressVO = addr; |
||||
|
||||
EdayunGetOrderDtos.OrderInfo.ProductItem item = |
||||
new EdayunGetOrderDtos.OrderInfo.ProductItem(); |
||||
item.productSku = "DM00001"; |
||||
item.quantity = 2; |
||||
item.unitPrice = 9.99; |
||||
item.snCodeList = java.util.Arrays.asList("SN001", "SN002"); |
||||
info.productItemVOList = java.util.Collections.singletonList(item); |
||||
|
||||
EdayunGetOrderDtos.OrderInfo.OrderAttribute attr = |
||||
new EdayunGetOrderDtos.OrderInfo.OrderAttribute(); |
||||
attr.signatureFlag = 1; |
||||
attr.insuranceFlag = 0; |
||||
info.orderAttribute = attr; |
||||
|
||||
return info; |
||||
} |
||||
|
||||
@Test |
||||
void mapsHeaderFields() { |
||||
OutboundOrder order = EdayunOrderQueryMapper.toOrder(fullOrder(), "OMS-WH", "P-20261112"); |
||||
|
||||
assertEquals("P-20261112", order.outboundRequestNo()); // poNumber 是来源单号
|
||||
assertEquals("EDA-1", order.providerOrderId()); // orderNo 是仓侧单号
|
||||
assertEquals("US-WH-1", order.warehouseCode()); |
||||
assertEquals(OutboundStatus.SHIPPED, order.status()); |
||||
assertEquals("Shipped", order.rawStatus()); |
||||
assertEquals("UPS", order.carrier()); |
||||
assertEquals("1Z999", order.trackingNumber()); |
||||
assertEquals(WarehouseProvider.EDAYUN, order.sourceProvider()); |
||||
assertEquals(Instant.ofEpochMilli(1762764000000L), order.requestedAt()); |
||||
assertEquals(Instant.ofEpochMilli(1762800000000L), order.shippedAt()); |
||||
} |
||||
|
||||
@Test |
||||
void mapsAddressPreferringTwoLetterCode() { |
||||
OutboundOrder order = EdayunOrderQueryMapper.toOrder(fullOrder(), "W", "P"); |
||||
|
||||
assertEquals("US", order.shipTo().countryCode()); |
||||
// 易达云同时给二字码与全称;标准模型口径是二字码
|
||||
assertEquals("CA", order.shipTo().stateOrProvince()); |
||||
assertEquals("LA", order.shipTo().city()); |
||||
assertEquals("Apt 2", order.shipTo().addressLine2()); |
||||
} |
||||
|
||||
@Test |
||||
void mapsLinesAndSerialNumbers() { |
||||
OutboundOrder order = EdayunOrderQueryMapper.toOrder(fullOrder(), "W", "P"); |
||||
|
||||
assertEquals(1, order.lines().size()); |
||||
assertEquals(Integer.valueOf(2), Integer.valueOf(order.lines().get(0).quantity())); |
||||
assertEquals("DM00001", order.lines().get(0).providerSku()); |
||||
|
||||
assertEquals(2, order.serialNumbers().size()); |
||||
assertEquals("SN001", order.serialNumbers().get(0).snCode()); |
||||
assertEquals("DM00001", order.serialNumbers().get(0).providerSku()); |
||||
} |
||||
|
||||
/** 0/1 旗标:null 保持 null,不猜成 false。 */ |
||||
@Test |
||||
void flagsStayNullWhenAbsent() { |
||||
EdayunGetOrderDtos.OrderInfo noAttr = fullOrder(); |
||||
noAttr.orderAttribute = null; |
||||
|
||||
OutboundOrder order = EdayunOrderQueryMapper.toOrder(noAttr, "W", "P"); |
||||
|
||||
assertNull(order.signatureRequired()); |
||||
assertNull(order.insured()); |
||||
} |
||||
|
||||
@Test |
||||
void mapsFlags() { |
||||
OutboundOrder order = EdayunOrderQueryMapper.toOrder(fullOrder(), "W", "P"); |
||||
assertEquals(Boolean.TRUE, order.signatureRequired()); |
||||
assertEquals(Boolean.FALSE, order.insured()); |
||||
} |
||||
|
||||
/** 异常类状态把 errorMsg 带出来。 */ |
||||
@Test |
||||
void errorMessageBecomesExceptionCode() { |
||||
EdayunGetOrderDtos.OrderInfo failed = fullOrder(); |
||||
failed.orderStatus = "DistrError"; |
||||
failed.errorMsg = "no warehouse for zip 90001"; |
||||
|
||||
OutboundOrder order = EdayunOrderQueryMapper.toOrder(failed, "W", "P"); |
||||
|
||||
assertEquals(OutboundStatus.EXCEPTION, order.status()); |
||||
assertEquals("no warehouse for zip 90001", order.exceptionCode()); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 面单映射
|
||||
|
||||
private static EdayunGetOrderLabelDtos.LabelData twoPackageLabel() { |
||||
EdayunGetOrderLabelDtos.LabelData data = new EdayunGetOrderLabelDtos.LabelData(); |
||||
data.orderNo = "EDA-1"; |
||||
data.poNumber = "P-20261112"; |
||||
data.carrierName = "UPS"; |
||||
data.carrierId = "3"; |
||||
data.trackingNo = "1Z111,1Z222"; |
||||
data.labels = "https://oss/1.png,https://oss/2.png"; |
||||
return data; |
||||
} |
||||
|
||||
/** 多包裹:trackingNo 与 labels 按位置一一对应。 */ |
||||
@Test |
||||
void packagesZipTrackingWithLabels() { |
||||
List<PackageResult> packages = EdayunOrderQueryMapper.toPackages(twoPackageLabel(), "P"); |
||||
|
||||
assertEquals(2, packages.size()); |
||||
assertEquals("1Z111", packages.get(0).trackingNumber()); |
||||
assertEquals("https://oss/1.png", packages.get(0).labelRef()); |
||||
assertEquals("1Z222", packages.get(1).trackingNumber()); |
||||
assertEquals("https://oss/2.png", packages.get(1).labelRef()); |
||||
assertEquals("UPS", packages.get(0).carrier()); |
||||
assertEquals("3", packages.get(0).carrierCode()); |
||||
} |
||||
|
||||
@Test |
||||
void singlePackageWorks() { |
||||
EdayunGetOrderLabelDtos.LabelData data = new EdayunGetOrderLabelDtos.LabelData(); |
||||
data.trackingNo = "1Z999"; |
||||
data.labels = "https://oss/1.png"; |
||||
|
||||
List<PackageResult> packages = EdayunOrderQueryMapper.toPackages(data, "P"); |
||||
|
||||
assertEquals(1, packages.size()); |
||||
assertEquals("1Z999", packages.get(0).trackingNumber()); |
||||
} |
||||
|
||||
/** 没有面单时返回空列表,不是错误。 */ |
||||
@Test |
||||
void emptyLabelIsEmptyList() { |
||||
EdayunGetOrderLabelDtos.LabelData data = new EdayunGetOrderLabelDtos.LabelData(); |
||||
|
||||
assertTrue(EdayunOrderQueryMapper.toPackages(data, "P").isEmpty()); |
||||
assertTrue(EdayunOrderQueryMapper.toPackages(null, "P").isEmpty()); |
||||
} |
||||
|
||||
/** 面单 URL 也能转成附件。 */ |
||||
@Test |
||||
void labelsBecomeAttachments() { |
||||
List<common.ecommerce.warehouse.model.WarehouseAttachment> atts = |
||||
EdayunOrderQueryMapper.attachmentsOf(twoPackageLabel()); |
||||
|
||||
assertEquals(2, atts.size()); |
||||
assertEquals("1Z111", atts.get(0).name()); |
||||
assertEquals("ShippingLabel", atts.get(0).type()); |
||||
assertEquals("https://oss/1.png", atts.get(0).url()); |
||||
} |
||||
} |
||||
@ -0,0 +1,174 @@
@@ -0,0 +1,174 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.dto.EdayunCreateOrderDtos; |
||||
import common.ecommerce.shared.model.Platform; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.enums.LabelMode; |
||||
import common.ecommerce.warehouse.model.OutboundCommand; |
||||
import common.ecommerce.warehouse.model.OutboundLine; |
||||
import common.ecommerce.warehouse.model.ShipTo; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import java.time.Instant; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertNull; |
||||
import static org.junit.jupiter.api.Assertions.assertThrows; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 创建出库单({@code POST /webApi/order/v1/createOrder})报文映射。 |
||||
* |
||||
* <p>重点:poNumber 是仓侧幂等键、promiseShipTime 是毫秒、州是<b>全称</b>不是二字码。</p> |
||||
*/ |
||||
class EdayunOrderTest { |
||||
|
||||
private static OutboundCommand.Builder base() { |
||||
return OutboundCommand.builder() |
||||
.outboundRequestNo("OB-1") |
||||
.orderRef("P-20261112") |
||||
.warehouseId("2") |
||||
.currency("USD") |
||||
.salesPlatform(Platform.AMAZON_SC) |
||||
.shipTo(ShipTo.builder() |
||||
.name("张三").phone("+1-555-0100").email("a@b.com") |
||||
.countryCode("US").stateOrProvince("California").city("Escondido") |
||||
.addressLine1("1308 E Washington Ave").postalCode("92027") |
||||
.build()) |
||||
.line(OutboundLine.builder() |
||||
.lineNo("1").omsSku("DM00001").quantity(2) |
||||
.declareValue(Money.of("9.99", "USD")) |
||||
.build()); |
||||
} |
||||
|
||||
@Test |
||||
void poNumberIsOrderRefNotOurRequestNo() { |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = |
||||
EdayunOrderMapper.toCreateRequest(base().build(), "2"); |
||||
|
||||
// 文档:重推时平台单号必须保持不变 → 用 orderRef
|
||||
assertEquals("P-20261112", req.poNumber); |
||||
} |
||||
|
||||
/** 没有 orderRef 时退回来源单号,不能为 null(它是幂等键)。 */ |
||||
@Test |
||||
void poNumberFallsBackToRequestNo() { |
||||
OutboundCommand noRef = OutboundCommand.builder() |
||||
.outboundRequestNo("OB-2") |
||||
.salesPlatform(Platform.AMAZON_SC) |
||||
.shipTo(ShipTo.builder().name("a").phone("p") |
||||
.countryCode("US").stateOrProvince("CA").city("c") |
||||
.addressLine1("a1").postalCode("1").build()) |
||||
.line(OutboundLine.builder().lineNo("1").omsSku("S").quantity(1).build()) |
||||
.build(); |
||||
|
||||
assertEquals("OB-2", EdayunOrderMapper.toCreateRequest(noRef, "2").poNumber); |
||||
} |
||||
|
||||
/** 最晚发货时间是毫秒时间戳,不是秒。 */ |
||||
@Test |
||||
void promiseShipTimeIsMillis() { |
||||
Instant ship = Instant.parse("2026-11-20T10:00:00Z"); |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = |
||||
EdayunOrderMapper.toCreateRequest(base().latestShipDate(ship).build(), "2"); |
||||
|
||||
assertEquals(Long.valueOf(ship.toEpochMilli()), req.promiseShipTime); |
||||
} |
||||
|
||||
@Test |
||||
void mapsAddress() { |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = |
||||
EdayunOrderMapper.toCreateRequest(base().build(), "2"); |
||||
|
||||
EdayunCreateOrderDtos.CreateOrderRequest.OrderAddress addr = req.orderAddressVO; |
||||
assertEquals("张三", addr.buyerName); |
||||
assertEquals("US", addr.destCountryName); |
||||
assertEquals("California", addr.destProvinceName); |
||||
assertEquals("Escondido", addr.destCity); |
||||
assertEquals("1308 E Washington Ave", addr.destFirstAddress); |
||||
assertEquals("92027", addr.zipCode); |
||||
assertEquals("a@b.com", addr.email); |
||||
} |
||||
|
||||
/** 商品行:unitPrice 是单价,不乘数量。 */ |
||||
@Test |
||||
void productUnitPriceIsNotMultiplied() { |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = |
||||
EdayunOrderMapper.toCreateRequest(base().build(), "2"); |
||||
|
||||
assertEquals(1, req.productItemVOList.size()); |
||||
EdayunCreateOrderDtos.CreateOrderRequest.ProductItem item = req.productItemVOList.get(0); |
||||
assertEquals("DM00001", item.productSku); |
||||
assertEquals(Integer.valueOf(2), item.quantity); |
||||
assertEquals(Double.valueOf(9.99), item.unitPrice); |
||||
assertEquals("USD", item.currencyCode); |
||||
} |
||||
|
||||
@Test |
||||
void mapsOrderCostAndCurrency() { |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = EdayunOrderMapper.toCreateRequest( |
||||
base().declaredTotal(Money.of("20.00", "USD")).build(), "2"); |
||||
|
||||
assertEquals(Double.valueOf(20.0), req.orderCost); |
||||
assertEquals("USD", req.currency); |
||||
} |
||||
|
||||
@Test |
||||
void warehouseIdFromCommandOrAccount() { |
||||
assertEquals("2", EdayunOrderMapper.toCreateRequest(base().build(), "99").warehouseId); |
||||
|
||||
OutboundCommand noWarehouse = base().warehouseId(null).build(); |
||||
assertEquals("99", EdayunOrderMapper.toCreateRequest(noWarehouse, "99").warehouseId); |
||||
} |
||||
|
||||
@Test |
||||
void platformNameIsEdayunStyle() { |
||||
assertEquals("Amazon", EdayunOrderMapper.channelNameOf( |
||||
base().salesPlatform(Platform.AMAZON_SC).build())); |
||||
assertEquals("eBay", EdayunOrderMapper.channelNameOf( |
||||
base().salesPlatform(Platform.EBAY).build())); |
||||
assertEquals("TIKTOK", EdayunOrderMapper.channelNameOf( |
||||
base().salesPlatform(Platform.TIKTOK).build())); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 面单
|
||||
|
||||
/** 平台面单必须给 URL;给 base64 在本地就拒绝。 */ |
||||
@Test |
||||
void platformLabelAcceptsUrlRejectsBase64() { |
||||
EdayunCreateOrderDtos.CreateOrderRequest withUrl = EdayunOrderMapper.toCreateRequest( |
||||
base().labelMode(LabelMode.PLATFORM_LABEL) |
||||
.labelContentBase64("https://files.example/label.pdf") |
||||
.trackingNumber("1Z999") |
||||
.build(), "2"); |
||||
assertEquals("https://files.example/label.pdf", withUrl.labels); |
||||
assertEquals("1Z999", withUrl.trackingNo); |
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> EdayunOrderMapper.toCreateRequest( |
||||
base().labelMode(LabelMode.PLATFORM_LABEL) |
||||
.labelContentBase64("JVBERi0xLjQK") |
||||
.build(), "2")); |
||||
} |
||||
|
||||
/** 仓自有面单:只带承运商,不带 labels。 */ |
||||
@Test |
||||
void warehouseLabelHasNoLabels() { |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = EdayunOrderMapper.toCreateRequest( |
||||
base().labelMode(LabelMode.WAREHOUSE_LABEL).carrier("FEDEX").build(), "2"); |
||||
|
||||
assertNull(req.labels); |
||||
assertEquals("FEDEX", req.carrierName); |
||||
} |
||||
|
||||
/** 签收服务。 */ |
||||
@Test |
||||
void signatureMapsToAddService() { |
||||
EdayunCreateOrderDtos.CreateOrderRequest req = EdayunOrderMapper.toCreateRequest( |
||||
base().signatureRequired(true).build(), "2"); |
||||
|
||||
assertEquals(1, req.addService.size()); |
||||
assertEquals("is_signature", req.addService.get(0)); |
||||
|
||||
assertNull(EdayunOrderMapper.toCreateRequest(base().build(), "2").addService); |
||||
} |
||||
} |
||||
@ -0,0 +1,153 @@
@@ -0,0 +1,153 @@
|
||||
package common.ecommerce.edayun.adapter; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.dto.EdayunCreateProductDtos; |
||||
import common.ecommerce.edayun.enums.EdayunYesNo; |
||||
import common.ecommerce.shared.spi.AccessToken; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.capability.WarehouseProduct; |
||||
import common.ecommerce.warehouse.enums.WarehouseCapability; |
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals; |
||||
import static org.junit.jupiter.api.Assertions.assertNull; |
||||
import static org.junit.jupiter.api.Assertions.assertTrue; |
||||
|
||||
/** |
||||
* 创建产品({@code POST /webApi/skuInfo/v1/createProduct})报文映射。 |
||||
* |
||||
* <p>只测映射,不发请求——重点是三处反向标志、g→kg 换算、申报信息的组装。</p> |
||||
*/ |
||||
class EdayunProductTest { |
||||
|
||||
private static WarehouseProduct.Builder base() { |
||||
return WarehouseProduct.builder() |
||||
.omsSku("DM00001") |
||||
.name("测试商品") |
||||
.nameEn("Test Product") |
||||
.packingType(0) |
||||
.lengthCm(10).widthCm(8).heightCm(6) |
||||
.weightGrams(500); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 映射
|
||||
|
||||
@Test |
||||
void mapsCoreFields() { |
||||
EdayunCreateProductDtos.CreateProductRequest req = |
||||
EdayunProductMapper.toCreateRequest(base().build()); |
||||
|
||||
assertEquals("DM00001", req.skuCode); |
||||
assertEquals("测试商品", req.skuName); |
||||
assertEquals("Test Product", req.skuNameEn); |
||||
assertEquals(Double.valueOf(10.0), req.length); |
||||
assertEquals(Double.valueOf(8.0), req.width); |
||||
assertEquals(Double.valueOf(6.0), req.height); |
||||
} |
||||
|
||||
/** 单位:标准模型是克,易达云是千克。 */ |
||||
@Test |
||||
void convertsGramsToKilograms() { |
||||
EdayunCreateProductDtos.CreateProductRequest req = |
||||
EdayunProductMapper.toCreateRequest(base().weightGrams(500).build()); |
||||
|
||||
assertEquals(Double.valueOf(0.5), req.weight); |
||||
} |
||||
|
||||
/** |
||||
* brandFlag 是「0 是 / 1 否」,与直觉相反。 |
||||
* 没有品牌信息时必须传 1(否),传 0 会让仓以为这是品牌商品。 |
||||
*/ |
||||
@Test |
||||
void brandFlagIsInverted() { |
||||
EdayunCreateProductDtos.CreateProductRequest withoutBrand = |
||||
EdayunProductMapper.toCreateRequest(base().build()); |
||||
assertEquals(Integer.valueOf(1), withoutBrand.brandFlag); |
||||
|
||||
EdayunCreateProductDtos.CreateProductRequest withBrand = |
||||
EdayunProductMapper.toCreateRequest( |
||||
base().customItemNo("BRAND-1").build()); |
||||
assertEquals(Integer.valueOf(0), withBrand.brandFlag); |
||||
} |
||||
|
||||
/** 统一模型没有带电信息,默认按「不带电」= 1。 */ |
||||
@Test |
||||
void defaultsToNotPowered() { |
||||
EdayunCreateProductDtos.CreateProductRequest req = |
||||
EdayunProductMapper.toCreateRequest(base().build()); |
||||
|
||||
assertEquals(Integer.valueOf(1), req.electricFlag); |
||||
assertEquals(Integer.valueOf(0), req.logisticsPackagingType); |
||||
assertEquals(Boolean.FALSE, req.pmFlag); |
||||
} |
||||
|
||||
@Test |
||||
void mapsSerialAndBatchFlags() { |
||||
EdayunCreateProductDtos.CreateProductRequest req = |
||||
EdayunProductMapper.toCreateRequest(base() |
||||
.snManagementMode(1) |
||||
.lotControlEnabled(true) |
||||
.expirationControl(true) |
||||
.expirationDays(365) |
||||
.build()); |
||||
|
||||
assertEquals(Integer.valueOf(1), req.collectSerialNumber); |
||||
assertEquals(Integer.valueOf(0), req.batchManagementEnabled); |
||||
assertEquals(Integer.valueOf(1), req.batchInfo.expirationEnabled); |
||||
assertEquals(Integer.valueOf(365), req.batchInfo.shelfLifeDays); |
||||
} |
||||
|
||||
/** 申报信息:出口 + 进口各一条,缺申报价值时整组不下发(不编造)。 */ |
||||
@Test |
||||
void declarationsRequireValueAndOrigin() { |
||||
assertNull(EdayunProductMapper.toCreateRequest(base().build()).declarationInfoList); |
||||
|
||||
EdayunCreateProductDtos.CreateProductRequest req = EdayunProductMapper.toCreateRequest( |
||||
base().declaredValue(Money.of("10.00", "USD")) |
||||
.countryOfOrigin("cn") |
||||
.hsCode("8517") |
||||
.build()); |
||||
|
||||
assertEquals(2, req.declarationInfoList.size()); |
||||
assertEquals(Integer.valueOf(0), req.declarationInfoList.get(0).declarationType); // 出口
|
||||
assertEquals("CN", req.declarationInfoList.get(0).country); |
||||
assertEquals(Integer.valueOf(1), req.declarationInfoList.get(1).declarationType); // 进口
|
||||
assertEquals(Double.valueOf(10.0), req.declarationInfoList.get(0).declaredPrice); |
||||
assertEquals("USD", req.declarationInfoList.get(0).currencyType); |
||||
} |
||||
|
||||
@Test |
||||
void imageGoesToPicList() { |
||||
EdayunCreateProductDtos.CreateProductRequest req = EdayunProductMapper.toCreateRequest( |
||||
base().imageUrl("https://img/1.jpg").build()); |
||||
|
||||
assertEquals(1, req.picList.size()); |
||||
assertEquals("https://img/1.jpg", req.picList.get(0).picUrl); |
||||
assertNull(EdayunProductMapper.toCreateRequest(base().build()).picList); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 枚举
|
||||
|
||||
@Test |
||||
void yesNoCodesAreInverted() { |
||||
assertEquals(Integer.valueOf(0), EdayunYesNo.codeOf(true)); |
||||
assertEquals(Integer.valueOf(1), EdayunYesNo.codeOf(false)); |
||||
assertNull(EdayunYesNo.codeOf(null)); |
||||
|
||||
assertEquals(Boolean.TRUE, EdayunYesNo.valueOf(0)); |
||||
assertEquals(Boolean.FALSE, EdayunYesNo.valueOf(1)); |
||||
// 未知码不猜
|
||||
assertNull(EdayunYesNo.valueOf(9)); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 适配器
|
||||
|
||||
@Test |
||||
void declaresProductCapability() { |
||||
EdayunAdapter adapter = new EdayunAdapter(RecordingTransport.create(), |
||||
new common.ecommerce.http.JacksonJsonCodec()); |
||||
assertTrue(adapter.capabilities().contains(WarehouseCapability.PRODUCT)); |
||||
} |
||||
} |
||||
@ -0,0 +1,214 @@
@@ -0,0 +1,214 @@
|
||||
package common.ecommerce.edayun.auth; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.http.EdayunRequestFactory; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.shared.error.ValidationException; |
||||
import common.ecommerce.shared.spi.AccessToken; |
||||
import common.ecommerce.shared.testkit.RecordingTransport; |
||||
import common.ecommerce.shared.testkit.Responses; |
||||
import common.ecommerce.warehouse.error.WarehouseException; |
||||
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; |
||||
|
||||
/** |
||||
* 易达云获取 token({@code POST /oauth/token})。 |
||||
* |
||||
* <p>文档只给了 {@code code} 的取值,没给响应体结构,所以这里把三种常见形态 |
||||
* (OAuth 标准 / 绝对时刻 / 顶层 token)都固化成测试,等真机确认后再删多余的分支。</p> |
||||
*/ |
||||
class EdayunTokenClientTest { |
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-12T00:00:00Z"), ZoneOffset.UTC); |
||||
private static final String BASE = "https://api.edayun.test"; |
||||
|
||||
private static EdayunTokenClient client(RecordingTransport transport) { |
||||
return new EdayunTokenClient(transport, new JacksonJsonCodec(), CLOCK); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 请求
|
||||
|
||||
@Test |
||||
void sendsDocumentedRequest() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"access_token\":\"T1\",\"expires_in\":7200}}")); |
||||
|
||||
client(transport).fetch(BASE, "dl-test", "123456"); |
||||
|
||||
String body = transport.lastDataRequest().body(); |
||||
assertEquals("POST", transport.lastDataRequest().method()); |
||||
assertEquals(BASE + "/oauth/token", transport.lastDataRequest().url()); |
||||
// 字段名是下划线风格,照文档原样
|
||||
assertTrue(body.contains("\"client_id\":\"dl-test\""), body); |
||||
assertTrue(body.contains("\"client_secret\":\"123456\""), body); |
||||
// 文档明确:这一步不需要业务头
|
||||
assertTrue(transport.lastDataRequest().headers().isEmpty() |
||||
|| !transport.lastDataRequest().headers().containsKey("token")); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 响应形态
|
||||
|
||||
/** 实测形态:HTTP 200 + 扁平 body,没有 code。 */ |
||||
@Test |
||||
void acceptsFlatShapeWithoutCode() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"access_token\":\"0dabff46-0492-44bc-9283-64163dc8a995\"," |
||||
+ "\"token_type\":\"bearer\",\"scope\":\"server\"}")); |
||||
|
||||
AccessToken token = client(transport).fetch(BASE, "openapi-test", "123456"); |
||||
|
||||
assertEquals("0dabff46-0492-44bc-9283-64163dc8a995", token.value()); |
||||
// 响应无有效期字段,按兜底周期估算
|
||||
assertEquals(Instant.parse("2026-11-12T02:00:00Z"), token.expiresAt()); |
||||
} |
||||
|
||||
@Test |
||||
void acceptsOauthStandardShape() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"access_token\":\"T1\",\"expires_in\":7200}}")); |
||||
|
||||
AccessToken token = client(transport).fetch(BASE, "u", "p"); |
||||
|
||||
assertEquals("T1", token.value()); |
||||
assertEquals(Instant.parse("2026-11-12T02:00:00Z"), token.expiresAt()); |
||||
} |
||||
|
||||
@Test |
||||
void acceptsAbsoluteExpiry() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"access_token\":\"T2\"," |
||||
+ "\"expiry\":\"2026-11-12T03:00:00Z\"}}")); |
||||
|
||||
AccessToken token = client(transport).fetch(BASE, "u", "p"); |
||||
|
||||
assertEquals("T2", token.value()); |
||||
assertEquals(Instant.parse("2026-11-12T03:00:00Z"), token.expiresAt()); |
||||
} |
||||
|
||||
@Test |
||||
void acceptsTopLevelToken() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"token\":\"T3\"}")); |
||||
|
||||
AccessToken token = client(transport).fetch(BASE, "u", "p"); |
||||
|
||||
assertEquals("T3", token.value()); |
||||
// 没有有效期信息时按兜底 TTL
|
||||
assertEquals(Instant.parse("2026-11-12T02:00:00Z"), token.expiresAt()); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 失败路径
|
||||
|
||||
@Test |
||||
void noTokenInResponseIsRejected() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":200,\"data\":{\"foo\":\"bar\"}}")); |
||||
|
||||
ValidationException ex = assertThrows(ValidationException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p")); |
||||
assertTrue(ex.getMessage().contains("no access token"), ex.getMessage()); |
||||
} |
||||
|
||||
/** 500 是明确失败,不重试。 */ |
||||
@Test |
||||
void business500IsNotRetryable() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":500,\"message\":\"bad credentials\"}")); |
||||
|
||||
WarehouseException ex = assertThrows(WarehouseException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p")); |
||||
assertTrue(ex.getMessage().contains("code=500"), ex.getMessage()); |
||||
assertEquals(Boolean.FALSE, ex.retryable()); |
||||
} |
||||
|
||||
/** 503 / 504 是网关与超时,值得重试。 */ |
||||
@Test |
||||
void gatewayAndTimeoutAreRetryable() { |
||||
for (String code : new String[] {"503", "504"}) { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( |
||||
"{\"code\":" + code + ",\"message\":\"gw\"}")); |
||||
WarehouseException ex = assertThrows(WarehouseException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p"), code); |
||||
assertEquals(Boolean.TRUE, ex.retryable(), code); |
||||
} |
||||
} |
||||
|
||||
/** 实测无 code;但 body 里也没有 token,所以要报「没有 access token」。 */ |
||||
@Test |
||||
void missingCodeWithoutTokenIsRejected() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.ok("{\"message\":\"ok\"}")); |
||||
|
||||
ValidationException ex = assertThrows(ValidationException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p")); |
||||
assertTrue(ex.getMessage().contains("no access token"), ex.getMessage()); |
||||
} |
||||
|
||||
@Test |
||||
void non2xxIsRejected() { |
||||
RecordingTransport transport = RecordingTransport.create() |
||||
.route(EdayunConstants.PATH_TOKEN, req -> Responses.status(401, "{}")); |
||||
|
||||
WarehouseException ex = assertThrows(WarehouseException.class, |
||||
() -> client(transport).fetch(BASE, "u", "p")); |
||||
assertTrue(ex.getMessage().contains("http 401"), ex.getMessage()); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 凭据校验
|
||||
|
||||
@Test |
||||
void missingCredentialsFailFast() { |
||||
RecordingTransport transport = RecordingTransport.create(); |
||||
|
||||
assertThrows(IllegalArgumentException.class, |
||||
() -> client(transport).fetch(BASE, " ", "p")); |
||||
assertThrows(IllegalArgumentException.class, |
||||
() -> client(transport).fetch(BASE, "u", null)); |
||||
assertTrue(transport.recorded().isEmpty(), "凭据缺失不应发出请求"); |
||||
} |
||||
|
||||
// ------------------------------------------------------------ 签名
|
||||
|
||||
@Test |
||||
void signIsMd5OfBodyDotSecret() { |
||||
// MD5("{\"a\":1}.secret") 的已知值,用独立实现校验
|
||||
String expected = md5Hex("{\"a\":1}.secret"); |
||||
assertEquals(expected, EdayunRequestFactory.sign("{\"a\":1}", "secret")); |
||||
} |
||||
|
||||
@Test |
||||
void emptyBodyStillSigns() { |
||||
assertEquals(md5Hex(".secret"), EdayunRequestFactory.sign(null, "secret")); |
||||
assertEquals(md5Hex(".secret"), EdayunRequestFactory.sign("", "secret")); |
||||
} |
||||
|
||||
private static String md5Hex(String s) { |
||||
try { |
||||
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); |
||||
byte[] d = md.digest(s.getBytes(java.nio.charset.StandardCharsets.UTF_8)); |
||||
StringBuilder sb = new StringBuilder(); |
||||
for (byte b : d) { |
||||
sb.append(Character.forDigit((b >> 4) & 0xF, 16)); |
||||
sb.append(Character.forDigit(b & 0xF, 16)); |
||||
} |
||||
return sb.toString(); |
||||
} catch (Exception e) { |
||||
throw new IllegalStateException(e); |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,114 @@
@@ -0,0 +1,114 @@
|
||||
package common.ecommerce.edayun.probe; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.adapter.EdayunAdapter; |
||||
import common.ecommerce.edayun.dto.EdayunCreateProductDtos; |
||||
import common.ecommerce.edayun.adapter.EdayunProductMapper; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.http.OkHttpTransport; |
||||
import common.ecommerce.shared.error.ChannelException; |
||||
import common.ecommerce.shared.spi.ChannelSecret; |
||||
import common.ecommerce.shared.support.Money; |
||||
import common.ecommerce.warehouse.capability.WarehouseProduct; |
||||
import common.ecommerce.warehouse.enums.WarehouseProvider; |
||||
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.UUID; |
||||
|
||||
/** |
||||
* 创建产品联调探针:<b>只打印将要发出的报文,不真的调用</b>。 |
||||
* |
||||
* <p>创建产品是写操作,会真实建档。默认连报文构造都只做 dry-run; |
||||
* 真跑需要显式加 {@code -Dedayun.probe.write=true}。</p> |
||||
* |
||||
* <pre> |
||||
* # 只看报文(安全) |
||||
* mvn -pl warehouse-sdk-edayun -DfailIfNoTests=false \ |
||||
* -Dedayun.probe.product=true \ |
||||
* -Dtest=EdayunCreateProductProbeTest test |
||||
* |
||||
* # 真发一次(会在测试仓建档,用随机 SKU 避免撞车) |
||||
* ... -Dedayun.probe.product=true -Dedayun.probe.write=true \ |
||||
* -Dedayun.probe.token=... -Dedayun.probe.appKey=... -Dedayun.probe.appSecret=... |
||||
* </pre> |
||||
*/ |
||||
@EnabledIfSystemProperty(named = "edayun.probe.product", matches = "true") |
||||
class EdayunCreateProductProbeTest { |
||||
|
||||
private static final String BASE_URL = opt("edayun.probe.baseUrl", EdayunConstants.PR_BASE_URL); |
||||
private static final String TOKEN = System.getProperty("edayun.probe.token", ""); |
||||
private static final String APP_KEY = System.getProperty("edayun.probe.appKey", ""); |
||||
private static final String APP_SECRET = System.getProperty("edayun.probe.appSecret", ""); |
||||
private static final boolean WRITE = Boolean.getBoolean("edayun.probe.write"); |
||||
|
||||
@Test |
||||
void dumpRequest() { |
||||
String sku = "PROBE-" + Long.toString(System.currentTimeMillis(), 36).toUpperCase(); |
||||
WarehouseProduct product = WarehouseProduct.builder() |
||||
.omsSku(sku) |
||||
.name("探针商品") |
||||
.nameEn("Probe Product") |
||||
.packingType(0) |
||||
.lengthCm(10).widthCm(8).heightCm(6) |
||||
.weightGrams(500) |
||||
.declaredValue(Money.of("10.00", "USD")) |
||||
.countryOfOrigin("CN") |
||||
.hsCode("8517") |
||||
.build(); |
||||
|
||||
EdayunCreateProductDtos.CreateProductRequest req = |
||||
EdayunProductMapper.toCreateRequest(product); |
||||
String bodyJson = new JacksonJsonCodec().toJson(req); |
||||
|
||||
System.out.println("\n================ edayun / POST /webApi/skuInfo/v1/createProduct ================"); |
||||
System.out.println("[request] " + bodyJson); |
||||
if (APP_SECRET != null && !APP_SECRET.isEmpty()) { |
||||
System.out.println("[sign] " + common.ecommerce.edayun.http.EdayunRequestFactory |
||||
.sign(bodyJson, APP_SECRET)); |
||||
} |
||||
|
||||
Assumptions.assumeTrue(WRITE, "dry-run:未加 -Dedayun.probe.write=true,不实际创建"); |
||||
Assumptions.assumeTrue(!TOKEN.trim().isEmpty() && !APP_KEY.trim().isEmpty() |
||||
&& !APP_SECRET.trim().isEmpty(), |
||||
"真跑需要 -Dedayun.probe.token / appKey / appSecret"); |
||||
|
||||
try { |
||||
WarehouseContext ctx = WarehouseContext.of("EDY-PROBE", WarehouseProvider.EDAYUN, null, |
||||
WarehouseConnection.of(BASE_URL, |
||||
ChannelSecret.builder() |
||||
.appKey(APP_KEY).appSecret(APP_SECRET).build()), |
||||
"probe-" + UUID.randomUUID(), Clock.systemUTC()); |
||||
EdayunAdapter adapter = new EdayunAdapter( |
||||
new OkHttpTransport("common-ecommerce/1.0.0 (edayun-probe)"), |
||||
new JacksonJsonCodec()); |
||||
// 用适配器的 public 能力入口,但 token 走系统属性注入的取值
|
||||
common.ecommerce.warehouse.capability.WarehouseProductCapable.ProductResult result = |
||||
adapter.createOrUpdate(ctx, product); |
||||
System.out.println("[OK] providerSku=" + result.providerSku() |
||||
+ " status=" + result.status() + " rawStatus=" + result.rawStatus()); |
||||
} catch (RuntimeException e) { |
||||
String msg = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); |
||||
System.out.println("[ERROR] " + e.getClass().getSimpleName() + ": " |
||||
+ (msg.length() <= 800 ? msg : msg.substring(0, 800) + "…")); |
||||
if (e instanceof ChannelException) { |
||||
ChannelException ce = (ChannelException) e; |
||||
System.out.println(" platformCode=" + ce.platformCode() |
||||
+ " retryable=" + ce.retryable()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private static String opt(String name, String fallback) { |
||||
String value = System.getProperty(name, ""); |
||||
if (value == null) { |
||||
return fallback; |
||||
} |
||||
String trimmed = value.trim(); |
||||
return trimmed.isEmpty() ? fallback : trimmed; |
||||
} |
||||
} |
||||
@ -0,0 +1,100 @@
@@ -0,0 +1,100 @@
|
||||
package common.ecommerce.edayun.probe; |
||||
|
||||
import common.ecommerce.edayun.EdayunConstants; |
||||
import common.ecommerce.edayun.auth.EdayunTokenClient; |
||||
import common.ecommerce.edayun.http.EdayunRequestFactory; |
||||
import common.ecommerce.http.JacksonJsonCodec; |
||||
import common.ecommerce.http.OkHttpTransport; |
||||
import common.ecommerce.shared.error.ChannelException; |
||||
import common.ecommerce.shared.spi.AccessToken; |
||||
import org.junit.jupiter.api.Assumptions; |
||||
import org.junit.jupiter.api.Test; |
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty; |
||||
|
||||
import java.time.Clock; |
||||
|
||||
/** |
||||
* 易达云获取 token 的联调探针。 |
||||
* |
||||
* <p>默认跳过,用 {@code -Dedayun.probe=true} 开启;凭据走系统属性, |
||||
* <b>真实值不入库</b>:</p> |
||||
* |
||||
* <pre> |
||||
* mvn -pl warehouse-sdk-edayun -DfailIfNoTests=false \ |
||||
* -Dedayun.probe=true \ |
||||
* -Dedayun.probe.baseUrl=https://test.omniselling.com.cn/saas-service/openapi/microService \
|
||||
* -Dedayun.probe.clientId=你的OMS授权用户名 \ |
||||
* -Dedayun.probe.clientSecret=你的OMS授权密码 \ |
||||
* -Dtest=EdayunTokenProbeTest test |
||||
* </pre> |
||||
* |
||||
* <p>只调只读的 token 接口,不碰任何业务写接口。异常只打印不抛出, |
||||
* 便于一次跑完对照真实报文。</p> |
||||
*/ |
||||
@EnabledIfSystemProperty(named = "edayun.probe", matches = "true") |
||||
class EdayunTokenProbeTest { |
||||
|
||||
private static final String BASE_URL = opt("edayun.probe.baseUrl", EdayunConstants.PR_BASE_URL); |
||||
private static final String CLIENT_ID = System.getProperty("edayun.probe.clientId", ""); |
||||
private static final String CLIENT_SECRET = System.getProperty("edayun.probe.clientSecret", ""); |
||||
|
||||
@Test |
||||
void probeToken() { |
||||
Assumptions.assumeTrue(!CLIENT_ID.trim().isEmpty() && !CLIENT_SECRET.trim().isEmpty(), |
||||
"未提供 -Dedayun.probe.clientId / clientSecret,跳过"); |
||||
|
||||
System.out.println("\n================ edayun / POST /oauth/token ================"); |
||||
System.out.println("[probe] baseUrl=" + BASE_URL |
||||
+ " clientId=" + mask(CLIENT_ID) + " clientSecret=" + mask(CLIENT_SECRET)); |
||||
|
||||
EdayunTokenClient client = new EdayunTokenClient( |
||||
new OkHttpTransport("common-ecommerce/1.0.0 (edayun-probe)"), |
||||
new JacksonJsonCodec(), Clock.systemUTC()); |
||||
|
||||
try { |
||||
AccessToken token = client.fetch(BASE_URL, CLIENT_ID, CLIENT_SECRET); |
||||
System.out.println("[OK] token=" + mask(token.value()) |
||||
+ " tokenType=" + token.tokenType() |
||||
+ " expiresAt=" + token.expiresAt() |
||||
+ " refreshToken=" + (token.refreshToken() == null ? "null" : "present")); |
||||
System.out.println(" 有效期剩余(秒)=" |
||||
+ (token.expiresAt().getEpochSecond() - java.time.Instant.now().getEpochSecond())); |
||||
} catch (RuntimeException e) { |
||||
String msg = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); |
||||
System.out.println("[ERROR] " + e.getClass().getSimpleName() + ": " |
||||
+ (msg.length() <= 600 ? msg : msg.substring(0, 600) + "…")); |
||||
if (e instanceof ChannelException) { |
||||
ChannelException ce = (ChannelException) e; |
||||
System.out.println(" platformCode=" + ce.platformCode() |
||||
+ " retryable=" + ce.retryable()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** 签名算法自检:不联网,确认 MD5(body + "." + appSecret) 的低 8 位形态。 */ |
||||
@Test |
||||
void probeSignatureShape() { |
||||
String secret = System.getProperty("edayun.probe.appSecret", ""); |
||||
Assumptions.assumeTrue(!secret.trim().isEmpty(), |
||||
"未提供 -Dedayun.probe.appSecret,跳过签名自检"); |
||||
String sign = EdayunRequestFactory.sign("{\"a\":1}", secret); |
||||
System.out.println("[sign] MD5(body + \".\" + appSecret) = " + sign |
||||
+ " (长度应为 32 的小写十六进制)"); |
||||
} |
||||
|
||||
private static String mask(String v) { |
||||
if (v == null || v.length() <= 6) { |
||||
return "***"; |
||||
} |
||||
return v.substring(0, 4) + "***" + v.substring(v.length() - 2); |
||||
} |
||||
|
||||
private static String opt(String name, String fallback) { |
||||
String value = System.getProperty(name, ""); |
||||
if (value == null) { |
||||
return fallback; |
||||
} |
||||
String trimmed = value.trim(); |
||||
return trimmed.isEmpty() ? fallback : trimmed; |
||||
} |
||||
} |
||||
Loading…
Reference in new issue