diff --git a/docs-warehouse/edayun/README.md b/docs-warehouse/edayun/README.md
index e497d31..3a96829 100644
--- a/docs-warehouse/edayun/README.md
+++ b/docs-warehouse/edayun/README.md
@@ -15,6 +15,11 @@
| 取消订单 | ✅ 已对接(`POST /webApi/order/v1/cancelOrder`) |
| 交易明细(账户流水) | ✅ 已对接(`POST /webApi/accountFlow/list`) |
| 订单费用明细 | ✅ 已对接(`POST /webApi/order/cost/v1/selectOrderCostInfoList`) |
+| 仓租费用明细 | ✅ 已对接(`POST /webApi/order/cost/v1/selectUserRentDetailList`) |
+| 费用试算(预估) | ✅ 已对接(`POST /webApi/estimate/v1/trial`) |
+| 库存查询 | ✅ 已对接(`POST /webApi/userSkuStock/v1/queryInventory`) |
+| 创建 / 编辑自发入库单 | ✅ 已对接(`POST /webApi/entryInfo/v1/saveEntrySpontaneousOrder`) |
+| 查询入库单 / 入库状态 | ✅ 已对接(`POST /webApi/entryInfo/v1/selectEntrySkuGoodsDetail`) |
| 其它业务接口 | ⬜ 等文档 |
| 回调 | ⬜ 等文档 |
| 真机验证 | ⬜ 等测试环境 |
@@ -415,6 +420,406 @@ POST /webApi/order/cost/v1/selectOrderCostInfoList → List 与上面两个的区别:{@link #settlements} 是账户流水,{@link #orderCosts}
+ * 按订单拆费用,本方法只出仓储费。统一模型只带金额 + 计费日 + SKU,
+ * 租期天数 / 计费体积等仓租专有口径不进 {@link BillingDocument}。 默认不支持——只有提供该接口的仓才覆盖。 与 {@link #orderCosts} 不同:那个按订单拆尾程 / 操作费,这个只出仓储费。
+ * 只读,不走幂等。
一次调用直接发布,不走「先存草稿再发布」两步——文档里发布是保存的一部分。 + * 快递类(海快 / 空运 / 快递)发布时仓方还要求 {@code shipCompany + waybill}, + * 卡车类要求 {@code estimatedDepartureTime},标准模型没有这几个字段, + * 缺了由仓方报错,不在本地编造。
+ */ + @Override + public InboundReceipt create(WarehouseContext ctx, InboundCommand cmd) { + EdayunInboundDtos.SaveEntryRequest body = EdayunInboundMapper.toRequest( + cmd, EdayunInboundMapper.SAVE_PUBLISH, null, ctx.providerWarehouseId()); + return saveEntry(ctx, body, cmd.inboundRequestNo(), "warehouse.inbound.create"); + } + + /** + * 编辑自发入库单({@code saveType=1})。 + * + * @param inboundRef 仓侧入库单号({@code entryCode}),不是我们的来源单号 + */ + @Override + public void improve(WarehouseContext ctx, String inboundRef, InboundCommand cmd) { + EdayunInboundDtos.SaveEntryRequest body = EdayunInboundMapper.toRequest( + cmd, EdayunInboundMapper.SAVE_UPDATE, inboundRef, ctx.providerWarehouseId()); + saveEntry(ctx, body, cmd.inboundRequestNo(), "warehouse.inbound.improve"); + } + + private InboundReceipt saveEntry(WarehouseContext ctx, EdayunInboundDtos.SaveEntryRequest body, + String inboundRequestNo, String operation) { + HttpResponse resp = send(ctx, EdayunConstants.PATH_INBOUND_SAVE, json.toJson(body), operation); + EdayunInboundDtos.SaveEntryResponse parsed = + json.fromJson(resp.body(), EdayunInboundDtos.SaveEntryResponse.class); + requireSuccess(ctx, parsed == null ? null : parsed.code, + parsed == null ? null : parsed.msg, resp, operation); + String entryCode = parsed.data == null ? null : parsed.data.entryCode; + return InboundReceipt.of(inboundRequestNo, entryCode); + } + + /** + * 查入库单({@code POST /webApi/entryInfo/v1/selectEntrySkuGoodsDetail})。 + * + *接口按 SKU 逐行返回,这里翻完所有页合并成一张单。 + * 只认仓侧 {@code entryCode}(REV 单号)——接口不支持按客户单号查。
+ * + *接口只回 SKU 级数据:仓库编码取 OMS 配置的仓,单头状态由各 SKU 状态汇总 + * (还有 SKU 没上架,整单就不算完成)。
+ */ + @Override + public InboundOrder get(WarehouseContext ctx, String inboundRef) { + List宿主按本值做全量 diff,不要指望 {@code updatedAfter} 生效。
+ */ + @Override + public InventorySyncStrategy syncStrategy() { + return InventorySyncStrategy.FULL_PULL_DIFF; + } + + /** + * 库存查询({@code POST /webApi/userSkuStock/v1/queryInventory})。 + * + *一行 = 一个 SKU 在一个仓的汇总。默认只返回总库存大于 0 的数据, + * 需要零库存时由调用方传 {@code includeZeroStock(true)}。
+ * + *分页按页码游标:单页最多 500 条,{@code total} 是总行数。
+ */ + @Override + public Page与 {@link #settlements}(账户流水)、{@link #orderCosts}(按订单拆费用)都不同: + * 这个只出仓储费,按 SKU + 计费日逐条,带租期天数与计费体积。
+ * + *文档要求计费时间窗必填且不超过 3 个月,所以按时间窗 + 翻页拉: + * 一页 200 条,最多 {@link EdayunRentDetailMapper#MAX_PAGES} 页。仍有剩余时 + * 显式失败而不是截断——少算仓租会让对账金额偏小。
+ */ + @Override + public List只做「按包裹」这一种预估——标准模型只带包裹尺寸重量。 + * 真机实测:按 SKU 预估要求 SKU 在仓侧已建档,虚拟包裹在 PR 环境直接 + * 「内部服务器错误」,两者都不适合作为默认路径。
+ * + *响应分 {@code successItems} / {@code failItems},只映射前者; + * 全部失败时返回一个 {@code carriers()} 为空的结果(表示该仓无法承运)。 + * 渠道的无报价原因(如「不支持派送」)只在原报文里,不同步到统一模型。
+ */ + @Override + public List统一模型只有「按包裹」这一种口径,对应易达云的 + * {@code manualInputSwitch = true} + {@code packageDetails}。
+ * + *三处本地定值(标准模型没有对应字段,见 docs-warehouse/edayun/TODO.md):
+ *取 {@code providerWarehouseId};缺省时退回调用方给的 {@code warehouseCodes} 首个。
+ */ + private static void applyWarehouse(EdayunFeeEstimateDtos.TrialRequest req, + String providerWarehouseId, List统一模型的 {@code logisticsServiceCode} / {@code logisticsProductCode} 是仓方口径的字符串; + * 易达云要的是数字 id。非数字视为「不指定渠道」,让仓方返回全部报价—— + * 传一个非数字进去只会让仓方静默查不到。
+ */ + static Long logisticsProductIdOf(FeeEstimateQuery query) { + Long id = numericOrNull(query.logisticsProductCode()); + return id != null ? id : numericOrNull(query.logisticsServiceCode()); + } + + /** + * 试算结果 → 统一结果。 + * + *只取 {@code successItems}:{@code failItems} 是「不支持派送」这类无报价渠道, + * 塞进 {@link FeeEstimateResult.CarrierQuote} 只会得到一堆空金额的假渠道。 + * 全部失败时返回 {@code carriers()} 为空的仓结果——按能力接口约定, + * 这表示「该仓无法承运该包裹」,具体原因({@code errorInfo})只在原报文里。
+ */ + public static FeeEstimateResult toResult(EdayunFeeEstimateDtos.TrialResponse response, + String warehouseCode) { + FeeEstimateResult.Builder builder = FeeEstimateResult.builder() + .sourceProvider(WarehouseProvider.EDAYUN) + .shipOrgWarehouseCode(warehouseCode); + EdayunFeeEstimateDtos.TrialData data = response == null ? null : response.data; + if (data != null && data.successItems != null) { + for (EdayunFeeEstimateDtos.EstimateItem item : data.successItems) { + if (item != null) { + builder.carrier(toQuote(item)); + } + } + } + return builder.build(); + } + + private static FeeEstimateResult.CarrierQuote toQuote(EdayunFeeEstimateDtos.EstimateItem item) { + String currency = hasText(item.currencyCode) ? item.currencyCode.trim() : DEFAULT_CURRENCY; + FeeEstimateResult.CarrierQuote.Builder quote = FeeEstimateResult.CarrierQuote.builder() + // 易达云只给物流产品(渠道)名称,没有独立的承运商字段 + .carrier(item.logisticProductName) + .logisticsServiceCode(item.logisticProductId) + .totalRate(item.estimatedPrice == null ? null + : Money.of(BigDecimal.valueOf(item.estimatedPrice), currency)); + if (item.detailList != null) { + for (EdayunFeeEstimateDtos.DetailItem detail : item.detailList) { + if (detail == null) { + continue; + } + quote.costItem(FeeEstimateResult.CarrierQuote.CostItem.builder() + .costName(detail.billingItemName) + .estimatedCost(detail.estimatedPrice == null ? null + : Money.of(BigDecimal.valueOf(detail.estimatedPrice), + hasText(detail.currencyCode) ? detail.currencyCode.trim() + : currency)) + .build()); + } + } + return quote.build(); + } + + private static Double toDouble(BigDecimal v) { + return v == null ? null : v.doubleValue(); + } + + private static Long numericOrNull(String v) { + if (!hasText(v)) { + return null; + } + try { + return Long.valueOf(v.trim()); + } catch (NumberFormatException e) { + return null; + } + } + + private static String firstOf(List一个接口吃下新增 / 更新 / 发布,靠 {@code saveType} 区分:
+ *只下发统一模型有的三组:{@code basicInfo} / {@code logisticsInfo} / + * {@code cargoInfos}。头程拖车、报关、清关、海外拖车在标准模型里没有对应字段, + * 不下发——这些服务范围本来就由仓方按物流产品判定,缺字段时仓方会报错。
+ */ +public final class EdayunInboundMapper { + + /** 保存类型:新增。 */ + static final int SAVE_NEW = 0; + /** 保存类型:更新。 */ + static final int SAVE_UPDATE = 1; + /** 保存类型:保存并发布。 */ + static final int SAVE_PUBLISH = 2; + + /** 客户单号长度上限。 */ + static final int MAX_CUSTOMER_ORDER_NO = 30; + + private static final double GRAMS_PER_KG = 1000.0; + + private EdayunInboundMapper() { + } + + /** + * 统一命令 → 保存入库单请求。 + * + * @param saveType {@link #SAVE_PUBLISH} / {@link #SAVE_UPDATE} + * @param entryCode 仓侧入库单号;仅更新时必填 + * @param warehouseId 仓方仓标识;数字进 {@code shelfWarehouseId},非数字进 + * {@code shelfWarehouseCode} + */ + public static EdayunInboundDtos.SaveEntryRequest toRequest(InboundCommand cmd, int saveType, + String entryCode, String warehouseId) { + EdayunInboundDtos.SaveEntryRequest req = new EdayunInboundDtos.SaveEntryRequest(); + req.saveType = saveType; + + String customerOrderNo = cmd.inboundRequestNo(); + if (customerOrderNo.length() > MAX_CUSTOMER_ORDER_NO) { + throw new IllegalArgumentException( + "edayun customerOrderNo must not exceed " + MAX_CUSTOMER_ORDER_NO + + " chars, got " + customerOrderNo.length() + ": " + customerOrderNo); + } + req.customerOrderNo = customerOrderNo; + + if (saveType == SAVE_UPDATE) { + if (!hasText(entryCode)) { + throw new IllegalArgumentException( + "edayun updating an inbound order requires entryCode (provider entry no)"); + } + req.entryCode = entryCode.trim(); + } + + req.basicInfo = toBasicInfo(cmd, warehouseId); + req.logisticsInfo = toLogisticsInfo(cmd); + req.cargoInfos = toCargoInfos(cmd.cartons()); + return req; + } + + /** + * 基础信息:仓 id 或编码二选一。 + * + *易达云的 {@code shelfWarehouseId} 是数字、{@code shelfWarehouseCode} 是编码(如 + * {@code USLA})。配成 {@code EDY-WH-1} 这类 OMS 编码时走 code 分支。
+ */ + private static EdayunInboundDtos.BasicInfo toBasicInfo(InboundCommand cmd, String warehouseId) { + EdayunInboundDtos.BasicInfo info = new EdayunInboundDtos.BasicInfo(); + String raw = hasText(cmd.warehouseId()) ? cmd.warehouseId().trim() + : (hasText(warehouseId) ? warehouseId.trim() : null); + Long id = numericOrNull(raw); + if (id != null) { + info.shelfWarehouseId = id; + } else if (raw != null) { + info.shelfWarehouseCode = raw; + } + + info.intShippingMethod = cmd.transportType(); + info.cabinetType = intOrNull(cmd.cabinetType()); + // shippingProductId 是「查询入库物流产品」接口给的 id,标准模型没有对应字段 + return info; + } + + /** + * 物流信息:只填标准模型有的。 + * + *{@code waybill}(快递单号)与 {@code shipCompany}(承运商名)标准模型没有, + * 不下发——快递类发布时仓方会报缺字段,由宿主补。不要把柜号之类的 + * {@code transportOrderNos} 塞进 {@code waybill},那是另一回事。
+ */ + private static EdayunInboundDtos.LogisticsInfo toLogisticsInfo(InboundCommand cmd) { + EdayunInboundDtos.LogisticsInfo info = new EdayunInboundDtos.LogisticsInfo(); + info.cabinetCode = blankToNull(cmd.containerNo()); + // 预计离港 ≈ 预计发运日期;预计到港 ≈ 预计到仓日期(口径待仓方确认) + info.estimatedDepartureTime = millisOf(cmd.predictionShipDate()); + info.estimatedArrivalDate = millisOf(cmd.estimateArriveDate()); + return info; + } + + /** + * 装箱 → 箱货信息。 + * + *统一模型一行是「一个 SKU 在一箱里的数量」,一箱多 SKU 时同一 {@code sid} + * 会拆成多行。这里按 {@code sid}(缺失时用箱码)归并成「一箱 = 一个 cargoInfo + + * 多条 boxSkuInfoList」,与文档结构对齐。
+ * + *{@code cargoInfos} 是必填的,而箱规只有 {@code InboundCarton} 才有—— + * 调用方只给了 SKU 明细时本地拒绝,不凭空编一个箱子。
+ */ + static List一行 = 一个 SKU 的预报 / 清点 / 上架数量。这是目前唯一能拿到入库进度的接口。
+ * + *这个接口只回 SKU 级数据:没有仓、没有时间、没有箱明细、没有单头状态。 + * 所以 {@link InboundOrder} 里这些字段是空的,单头状态由 SKU 状态汇总得到。
+ */ +public final class EdayunInboundQueryMapper { + + /** 单页上限。 */ + static final int MAX_PAGE_SIZE = 1000; + /** 默认页大小(文档写「默认 200 条」)。 */ + static final int DEFAULT_PAGE_SIZE = 200; + + private EdayunInboundQueryMapper() { + } + + /** 查询请求。 */ + public static EdayunInboundQueryDtos.SelectEntrySkuRequest toRequest(String entryCode, int pageNum) { + if (!hasText(entryCode)) { + throw new IllegalArgumentException( + "edayun inbound query requires entryCode (provider REV no);" + + " the endpoint cannot look up by customerOrderNo"); + } + EdayunInboundQueryDtos.SelectEntrySkuRequest req = + new EdayunInboundQueryDtos.SelectEntrySkuRequest(); + req.entryCode = entryCode.trim(); + req.pageNum = pageNum; + req.pageSize = DEFAULT_PAGE_SIZE; + return req; + } + + /** + * 一页 SKU 明细 → 入库单。 + * + *仓库编码用 OMS 配置的仓(接口不回仓);状态取最靠前的那条—— + * 还有 SKU 没上架,整单就不算完成。
+ * + * @param allRows 已翻页合并的全部行 + */ + public static InboundOrder toOrder(String entryCode, List取「最靠前」的状态而不是第一条:顺序按 {@link InboundStatus#code()}, + * 数值小的更靠前。UNKNOWN(0) 会污染结果,所以有可识别状态时忽略它。
+ */ + static InboundStatus headStatusOf(List语义:一行 = 一个 SKU 在一个仓的库存汇总。默认只返回总库存大于 0 的数据。
+ */ +public final class EdayunInventoryMapper { + + /** 单页上限。 */ + static final int MAX_PAGE_SIZE = 500; + + /** SKU 过滤上限。 */ + static final int MAX_SKUS = 100; + + private EdayunInventoryMapper() { + } + + /** + * 统一查询条件 → 库存查询请求。 + * + * @param providerWarehouseId 仓方数字仓 id;为空时不下发 {@code warehouseIdList} + * (仓方按账号下全部仓返回) + */ + public static EdayunInventoryDtos.QueryInventoryRequest toRequest( + InventoryQuery query, String providerWarehouseId, int pageNum) { + EdayunInventoryDtos.QueryInventoryRequest req = + new EdayunInventoryDtos.QueryInventoryRequest(); + req.pageNum = pageNum; + req.pageSize = pageSize(query.pageSize()); + + if (!query.providerSkus().isEmpty()) { + if (query.providerSkus().size() > MAX_SKUS) { + throw new IllegalArgumentException( + "edayun inventory query accepts at most " + MAX_SKUS + " sku codes, got " + + query.providerSkus().size()); + } + req.skuCodeList = new ArrayList文档写明 {@code total} 是响应数据总数(行数),优先用它判断; + * 缺失时退回「本页是否满页」。
+ */ + static String nextCursor(Long total, int currentPage, int pageSize, int fetched) { + boolean more = total != null + ? (long) currentPage * pageSize < total + : fetched >= pageSize; + return more ? String.valueOf(currentPage + 1) : null; + } + + /** 游标是字符串化的页码。 */ + static int pageNumber(String cursor) { + if (!hasText(cursor)) { + return 1; + } + try { + int v = Integer.parseInt(cursor.trim()); + return v > 0 ? v : 1; + } catch (NumberFormatException e) { + return 1; + } + } + + /** 每页条数:默认 100,上限 500。 */ + static int pageSize(int requested) { + if (requested <= 0) { + return 100; + } + return Math.min(requested, MAX_PAGE_SIZE); + } + + /** 仓方仓 id 是数字;非数字直接拒绝,避免仓侧静默查不到。 */ + static Long warehouseIdOf(String providerWarehouseId) { + if (!hasText(providerWarehouseId)) { + return null; + } + try { + return Long.valueOf(providerWarehouseId.trim()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + "edayun warehouseIdList must be numeric, got: " + providerWarehouseId + + " (configure the provider warehouse id as edayun's numeric warehouse id)"); + } + } + + private static int intOf(Integer v) { + return v == null ? 0 : v; + } + + private static String firstNonBlank(String a, String b) { + if (hasText(a)) { + return a.trim(); + } + return hasText(b) ? b.trim() : null; + } + + private static String blankToNull(String v) { + return hasText(v) ? v.trim() : null; + } + + private static boolean hasText(String v) { + return v != null && !v.trim().isEmpty(); + } +} diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunOrderCostMapper.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunOrderCostMapper.java index b272265..3a673de 100644 --- a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunOrderCostMapper.java +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunOrderCostMapper.java @@ -9,7 +9,6 @@ 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; @@ -52,12 +51,8 @@ public final class EdayunOrderCostMapper { 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"); - } + EdayunQueryWindows.requireWithinMonths(query.settledAfter(), query.settledBefore(), + MAX_RANGE_MONTHS, "order cost"); req.beginBillingTime = query.settledAfter().toEpochMilli(); req.endBillingTime = query.settledBefore().toEpochMilli(); } else if (!hasText(orderNo)) { @@ -155,12 +150,17 @@ public final class EdayunOrderCostMapper { * *易达云的名称是中文(如「尾程-出库处理费」),按关键字推断; * 认不出返回 null,不猜——对账时宁可不分类,也不能分错。
+ * + *先剥掉「尾程-」这类前缀再判断:真机返回的名称为 + * 「尾程-产品贴标费」「尾程-出库包装费」,前缀只是模块归属, + * 不剥会把贴标、包装一律误判成尾程运费。
*/ static WarehouseFeeType feeTypeOf(String name) { if (!hasText(name)) { return null; } - String n = name.toLowerCase(); + String n = stripModulePrefix(name.trim()).toLowerCase(); + if (n.contains("仓储") || n.contains("storage") || n.contains("仓租")) { return WarehouseFeeType.STORAGE; } @@ -168,17 +168,41 @@ public final class EdayunOrderCostMapper { || n.contains("操作")) { return WarehouseFeeType.OPERATION; } + // 增值类先于尾程判断:「尾程-贴标」是增值服务,不是运费 + if (n.contains("增值") || n.contains("service") || n.contains("服务") + || n.contains("贴标") || n.contains("label") + || n.contains("打包") || n.contains("包装") || n.contains("pack")) { + return WarehouseFeeType.VALUE_ADDED; + } if (n.contains("尾程") || n.contains("运费") || n.contains("freight") - || n.contains("delivery") || n.contains("燃油") || n.contains("附加费")) { + || n.contains("delivery") || n.contains("派送") || n.contains("快递") + || 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; } + /** + * 剥掉模块前缀,如 {@code 尾程-} / {@code 头程-}。 + * + *只剥第一个连字符前的两三个字,别把「尾程-偏远附加费」里的语义也剥了。
+ */ + private static String stripModulePrefix(String name) { + int dash = name.indexOf('-'); + if (dash <= 0) { + dash = name.indexOf('-'); + } + if (dash <= 0) { + return name; + } + String prefix = name.substring(0, dash); + if (prefix.length() <= 3 && (prefix.endsWith("程") || prefix.startsWith("尾") + || prefix.startsWith("头"))) { + return name.substring(dash + 1); + } + return name; + } + private static String defaultCurrency(EdayunOrderCostDtos.OrderCostRow row) { return "USD"; } diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunQueryWindows.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunQueryWindows.java new file mode 100644 index 0000000..82730f1 --- /dev/null +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunQueryWindows.java @@ -0,0 +1,63 @@ +package common.ecommerce.edayun.adapter; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; + +/** + * 易达云费用类查询的时间窗约束。 + * + *易达云各费用接口都限制「最大查询 3 个月」。本地只挡明显超限, + * 精确阈值交给仓方判定——真机实测(2026-11-13,PR 环境)边界不是自然月也不是 + * 固定天数:
+ * + *+ * 6/1 ~ 10/1 通过 6/2 ~ 10/2 拒绝 + * 7/2 ~ 10/31 通过 7/1 ~ 10/31 拒绝 + * 6/1 ~ 11/1 拒绝「计费时间范围不能超过3个月」 + *+ * + *
按「自然月加 N」严格算会把上面通过的那些合法窗口挡在本地, + * 所以这里放宽到 {@code months + 1} 个月:既拦住「一次拉一年」这类明显错误, + * 又不会误伤 3~4 个月之间的窗口。真正超限时仓方返回 + * {@code code=500, msg=计费时间范围不能超过3个月},由适配器原样抛出。
+ */ +final class EdayunQueryWindows { + + /** + * 本地允许的余量(月)。3 个月 + 1 个月 = 4 个月。 + * + *实测存在 3~4 个月之间被仓方接受的窗口,余量不能少于 1 个月。
+ */ + private static final int LOCAL_SLACK_MONTHS = 1; + + /** 支持的月数上限;超出说明调用方传错了常量。 */ + private static final int MAX_GUARD_MONTHS = 12; + + private EdayunQueryWindows() { + } + + /** + * 校验时间窗没有明显超过 {@code months} 个月。 + * + *时间点按 UTC 换算成日期比较——仓方按自己的时区解释毫秒时间戳, + * 这里只做保守的日期级判断。
+ * + * @param what 用于报错的业务名,如 {@code "order cost"} / {@code "rent detail"} + * @throws IllegalArgumentException 明显超出上限 + */ + static void requireWithinMonths(Instant start, Instant end, int months, String what) { + if (months <= 0 || months > MAX_GUARD_MONTHS) { + throw new IllegalArgumentException( + "edayun " + what + " window guard configured with unsupported months: " + months); + } + ZonedDateTime from = start.atZone(ZoneOffset.UTC); + ZonedDateTime to = end.atZone(ZoneOffset.UTC); + if (from.plusMonths(months + LOCAL_SLACK_MONTHS).isBefore(to)) { + throw new IllegalArgumentException( + "edayun " + what + " query range must not exceed " + months + " months, got " + + from.toLocalDate() + " ~ " + to.toLocalDate() + + "; split the window and query again"); + } + } +} diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunRentDetailMapper.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunRentDetailMapper.java new file mode 100644 index 0000000..2d14bee --- /dev/null +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunRentDetailMapper.java @@ -0,0 +1,192 @@ +package common.ecommerce.edayun.adapter; + +import common.ecommerce.edayun.dto.EdayunRentDetailDtos; +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.Collections; +import java.util.List; + +/** + * 易达云仓租费用明细映射 + * ({@code POST /webApi/order/cost/v1/selectUserRentDetailList})。 + * + *与另外两个费用接口的区别:
+ *金额口径:{@code rentPrice} 是原价减折扣后的实收;缺失时用 + * {@code originalPrice - discountPrice} 兜底,两者都没有才记 0。
+ */ +public final class EdayunRentDetailMapper { + + /** 计费时间窗上限 3 个月。 */ + static final int MAX_RANGE_MONTHS = 3; + + /** 单页上限。 */ + static final int MAX_PAGE_SIZE = 200; + + /** + * 翻页上限:{@value #MAX_PAGES} 页 × {@value #MAX_PAGE_SIZE} 条。 + * + *仓租按 SKU + 天出账,3 个月窗口下条数可能上万;这里设上限防止一次拉爆, + * 超出时适配器显式失败而不是截断——见 docs-warehouse/edayun/TODO.md。
+ */ + static final int MAX_PAGES = 20; + + /** 一次拉取的最大行数;超过即失败。 */ + static final int MAX_ROWS = MAX_PAGES * MAX_PAGE_SIZE; + + private EdayunRentDetailMapper() { + } + + /** + * 统一查询条件 → 仓租明细查询请求。 + * + *文档里 {@code billDateBegin} / {@code billDateEnd} 都是必填,所以没有 + * 时间窗时本地直接拒绝——仓租没有按单号单独查的口径。
+ * + * @param providerWarehouseId 仓方仓 id;非空时作为 {@code warehouseIds} 唯一元素 + */ + public static EdayunRentDetailDtos.SelectRentDetailRequest toRequest( + FeeQuery query, String providerWarehouseId) { + if (!query.hasSettledRange()) { + throw new IllegalArgumentException( + "edayun rent detail query requires a billing time range (billDateBegin/End);" + + " refusing to pull all rents"); + } + requireStorageOnly(query); + + EdayunRentDetailDtos.SelectRentDetailRequest req = + new EdayunRentDetailDtos.SelectRentDetailRequest(); + req.pageNum = 1; + req.pageSize = MAX_PAGE_SIZE; + + EdayunQueryWindows.requireWithinMonths(query.settledAfter(), query.settledBefore(), + MAX_RANGE_MONTHS, "rent detail"); + req.billDateBegin = query.settledAfter().toEpochMilli(); + req.billDateEnd = query.settledBefore().toEpochMilli(); + + Long warehouseId = warehouseIdOf(providerWarehouseId); + req.warehouseIds = warehouseId == null ? null + : Collections.singletonList(warehouseId); + + String businessNum = firstNonBlank(query.externalOrderNo(), query.saleOrderNo()); + req.businessNums = businessNum == null ? null + : Collections.singletonList(businessNum); + + // 仓租是 SKU 维度;只给条码时用条码查,别把条码当 SKU 传 + req.skuCodes = hasText(query.providerSku()) + ? Collections.singletonList(query.providerSku().trim()) : null; + + return req; + } + + /** + * 本接口只出仓租。 + * + *宿主若明确要求别的费用类型,说明用错了接口——显式拒绝而不是返回空集合, + * 否则调用方会误以为「该期间没有作业费」。
+ */ + private static void requireStorageOnly(FeeQuery query) { + if (query.costType() != null && query.costType() != WarehouseFeeType.STORAGE) { + throw new IllegalArgumentException( + "edayun rent detail query only returns STORAGE cost, got " + query.costType() + + "; use settlements() or orderCosts() for other fee types"); + } + if (query.hasDateRange()) { + throw new IllegalArgumentException( + "edayun rent detail query uses settledAfter/settledBefore (billDateBegin/End)," + + " not snapshot date range"); + } + } + + /** 仓方仓 id 是数字;非数字直接拒绝,避免仓侧静默查不到。 */ + static Long warehouseIdOf(String providerWarehouseId) { + if (!hasText(providerWarehouseId)) { + return null; + } + try { + return Long.valueOf(providerWarehouseId.trim()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + "edayun warehouseIds must be numeric, got: " + providerWarehouseId + + " (configure the provider warehouse id as edayun's numeric warehouse id)"); + } + } + + /** + * 一行仓租明细 → 一条 {@link BillingDocument}。 + * + *仓租天然就是仓储费,费用类型固定 {@link WarehouseFeeType#STORAGE}, + * 不按 {@code billingName} 关键字猜。
+ */ + public static BillingDocument toDocument(EdayunRentDetailDtos.RentDetailRow row, + String warehouseCode) { + String currency = hasText(row.currencyCode) ? row.currencyCode.trim() : "USD"; + return BillingDocument.builder() + .warehouseCode(firstNonBlank(row.warehouseName, warehouseCode)) + .sourceProvider(WarehouseProvider.EDAYUN) + .documentNo(firstNonBlank(row.businessNum, row.orderNo)) + // billingId 是计费明细唯一标识,可作为重复拉取的去重键 + .serialNumber(row.billingId == null ? null : String.valueOf(row.billingId)) + .feeName(firstNonBlank(row.billingName, "仓租")) + .feeType(WarehouseFeeType.STORAGE) + .estimated(false) + .settledAt(row.billingDate == null ? null : Instant.ofEpochMilli(row.billingDate)) + .amount(moneyOf(row, currency)) + .saleOrderNo(row.orderNo) + .providerSku(row.skuCode) + .build(); + } + + /** 批量映射,跳过 null 行。 */ + public static List一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构。
+ * + *三种预估方式(优先级从高到低):
+ *响应把渠道分成 {@code successItems}(有报价)与 {@code failItems}(不支持派送), + * 每个失败项也带 {@code errorMessage}。
+ */ +public final class EdayunFeeEstimateDtos { + + private EdayunFeeEstimateDtos() { + } + + /** 试算请求。 */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static final class TrialRequest { + + /** 出货仓库 id;与 {@link #warehouseCode} 必填一个。 */ + public Long warehouseId; + /** 出货仓库编码;与 {@link #warehouseId} 必填一个。 */ + public String warehouseCode; + /** 目的国二字码;缺省用仓库所在国。 */ + public String endCountryCode; + /** 城市;部分物流(如澳洲 Allied)必须给城市才能报价。 */ + public String city; + /** 目的地邮编。必填。 */ + public String endZipcode; + + /** true 按包裹预估 / false 按 SKU 预估。必填。 */ + public Boolean manualInputSwitch; + /** 货物类型;按包裹预估时必填。 */ + public String estimatedGoodsType; + + /** 按 SKU 预估时的商品集合。 */ + public List自发入库单 = 卖家自己备货、自己找代理送到 EDA 海外仓,物流信息由卖家维护。 + * 一个接口承担新增 / 更新 / 保存并发布,靠 {@code saveType} 区分。
+ * + *只映射统一模型能提供的部分:{@code basicInfo} / {@code logisticsInfo} / {@code cargoInfos}。 + * 头程拖车、报关、清关、海外拖车四组({@code domesticTrailerInfo} 等)在统一模型里 + * 没有对应字段,不下发——需要时由仓方报错,由宿主走人工。
+ */ +public final class EdayunInboundDtos { + + private EdayunInboundDtos() { + } + + /** 保存入库单请求。 */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static final class SaveEntryRequest { + + /** 保存类型:0 新增 / 1 更新 / 2 保存并发布。默认新增。 */ + public Integer saveType; + /** 入库单号;{@code saveType=1} 更新时必填。 */ + public String entryCode; + /** 客户单号,≤30。必填。 */ + public String customerOrderNo; + + public BasicInfo basicInfo; + public LogisticsInfo logisticsInfo; + public List一行 = 一个 SKU 在入库单里的预报 / 清点 / 上架数量与状态。 + * 这是目前唯一能拿到入库进度的接口——创建接口只回 {@code entryCode},不带状态。
+ */ +public final class EdayunInboundQueryDtos { + + private EdayunInboundQueryDtos() { + } + + /** 查询请求。 */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static final class SelectEntrySkuRequest { + + /** 入库单号(仓侧 REV 单号)。必填。 */ + public String entryCode; + /** 每页条数,默认 200,最大 1000。必填。 */ + public Integer pageSize; + /** 页码,从 1 开始。必填。 */ + public Integer pageNum; + } + + /** 查询响应。 */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static final class SelectEntrySkuResponse { + /** 总行数。 */ + public Long total; + public Integer code; + public String msg; + public String traceId; + public List一行 = 一个 SKU 在一个仓的库存汇总。默认只返回总库存大于 0 的数据, + * 单页最多 500 条。
+ */ +public final class EdayunInventoryDtos { + + private EdayunInventoryDtos() { + } + + /** 查询请求。 */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static final class QueryInventoryRequest { + + /** 页码,从 1 开始。必填。 */ + public Integer pageNum; + /** 每页条数,最大 500。必填。 */ + public Integer pageSize; + + /** SKU 编码列表,最多 100 个。 */ + public List不传时仓方默认 {@code true};要零库存数据时显式传 {@code false}。
+ */ + public Boolean totalStockGreaterThanZero; + } + + /** 查询响应。 */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static final class QueryInventoryResponse { + /** 响应数据总数(行数)。 */ + public Long total; + public List一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构。
+ * + *与「订单费用明细」({@code selectOrderCostInfoList})的区别:那个按订单 + * 拆尾程 / 操作费等费用;这个是仓租——按 SKU + 计费日逐日累计, + * 带租期天数、库存件数、计费体积与单价。
+ */ +public final class EdayunRentDetailDtos { + + private EdayunRentDetailDtos() { + } + + /** 查询请求。 */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public static final class SelectRentDetailRequest { + + /** 页码,从 1 开始。必填。 */ + public Integer pageNum; + /** 每页条数,最大 200。必填。 */ + public Integer pageSize; + + /** 计费时间开始(毫秒)。必填,最大查询 3 个月。 */ + public Long billDateBegin; + /** 计费时间结束(毫秒)。必填。 */ + public Long billDateEnd; + + /** 仓库 id 列表,最大 20 个。 */ + public List只有一个是实测确认的:{@code 4 = 已上架}(文档响应示例)。 + * 完整码表易达云还没给,所以其余先按 {@code statusName} 中文名兜底推断 + * (与费用类型一样的关键字推断思路),认不出归 {@link InboundStatus#UNKNOWN} + * 并保留原文,不猜。
+ * + *拿到码表后请把关键字兜底换成精确码值——中文名可能随语言 / 配置变化。
+ */ +public enum EdayunInboundSkuStatus { + + /** 4 已上架(文档示例)。 */ + STORED(4, InboundStatus.COMPLETED), + /** 无法识别。 */ + UNKNOWN(null, InboundStatus.UNKNOWN); + + private final Integer rawCode; + private final InboundStatus core; + + EdayunInboundSkuStatus(Integer rawCode, InboundStatus core) { + this.rawCode = rawCode; + this.core = core; + } + + /** 仓方状态码;null 表示无法识别。 */ + public Integer rawCode() { + return rawCode; + } + + public InboundStatus toCore() { + return core; + } + + /** + * 状态码 + 中文名 → 底层状态。 + * + *码值优先;认不出码时按中文名兜底;两者都认不出返回 {@code UNKNOWN}。
+ */ + public static InboundStatus toCore(Integer status, String statusName) { + if (status != null) { + for (EdayunInboundSkuStatus v : values()) { + if (status.equals(v.rawCode)) { + return v.core; + } + } + } + return byName(statusName); + } + + /** + * 按中文名兜底。 + * + *顺序有意义:「已取消」要在「已」之前判,避免被当成完成。
+ */ + static InboundStatus byName(String statusName) { + if (statusName == null || statusName.trim().isEmpty()) { + return InboundStatus.UNKNOWN; + } + String n = statusName.trim(); + if (n.contains("取消") || n.contains("作废") || n.contains("驳回")) { + return InboundStatus.CANCELLED; + } + if (n.contains("上架中")) { + return InboundStatus.STORING; + } + if (n.contains("已上架") || n.contains("完成")) { + return InboundStatus.COMPLETED; + } + if (n.contains("清点") || n.contains("收货") || n.contains("卸柜") || n.contains("签收")) { + return InboundStatus.RECEIVING; + } + if (n.contains("在途") || n.contains("运输") || n.contains("离港") + || n.contains("到港") || n.contains("发出")) { + return InboundStatus.IN_TRANSIT; + } + if (n.contains("待") || n.contains("预报") || n.contains("草稿")) { + return InboundStatus.PENDING_SHIPMENT; + } + return InboundStatus.UNKNOWN; + } +} diff --git a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java index 73a33fc..27f2fd5 100644 --- a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java +++ b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java @@ -93,7 +93,7 @@ class EdayunAdapterTest { common.ecommerce.warehouse.model.OutboundRef.ofRequestNo(""))); } - /** 未声明能力(如库存查询)时门面显式拒绝,不返回空列表。 */ + /** 未声明能力(如退货)时门面显式拒绝,不返回空列表。 */ @Test void unimplementedCapabilityIsRejected() { WarehouseSdk sdk = sdk(); @@ -102,9 +102,7 @@ class EdayunAdapterTest { common.ecommerce.shared.spi.ChannelSecret.builder().appSecret("k").build()); assertThrows(WarehouseUnsupportedCapabilityException.class, - () -> sdk.warehouses(WH, conn).inventory().query( - common.ecommerce.warehouse.model.InventoryQuery.builder() - .pageSize(1).build())); + () -> sdk.warehouses(WH, conn).returns().query(null)); } /** 能力矩阵查询本身可用(不触发真实 API)。 */ @@ -112,7 +110,7 @@ class EdayunAdapterTest { void capabilityQueryIsOffline() { EdayunAdapter adapter = new EdayunAdapter(RecordingTransport.create(), new JacksonJsonCodec()); - assertTrue(!adapter.capabilities().contains(WarehouseCapability.INBOUND)); + assertTrue(adapter.capabilities().contains(WarehouseCapability.INBOUND)); assertTrue(!adapter.capabilities().contains(WarehouseCapability.TRACKING)); } } diff --git a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunFeeEstimateTest.java b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunFeeEstimateTest.java new file mode 100644 index 0000000..bc98290 --- /dev/null +++ b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunFeeEstimateTest.java @@ -0,0 +1,248 @@ +package common.ecommerce.edayun.adapter; + +import common.ecommerce.edayun.dto.EdayunFeeEstimateDtos; +import common.ecommerce.shared.support.Money; +import common.ecommerce.warehouse.enums.WarehouseCapability; +import common.ecommerce.warehouse.model.FeeEstimateQuery; +import common.ecommerce.warehouse.model.FeeEstimateResult; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +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 /webApi/estimate/v1/trial})映射。 + * + *重点:仓 id/编码二选一、包裹模式固定下发、只映射 successItems、 + * 响应重量是 kg 而请求是 g。
+ */ +class EdayunFeeEstimateTest { + + private static FeeEstimateQuery query() { + return FeeEstimateQuery.builder() + .lengthCm(new BigDecimal("22")) + .widthCm(new BigDecimal("22")) + .heightCm(new BigDecimal("22")) + .weightGrams(new BigDecimal("1000")) + .receiveCountry("US") + .receivePostal("91761") + .logisticsServiceCode("80") + .build(); + } + + // ------------------------------------------------------------ 请求 + + @Test + void numericWarehouseIdGoesToWarehouseId() { + EdayunFeeEstimateDtos.TrialRequest req = + EdayunFeeEstimateMapper.toRequest(query(), "2"); + + assertEquals(Long.valueOf(2L), req.warehouseId); + assertNull(req.warehouseCode); + assertEquals("91761", req.endZipcode); + assertEquals("US", req.endCountryCode); + assertEquals(Boolean.TRUE, req.manualInputSwitch); + assertEquals("GENERAL_CARGO", req.estimatedGoodsType); + } + + /** 非数字仓 id 走 warehouseCode(文档说两者必填一个)。 */ + @Test + void nonNumericWarehouseGoesToWarehouseCode() { + EdayunFeeEstimateDtos.TrialRequest req = + EdayunFeeEstimateMapper.toRequest(query(), "USLA"); + + assertEquals("USLA", req.warehouseCode); + assertNull(req.warehouseId); + } + + /** providerWarehouseId 缺省时退回调用方给的 warehouseCode。 */ + @Test + void fallsBackToQueryWarehouseCode() { + FeeEstimateQuery q = FeeEstimateQuery.builder() + .warehouseCode("USLA") + .lengthCm(BigDecimal.ONE).widthCm(BigDecimal.ONE).heightCm(BigDecimal.ONE) + .weightGrams(BigDecimal.ONE) + .receiveCountry("US").receivePostal("91761") + .logisticsServiceCode("80") + .build(); + + EdayunFeeEstimateDtos.TrialRequest req = EdayunFeeEstimateMapper.toRequest(q, null); + + assertEquals("USLA", req.warehouseCode); + } + + @Test + void withoutAnyWarehouseIsRejected() { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunFeeEstimateMapper.toRequest(query(), null)); + + assertTrue(ex.getMessage().contains("requires a warehouse"), ex.getMessage()); + } + + /** 请求里的重量是克(实测 1000g → 响应 weight 1.000kg)。 */ + @Test + void packageUsesCentimetersAndGrams() { + EdayunFeeEstimateDtos.TrialRequest req = + EdayunFeeEstimateMapper.toRequest(query(), "2"); + + assertEquals(1, req.packageDetails.size()); + EdayunFeeEstimateDtos.PackageItem pkg = req.packageDetails.get(0); + assertEquals(Double.valueOf(22.0), pkg.length); + assertEquals(Double.valueOf(1000.0), pkg.weight); + } + + /** 物流产品 id 只认数字;非数字当作「不指定渠道」。 */ + @Test + void logisticsProductIdOnlyAcceptsNumeric() { + assertEquals(Long.valueOf(80L), EdayunFeeEstimateMapper.logisticsProductIdOf(query())); + + FeeEstimateQuery nonNumeric = FeeEstimateQuery.builder() + .lengthCm(BigDecimal.ONE).widthCm(BigDecimal.ONE).heightCm(BigDecimal.ONE) + .weightGrams(BigDecimal.ONE) + .receiveCountry("US").receivePostal("91761") + .logisticsServiceCode("US_ECONOMY") + .build(); + assertNull(EdayunFeeEstimateMapper.logisticsProductIdOf(nonNumeric)); + } + + @Test + void returnsEmptyListWhenNothingChosen() { + EdayunFeeEstimateDtos.TrialRequest req = + EdayunFeeEstimateMapper.toRequest(query(), "2"); + assertEquals(java.util.Collections.singletonList(80L), req.logisticsProductIds); + } + + /** 没指定渠道时不下发 logisticsProductIds,让仓方返回全部报价。 */ + @Test + void omitsLogisticsProductIdsWhenNotNumeric() { + FeeEstimateQuery q = FeeEstimateQuery.builder() + .lengthCm(BigDecimal.ONE).widthCm(BigDecimal.ONE).heightCm(BigDecimal.ONE) + .weightGrams(BigDecimal.ONE) + .receiveCountry("US").receivePostal("91761") + .logisticsServiceCode("US_ECONOMY") + .build(); + + assertNull(EdayunFeeEstimateMapper.toRequest(q, "2").logisticsProductIds); + } + + // ------------------------------------------------------------ 响应 + + private static EdayunFeeEstimateDtos.TrialResponse response() { + EdayunFeeEstimateDtos.DetailItem freight = new EdayunFeeEstimateDtos.DetailItem(); + freight.billingId = "1604101111532494888"; + freight.billingItemName = "尾程配送费"; + freight.estimatedPrice = 3.315; + freight.preferentialEstimatedPrice = 0.0; + freight.currencyCode = "USD"; + + EdayunFeeEstimateDtos.DetailItem check = new EdayunFeeEstimateDtos.DetailItem(); + check.billingId = "1697455503566127105"; + check.billingItemName = "安全检查费"; + check.estimatedPrice = 2.0; + check.currencyCode = "USD"; + + EdayunFeeEstimateDtos.EstimateItem ok = new EdayunFeeEstimateDtos.EstimateItem(); + ok.logisticProductId = "80"; + ok.logisticProductName = "美国经济派送"; + ok.timeLimit = "2-8 工作日"; + ok.weight = 1.0; + ok.currencyCode = "USD"; + ok.estimatedPrice = 5.315; + ok.detailList = java.util.Arrays.asList(freight, check); + ok.errorCode = "SUCCESS"; + + EdayunFeeEstimateDtos.EstimateItem fail = new EdayunFeeEstimateDtos.EstimateItem(); + fail.logisticProductId = "82"; + fail.logisticProductName = "美国标准派送"; + fail.errorMessage = "不支持派送"; + + EdayunFeeEstimateDtos.TrialData data = new EdayunFeeEstimateDtos.TrialData(); + data.successItems = java.util.Collections.singletonList(ok); + data.failItems = java.util.Collections.singletonList(fail); + data.showError = Boolean.FALSE; + + EdayunFeeEstimateDtos.TrialResponse resp = new EdayunFeeEstimateDtos.TrialResponse(); + resp.code = 200; + resp.msg = "操作成功"; + resp.data = data; + return resp; + } + + @Test + void mapsSuccessItemsToQuotes() { + FeeEstimateResult result = EdayunFeeEstimateMapper.toResult(response(), "EDY-WH"); + + assertEquals(1, result.carriers().size()); + FeeEstimateResult.CarrierQuote quote = result.carriers().get(0); + assertEquals("美国经济派送", quote.carrier()); + assertEquals("80", quote.logisticsServiceCode()); + assertEquals(new BigDecimal("5.315"), quote.totalRate().amount()); + assertEquals("USD", quote.totalRate().currencyCode()); + assertEquals(2, quote.costItems().size()); + assertEquals("尾程配送费", quote.costItems().get(0).costName()); + assertEquals(new BigDecimal("3.315"), quote.costItems().get(0).estimatedCost().amount()); + } + + /** 失败渠道不进结果——它们没有任何金额,混进去就是假渠道。 */ + @Test + void failItemsAreDropped() { + FeeEstimateResult result = EdayunFeeEstimateMapper.toResult(response(), "W"); + + assertEquals(1, result.carriers().size()); + for (FeeEstimateResult.CarrierQuote q : result.carriers()) { + assertTrue(!"美国标准派送".equals(q.carrier())); + } + } + + /** 全部失败时返回空渠道列表,不抛异常(能力接口约定:表示该仓无法承运)。 */ + @Test + void allFailedYieldsEmptyCarriers() { + EdayunFeeEstimateDtos.TrialResponse resp = response(); + resp.data.successItems = java.util.Collections.emptyList(); + resp.data.showError = Boolean.TRUE; + resp.data.errorInfo = "没有物流产品符合预估!"; + + FeeEstimateResult result = EdayunFeeEstimateMapper.toResult(resp, "W"); + + assertTrue(result.carriers().isEmpty()); + assertEquals("W", result.shipOrgWarehouseCode()); + } + + @Test + void handlesNullData() { + EdayunFeeEstimateDtos.TrialResponse resp = new EdayunFeeEstimateDtos.TrialResponse(); + + List重点:只认 entryCode、单头状态由 SKU 状态汇总、状态码表未确认时的中文名兜底。
+ */ +class EdayunInboundQueryTest { + + private static EdayunInboundQueryDtos.EntrySkuRow row(String sku, int forecast, + int checked, int shelves, + Integer status, String statusName) { + EdayunInboundQueryDtos.EntrySkuRow row = new EdayunInboundQueryDtos.EntrySkuRow(); + row.skuCode = sku; + row.skuName = "候杰测试" + sku; + row.forecastQuantity = forecast; + row.actualCheckedQuantity = checked; + row.shelvesQuantity = shelves; + row.status = status; + row.statusName = statusName; + row.entryCode = "REV24050738176"; + row.forecastWeight = 12100.0; + row.firstWeight = 12.1; + row.forecastCargoSize = "115.3*79.8*36"; + return row; + } + + // ------------------------------------------------------------ 请求 + + @Test + void mapsEntryCodeAndPaging() { + EdayunInboundQueryDtos.SelectEntrySkuRequest req = + EdayunInboundQueryMapper.toRequest("REV24050738176", 1); + + assertEquals("REV24050738176", req.entryCode); + assertEquals(Integer.valueOf(1), req.pageNum); + assertEquals(Integer.valueOf(200), req.pageSize); + } + + /** 接口只能按仓侧 entryCode 查,没有单号就别发。 */ + @Test + void blankEntryCodeIsRejected() { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunInboundQueryMapper.toRequest(" ", 1)); + + assertTrue(ex.getMessage().contains("entryCode"), ex.getMessage()); + } + + // ------------------------------------------------------------ 状态 + + /** 码 4 = 已上架(文档示例)。 */ + @Test + void code4IsCompleted() { + assertEquals(InboundStatus.COMPLETED, + EdayunInboundSkuStatus.toCore(4, "已上架")); + } + + /** 码表未给的部分按中文名兜底。 */ + @Test + void unknownCodeFallsBackToChineseName() { + assertEquals(InboundStatus.RECEIVING, EdayunInboundSkuStatus.toCore(99, "清点中")); + assertEquals(InboundStatus.IN_TRANSIT, EdayunInboundSkuStatus.toCore(99, "在途")); + assertEquals(InboundStatus.STORING, EdayunInboundSkuStatus.toCore(99, "上架中")); + assertEquals(InboundStatus.CANCELLED, EdayunInboundSkuStatus.toCore(99, "已取消")); + } + + /** 认不出就是 UNKNOWN,不猜。 */ + @Test + void unrecognizedStatusIsUnknown() { + assertEquals(InboundStatus.UNKNOWN, EdayunInboundSkuStatus.toCore(77, null)); + assertEquals(InboundStatus.UNKNOWN, EdayunInboundSkuStatus.toCore(null, "莫名其妙")); + assertNull(EdayunInboundSkuStatus.UNKNOWN.rawCode()); + } + + // ------------------------------------------------------------ 汇总 + + /** 还有 SKU 没上架,整单不算完成。 */ + @Test + void headStatusTakesLeastAdvancedSku() { + InboundOrder order = EdayunInboundQueryMapper.toOrder("REV1", Arrays.asList( + row("SKU-A", 10, 10, 10, 4, "已上架"), + row("SKU-B", 5, 5, 0, 99, "清点中")), "EDY-WH"); + + assertEquals(InboundStatus.RECEIVING, order.status()); + assertEquals("已上架", order.rawStatus()); + } + + /** 全部认不出 → UNKNOWN,不能当成完成。 */ + @Test + void allUnknownStatusStaysUnknown() { + InboundOrder order = EdayunInboundQueryMapper.toOrder("REV1", + Collections.singletonList(row("SKU-A", 1, 1, 1, 77, null)), "EDY-WH"); + + assertEquals(InboundStatus.UNKNOWN, order.status()); + } + + // ------------------------------------------------------------ 映射 + + @Test + void mapsQuantitiesAndLines() { + InboundOrder order = EdayunInboundQueryMapper.toOrder("REV1", Arrays.asList( + row("SKU-A", 10, 9, 8, 4, "已上架"), + row("SKU-B", 5, 5, 5, 4, "已上架")), "EDY-WH"); + + assertEquals("REV1", order.inboundRequestNo()); + assertEquals("REV1", order.providerInboundId()); + assertEquals("EDY-WH", order.warehouseCode()); + assertEquals(15, order.plannedQuantity()); + assertEquals(13, order.receivedQuantity()); + assertEquals(2, order.boxCount()); + assertEquals(2, order.lines().size()); + + InboundOrderLine line = order.lines().get(0); + assertEquals("SKU-A", line.providerSku()); + assertEquals(10, line.plannedQuantity()); + assertEquals(9, line.packedQuantity()); + assertEquals(8, line.receivedQuantity()); + assertTrue(!line.quantityMatchesPlan()); + assertEquals("候杰测试SKU-A", line.productName()); + } + + /** 没有 SKU 的行不计入明细,但数量照算——否则总数会悄悄变少。 */ + @Test + void rowsWithoutSkuAreSkippedButCounted() { + InboundOrder order = EdayunInboundQueryMapper.toOrder("REV1", Arrays.asList( + row(null, 3, 3, 3, 4, "已上架"), + row("SKU-B", 5, 5, 5, 4, "已上架")), "EDY-WH"); + + assertEquals(1, order.lines().size()); + assertEquals(8, order.plannedQuantity()); + } + + // ------------------------------------------------------------ 分页 + + @Test + void pageCarriesNextCursorWhenFull() { + Page重点:saveType 语义、一箱多 SKU 按 sid 归并、重量 g→kg、缺箱规本地拒绝。
+ */ +class EdayunInboundTest { + + private static InboundCommand.Builder cmd() { + return InboundCommand.builder() + .inboundRequestNo("PO-2026-001") + .warehouseId("2") + .predictionShipDate(LocalDate.of(2026, 12, 1)) + .estimateArriveDate(LocalDate.of(2026, 12, 20)) + .line(InboundLine.builder().omsSku("SKU-A").quantity(10).build()); + } + + private static InboundCarton carton(String sku, int qty, String sid) { + return InboundCarton.builder() + .providerSku(sku).quantity(qty).cartonNo("BOX-" + sid) + .sid(sid) + .lengthCm(50).widthCm(40).heightCm(30) + .weightGrams(12000) + .build(); + } + + // ------------------------------------------------------------ 请求 + + @Test + void createSendsPublishAndCustomerOrderNo() { + EdayunInboundDtos.SaveEntryRequest req = EdayunInboundMapper.toRequest( + cmd().carton(carton("SKU-A", 10, "1")).build(), + EdayunInboundMapper.SAVE_PUBLISH, null, null); + + assertEquals(Integer.valueOf(2), req.saveType); + assertEquals("PO-2026-001", req.customerOrderNo); + // 新建不带 entryCode + assertNull(req.entryCode); + } + + /** 更新必须带仓侧 entryCode,否则会变成「新建」把单子建重复。 */ + @Test + void updateRequiresEntryCode() { + InboundCommand command = cmd().carton(carton("SKU-A", 10, "1")).build(); + + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunInboundMapper.toRequest(command, + EdayunInboundMapper.SAVE_UPDATE, null, null)); + assertTrue(ex.getMessage().contains("entryCode"), ex.getMessage()); + + EdayunInboundDtos.SaveEntryRequest req = EdayunInboundMapper.toRequest( + command, EdayunInboundMapper.SAVE_UPDATE, "REV25052032239", null); + assertEquals("REV25052032239", req.entryCode); + } + + /** 客户单号上限 30,超了本地拒绝而不是让仓方截断。 */ + @Test + void tooLongCustomerOrderNoIsRejected() { + StringBuilder tooLong = new StringBuilder(); + for (int i = 0; i < 31; i++) { + tooLong.append('X'); + } + InboundCommand command = InboundCommand.builder() + .inboundRequestNo(tooLong.toString()) + .carton(carton("SKU-A", 1, "1")) + .build(); + + assertThrows(IllegalArgumentException.class, + () -> EdayunInboundMapper.toRequest(command, EdayunInboundMapper.SAVE_PUBLISH, null, null)); + } + + /** 数字仓 → shelfWarehouseId,非数字 → shelfWarehouseCode。 */ + @Test + void warehouseGoesToIdOrCode() { + EdayunInboundDtos.SaveEntryRequest numeric = EdayunInboundMapper.toRequest( + cmd().carton(carton("SKU-A", 1, "1")).build(), 2, null, null); + assertEquals(Long.valueOf(2L), numeric.basicInfo.shelfWarehouseId); + assertNull(numeric.basicInfo.shelfWarehouseCode); + + InboundCommand coded = cmd().warehouseId("USLA").carton(carton("SKU-A", 1, "1")).build(); + EdayunInboundDtos.SaveEntryRequest code = EdayunInboundMapper.toRequest(coded, 2, null, "USLA"); + assertEquals("USLA", code.basicInfo.shelfWarehouseCode); + assertNull(code.basicInfo.shelfWarehouseId); + } + + /** 预计离港 / 到港是毫秒时间戳。 */ + @Test + void datesBecomeMillis() { + EdayunInboundDtos.SaveEntryRequest req = EdayunInboundMapper.toRequest( + cmd().carton(carton("SKU-A", 1, "1")).build(), 2, null, null); + + assertEquals(Long.valueOf(LocalDate.of(2026, 12, 1).atStartOfDay(java.time.ZoneOffset.UTC) + .toInstant().toEpochMilli()), req.logisticsInfo.estimatedDepartureTime); + assertEquals(Long.valueOf(LocalDate.of(2026, 12, 20).atStartOfDay(java.time.ZoneOffset.UTC) + .toInstant().toEpochMilli()), req.logisticsInfo.estimatedArrivalDate); + } + + /** 箱规是 cargoInfos 的唯一来源;没有箱规就拒绝,别编一个箱子。 */ + @Test + void missingCartonsAreRejected() { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunInboundMapper.toRequest(cmd().build(), 2, null, null)); + + assertTrue(ex.getMessage().contains("carton"), ex.getMessage()); + } + + // ------------------------------------------------------------ 箱货 + + /** 一箱多 SKU:同一 sid 的行归并成一个 cargoInfo,含多条 boxSkuInfoList。 */ + @Test + void sameSidBecomesOneBoxWithMultipleSkus() { + List重点:零库存开关方向相反、仓 id 必须是数字、分页用 total 判断。
+ */ +class EdayunInventoryTest { + + private static final Instant AS_OF = Instant.parse("2026-11-13T00:00:00Z"); + + // ------------------------------------------------------------ 请求 + + @Test + void mapsPagingSkuAndWarehouse() { + EdayunInventoryDtos.QueryInventoryRequest req = EdayunInventoryMapper.toRequest( + InventoryQuery.builder().sku("ybtest").pageSize(1000).build(), "2", 1); + + assertEquals(Integer.valueOf(1), req.pageNum); + // 上限 500 + assertEquals(Integer.valueOf(500), req.pageSize); + assertEquals(Collections.singletonList("ybtest"), req.skuCodeList); + assertEquals(Collections.singletonList(2L), req.warehouseIdList); + // 没传零库存开关时不加限制,由仓方默认(只查总库存 > 0) + assertNull(req.totalStockGreaterThanZero); + } + + /** 统一模型是「包含零库存」,仓方是「只查大于 0」,方向相反。 */ + @Test + void includeZeroStockIsInverted() { + EdayunInventoryDtos.QueryInventoryRequest yes = EdayunInventoryMapper.toRequest( + InventoryQuery.builder().includeZeroStock(true).build(), null, 1); + EdayunInventoryDtos.QueryInventoryRequest no = EdayunInventoryMapper.toRequest( + InventoryQuery.builder().includeZeroStock(false).build(), null, 1); + + assertEquals(Boolean.FALSE, yes.totalStockGreaterThanZero); + assertEquals(Boolean.TRUE, no.totalStockGreaterThanZero); + } + + /** 每页默认 100。 */ + @Test + void pageSizeDefaultsTo100() { + assertEquals(Integer.valueOf(100), EdayunInventoryMapper.toRequest( + InventoryQuery.builder().build(), null, 1).pageSize); + } + + @Test + void moreThan100SkusIsRejected() { + List边界取自 PR 环境真机实测(2026-11-13):6/1~10/1 仓方接受、 + * 6/1~11/1 仓方拒绝。本地只挡明显超限,不误伤仓方接受的窗口。
+ */ +class EdayunQueryWindowsTest { + + private static final int MONTHS = 3; + + private static void check(String start, String end) { + EdayunQueryWindows.requireWithinMonths(Instant.parse(start), Instant.parse(end), + MONTHS, "rent detail"); + } + + /** 恰好 3 个自然月。 */ + @Test + void exactlyThreeMonthsIsAccepted() { + assertDoesNotThrow(() -> check("2026-06-01T00:00:00Z", "2026-09-01T00:00:00Z")); + } + + /** 真机实测仓方接受的 4 个月窗口不能被本地挡住。 */ + @Test + void windowProviderAcceptsIsNotBlocked() { + assertDoesNotThrow(() -> check("2026-06-01T00:00:00Z", "2026-10-01T00:00:00Z")); + assertDoesNotThrow(() -> check("2026-07-02T00:00:00Z", "2026-10-31T00:00:00Z")); + } + + /** 真机实测仓方拒绝的窗口,本地也挡。 */ + @Test + void obviouslyTooLongIsRejected() { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> check("2026-06-01T00:00:00Z", "2026-11-01T00:00:00Z")); + assertTrue(ex.getMessage().contains("3 months"), ex.getMessage()); + assertTrue(ex.getMessage().contains("2026-06-01"), ex.getMessage()); + } + + /** 拉一年这种明显错误必须本地挡掉,不发请求。 */ + @Test + void oneYearIsRejected() { + assertThrows(IllegalArgumentException.class, + () -> check("2026-01-01T00:00:00Z", "2027-01-01T00:00:00Z")); + } + + /** 时间窗由 FeeQuery 保证 start <= end,这里再兜一层不抛意外异常。 */ + @Test + void sameInstantIsAccepted() { + assertDoesNotThrow(() -> check("2026-06-01T00:00:00Z", "2026-06-01T00:00:00Z")); + } +} diff --git a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunRentDetailTest.java b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunRentDetailTest.java new file mode 100644 index 0000000..b4a783f --- /dev/null +++ b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunRentDetailTest.java @@ -0,0 +1,235 @@ +package common.ecommerce.edayun.adapter; + +import common.ecommerce.edayun.dto.EdayunRentDetailDtos; +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 selectUserRentDetailList})映射。 + * + *重点:时间窗必填且 ≤3 个月、仓 id 必须是数字、金额取 rentPrice、 + * 费用类型固定 STORAGE。
+ */ +class EdayunRentDetailTest { + + private static final Instant JAN_1 = Instant.parse("2026-01-01T00:00:00Z"); + private static final Instant FEB_15 = Instant.parse("2026-02-15T00:00:00Z"); + + private static FeeQuery.Builder range() { + return FeeQuery.builder().settledAfter(JAN_1).settledBefore(FEB_15); + } + + // ------------------------------------------------------------ 请求 + + @Test + void mapsTimeWindowAndWarehouseId() { + EdayunRentDetailDtos.SelectRentDetailRequest req = + EdayunRentDetailMapper.toRequest(range().build(), "98"); + + assertEquals(Long.valueOf(JAN_1.toEpochMilli()), req.billDateBegin); + assertEquals(Long.valueOf(FEB_15.toEpochMilli()), req.billDateEnd); + assertEquals(1, req.warehouseIds.size()); + assertEquals(Long.valueOf(98L), req.warehouseIds.get(0)); + assertEquals(Integer.valueOf(1), req.pageNum); + assertEquals(Integer.valueOf(200), req.pageSize); + } + + /** 仓租没有按单号单独查的口径:没时间窗直接拒绝。 */ + @Test + void withoutTimeRangeIsRejected() { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunRentDetailMapper.toRequest( + FeeQuery.builder().externalOrderNo("98-N9490-20260928").build(), "98")); + + assertTrue(ex.getMessage().contains("billing time range"), ex.getMessage()); + } + + /** 文档写明最大查询 3 个月。 */ + @Test + void rangeOver3MonthsIsRejected() { + FeeQuery tooLong = FeeQuery.builder() + .settledAfter(JAN_1) + .settledBefore(Instant.parse("2026-06-01T00:00:00Z")) + .build(); + + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunRentDetailMapper.toRequest(tooLong, "98")); + + assertTrue(ex.getMessage().contains("3 months"), ex.getMessage()); + } + + /** 本接口只出仓租,明确要别的费用类型说明用错了接口。 */ + @Test + void nonStorageCostTypeIsRejected() { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunRentDetailMapper.toRequest( + range().costType(WarehouseFeeType.LAST_MILE).build(), "98")); + + assertTrue(ex.getMessage().contains("only returns STORAGE"), ex.getMessage()); + } + + /** 快照日期是运去哪的口径,易达云按计费时间窗查。 */ + @Test + void snapshotDateRangeIsRejected() { + FeeQuery q = FeeQuery.builder() + .snapshotDateRange(java.time.LocalDate.of(2026, 1, 1), + java.time.LocalDate.of(2026, 1, 31)) + .settledAfter(JAN_1).settledBefore(FEB_15) + .build(); + + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunRentDetailMapper.toRequest(q, "98")); + + assertTrue(ex.getMessage().contains("settledAfter"), ex.getMessage()); + } + + @Test + void filtersMapToSingletonLists() { + EdayunRentDetailDtos.SelectRentDetailRequest req = EdayunRentDetailMapper.toRequest( + range().externalOrderNo("98-N9490-20260928").providerSku("CANADA-TEST").build(), null); + + assertEquals(java.util.Collections.singletonList("98-N9490-20260928"), req.businessNums); + assertEquals(java.util.Collections.singletonList("CANADA-TEST"), req.skuCodes); + // 仓 id 未知时不下发,避免空数组被仓方当成「查所有仓」 + assertNull(req.warehouseIds); + } + + /** 仓 id 非数字直接拒绝,避免仓侧静默查不到。 */ + @Test + void nonNumericWarehouseIdIsRejected() { + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> EdayunRentDetailMapper.toRequest(range().build(), "EDY-WH-1")); + + assertTrue(ex.getMessage().contains("must be numeric"), ex.getMessage()); + } + + // ------------------------------------------------------------ 响应 + + private static EdayunRentDetailDtos.RentDetailRow row() { + EdayunRentDetailDtos.RentDetailRow row = new EdayunRentDetailDtos.RentDetailRow(); + row.businessNum = "98-N9490-20260928"; + row.billingDate = 1790568000000L; + row.warehouseId = "98"; + row.warehouseName = "加西3仓"; + row.skuCode = "CANADA-TEST"; + row.orderNo = "RLB0011790104"; + row.rentDays = 1021; + row.totalStock = 7; + row.billingVol = 6.7; + row.billingVolUnit = "CBFT"; + row.billingId = 1679667136799649000L; + row.billingName = "仓租"; + row.unitPrice = 0.34; + row.originalPrice = 2.278; + row.discountPrice = 0.0; + row.currencyCode = "CAD"; + row.rentPrice = 2.278; + return row; + } + + @Test + void mapsRowToDocument() { + BillingDocument doc = EdayunRentDetailMapper.toDocument(row(), "EDY-WH"); + + assertEquals("加西3仓", doc.warehouseCode()); + assertEquals("98-N9490-20260928", doc.documentNo()); + assertEquals("1679667136799649000", doc.serialNumber()); + assertEquals("仓租", doc.feeName()); + assertEquals(WarehouseFeeType.STORAGE, doc.feeType()); + assertEquals(Instant.ofEpochMilli(1790568000000L), doc.settledAt()); + assertEquals("RLB0011790104", doc.saleOrderNo()); + assertEquals("CANADA-TEST", doc.providerSku()); + assertEquals(Boolean.FALSE, doc.estimated()); + } + + /** 金额取 rentPrice,币种按原值(可能是 CAD 等非 USD)。 */ + @Test + void amountIsRentPriceWithOriginalCurrency() { + BillingDocument doc = EdayunRentDetailMapper.toDocument(row(), "W"); + + assertEquals(new BigDecimal("2.278"), doc.amount().amount()); + assertEquals("CAD", doc.amount().currencyCode()); + } + + /** rentPrice 缺失时用原价减折扣兜底。 */ + @Test + void fallsBackToOriginalMinusDiscount() { + EdayunRentDetailDtos.RentDetailRow r = row(); + r.rentPrice = null; + r.originalPrice = 10.0; + r.discountPrice = 1.5; + + assertEquals(new BigDecimal("8.5"), + EdayunRentDetailMapper.toDocument(r, "W").amount().amount()); + } + + /** 全缺时记零,不抛异常——仓租明细缺金额不该阻断整批。 */ + @Test + void missingAmountYieldsZero() { + EdayunRentDetailDtos.RentDetailRow r = row(); + r.rentPrice = null; + r.originalPrice = null; + r.discountPrice = null; + + assertEquals(BigDecimal.ZERO, + EdayunRentDetailMapper.toDocument(r, "W").amount().amount()); + } + + /** 仓名缺失时回退 OMS 仓编码,warehouseCode 不能为空。 */ + @Test + void warehouseNameFallsBackToCode() { + EdayunRentDetailDtos.RentDetailRow r = row(); + r.warehouseName = null; + + assertEquals("EDY-WH", EdayunRentDetailMapper.toDocument(r, "EDY-WH").warehouseCode()); + } + + /** 业务单号缺失时用订单号当单据号。 */ + @Test + void documentNoFallsBackToOrderNo() { + EdayunRentDetailDtos.RentDetailRow r = row(); + r.businessNum = null; + + assertEquals("RLB0011790104", + EdayunRentDetailMapper.toDocument(r, "W").documentNo()); + } + + /** 计费时间和 billingId 都可能缺;缺时不能抛异常。 */ + @Test + void missingBillingDateAndIdAreTolerated() { + EdayunRentDetailDtos.RentDetailRow r = row(); + r.billingDate = null; + r.billingId = null; + + BillingDocument doc = EdayunRentDetailMapper.toDocument(r, "W"); + + assertNull(doc.settledAt()); + assertNull(doc.serialNumber()); + } + + @Test + void mapsAllRows() { + List默认跳过,用 {@code -Dedayun.probe.estimate=true} 开启;凭据走系统属性, + * 真实值不入库:
+ * + *+ * # 只看报文(不联网) + * mvn -pl warehouse-sdk-edayun -DfailIfNoTests=false \ + * -Dedayun.probe.estimate=true -Dtest=EdayunFeeEstimateProbeTest test + * + * # 真跑(只读) + * ... -Dedayun.probe.estimate=true -Dedayun.probe.call=true \ + * -Dedayun.probe.clientId=... -Dedayun.probe.clientSecret=... \ + * -Dedayun.probe.appKey=... -Dedayun.probe.appSecret=... \ + * [-Dedayun.probe.warehouseId=2] [-Dedayun.probe.zipcode=91761] + *+ * + *
异常只打印不抛出,便于一次跑完对照真实报文。
+ */ +@EnabledIfSystemProperty(named = "edayun.probe.estimate", matches = "true") +class EdayunFeeEstimateProbeTest { + + 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", ""); + 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 String WAREHOUSE_ID = opt("edayun.probe.warehouseId", "2"); + private static final String ZIPCODE = opt("edayun.probe.zipcode", "91761"); + private static final String PRODUCT_ID = System.getProperty("edayun.probe.productId", ""); + private static final boolean CALL = Boolean.getBoolean("edayun.probe.call"); + + @Test + void probeEstimate() { + FeeEstimateQuery.Builder query = FeeEstimateQuery.builder() + .lengthCm(new BigDecimal("22")) + .widthCm(new BigDecimal("22")) + .heightCm(new BigDecimal("22")) + .weightGrams(new BigDecimal("1000")) + .receiveCountry(opt("edayun.probe.country", "US")) + .receivePostal(ZIPCODE) + // 标准模型强制要求渠道码;易达云没有该概念,非数字会被映射成「不指定」 + .logisticsServiceCode(PRODUCT_ID.trim().isEmpty() ? "ALL" : PRODUCT_ID.trim()); + + EdayunFeeEstimateDtos.TrialRequest req = + EdayunFeeEstimateMapper.toRequest(query.build(), WAREHOUSE_ID); + String bodyJson = new JacksonJsonCodec().toJson(req); + + System.out.println("\n================ edayun / POST " + + EdayunConstants.PATH_FEE_ESTIMATE + " ================"); + System.out.println("[probe] baseUrl=" + BASE_URL + " warehouseId=" + WAREHOUSE_ID + + " zipcode=" + ZIPCODE); + System.out.println("[request] " + bodyJson); + if (!APP_SECRET.trim().isEmpty()) { + System.out.println("[sign] " + common.ecommerce.edayun.http.EdayunRequestFactory + .sign(bodyJson, APP_SECRET)); + } + + Assumptions.assumeTrue(CALL, "dry-run:未加 -Dedayun.probe.call=true,不实际调用"); + Assumptions.assumeTrue(!CLIENT_ID.trim().isEmpty() && !CLIENT_SECRET.trim().isEmpty() + && !APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), + "真跑需要 -Dedayun.probe.clientId / clientSecret / appKey / appSecret"); + + try { + WarehouseContext ctx = WarehouseContext.of("EDY-PROBE", WarehouseProvider.EDAYUN, + WAREHOUSE_ID, WarehouseConnection.of(BASE_URL, + ChannelSecret.builder() + .appKey(APP_KEY).appSecret(APP_SECRET) + .clientId(CLIENT_ID).clientSecret(CLIENT_SECRET) + .build()), + "probe-" + UUID.randomUUID(), Clock.systemUTC()); + EdayunAdapter adapter = new EdayunAdapter( + new OkHttpTransport("common-ecommerce/1.0.0 (edayun-probe)", 10_000, 120_000), + new JacksonJsonCodec()); + + List创建入库单是写操作,会真实建单,所以真跑要显式加 + * {@code -Dedayun.probe.write=true};客户单号用 {@code PROBE-} 前缀的时间戳,避免撞车。
+ * + *+ * # 只看报文(安全) + * mvn -pl warehouse-sdk-edayun -DfailIfNoTests=false \ + * -Dedayun.probe.inbound=true -Dtest=EdayunInboundProbeTest test + * + * # 真发一次(会在测试仓建入库单) + * ... -Dedayun.probe.inbound=true -Dedayun.probe.write=true \ + * -Dedayun.probe.clientId=... -Dedayun.probe.clientSecret=... \ + * -Dedayun.probe.appKey=... -Dedayun.probe.appSecret=... \ + * -Dedayun.probe.warehouseId=2 -Dedayun.probe.sku=ybtest + *+ * + *
若只想验证「保存不发布」,把 {@code -Dedayun.probe.saveType=0}(新增草稿); + * 默认 2(保存并发布)。
+ */ +@EnabledIfSystemProperty(named = "edayun.probe.inbound", matches = "true") +class EdayunInboundProbeTest { + + 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", ""); + 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 String WAREHOUSE_ID = System.getProperty("edayun.probe.warehouseId", ""); + private static final String SKU = opt("edayun.probe.sku", "ybtest"); + private static final int SAVE_TYPE = Integer.getInteger("edayun.probe.saveType", 2); + private static final boolean WRITE = Boolean.getBoolean("edayun.probe.write"); + + @Test + void probeSaveEntry() { + String customerOrderNo = "PROBE-" + + Long.toString(System.currentTimeMillis(), 36).toUpperCase(); + + InboundCommand cmd = InboundCommand.builder() + .inboundRequestNo(customerOrderNo) + .warehouseId(WAREHOUSE_ID) + .predictionShipDate(LocalDate.now().plusDays(7)) + .estimateArriveDate(LocalDate.now().plusDays(30)) + .line(InboundLine.builder().omsSku(SKU).quantity(1).build()) + .carton(InboundCarton.builder() + .providerSku(SKU) + .quantity(1) + .cartonNo("PROBE-BOX-1") + .lengthCm(11.2).widthCm(11.2).heightCm(11.2) + .weightGrams(11200) + .build()) + .build(); + + EdayunInboundDtos.SaveEntryRequest req = EdayunInboundMapper.toRequest( + cmd, SAVE_TYPE, null, emptyToNull(WAREHOUSE_ID)); + String bodyJson = new JacksonJsonCodec().toJson(req); + + System.out.println("\n================ edayun / POST " + + EdayunConstants.PATH_INBOUND_SAVE + " ================"); + System.out.println("[probe] baseUrl=" + BASE_URL + + " saveType=" + SAVE_TYPE + + " warehouseId=" + mask(WAREHOUSE_ID) + + " sku=" + mask(SKU) + + " customerOrderNo=" + customerOrderNo); + System.out.println("[request] " + bodyJson); + if (!APP_SECRET.trim().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(!CLIENT_ID.trim().isEmpty() && !CLIENT_SECRET.trim().isEmpty() + && !APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), + "真跑需要 -Dedayun.probe.clientId / clientSecret / appKey / appSecret"); + + try { + WarehouseContext ctx = WarehouseContext.of("EDY-PROBE", WarehouseProvider.EDAYUN, + emptyToNull(WAREHOUSE_ID), + WarehouseConnection.of(BASE_URL, + ChannelSecret.builder() + .appKey(APP_KEY).appSecret(APP_SECRET) + .clientId(CLIENT_ID).clientSecret(CLIENT_SECRET) + .build()), + "probe-" + UUID.randomUUID(), java.time.Clock.systemUTC()); + EdayunAdapter adapter = new EdayunAdapter( + new OkHttpTransport("common-ecommerce/1.0.0 (edayun-probe)", 10_000, 60_000), + new JacksonJsonCodec()); + + InboundReceipt receipt = adapter.create(ctx, cmd); + System.out.println("[OK] inboundRequestNo=" + receipt.inboundRequestNo() + + " providerInboundId=" + receipt.providerInboundId()); + System.out.println(" 建单后用 entryCode 查状态:目前 SDK 没有该接口,见 docs-warehouse/edayun/TODO.md"); + } 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, ""); + String trimmed = value == null ? "" : value.trim(); + return trimmed.isEmpty() ? fallback : trimmed; + } + + private static String emptyToNull(String v) { + return v == null || v.trim().isEmpty() ? null : v.trim(); + } + + private static String mask(String v) { + if (v == null || v.trim().isEmpty()) { + return "(empty)"; + } + String t = v.trim(); + return t.length() <= 6 ? "***" : t.substring(0, 3) + "***" + t.substring(t.length() - 2); + } +} diff --git a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/probe/EdayunInboundQueryProbeTest.java b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/probe/EdayunInboundQueryProbeTest.java new file mode 100644 index 0000000..9a162b1 --- /dev/null +++ b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/probe/EdayunInboundQueryProbeTest.java @@ -0,0 +1,115 @@ +package common.ecommerce.edayun.probe; + +import common.ecommerce.edayun.EdayunConstants; +import common.ecommerce.edayun.adapter.EdayunAdapter; +import common.ecommerce.edayun.adapter.EdayunInboundQueryMapper; +import common.ecommerce.edayun.dto.EdayunInboundQueryDtos; +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.warehouse.enums.WarehouseProvider; +import common.ecommerce.warehouse.model.InboundOrder; +import common.ecommerce.warehouse.model.InboundOrderLine; +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; + +/** + * 入库明细查询探针:只读,不会在仓侧产生任何数据。 + * + *+ * # 只看报文(不联网) + * mvn -pl warehouse-sdk-edayun -DfailIfNoTests=false \ + * -Dedayun.probe.inboundQuery=true -Dtest=EdayunInboundQueryProbeTest test + * + * # 真查(只读) + * ... -Dedayun.probe.inboundQuery=true -Dedayun.probe.call=true \ + * -Dedayun.probe.clientId=... -Dedayun.probe.clientSecret=... \ + * -Dedayun.probe.appKey=... -Dedayun.probe.appSecret=... \ + * -Dedayun.probe.entryCode=REV24050738176 + *+ */ +@EnabledIfSystemProperty(named = "edayun.probe.inboundQuery", matches = "true") +class EdayunInboundQueryProbeTest { + + 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", ""); + 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 String ENTRY_CODE = opt("edayun.probe.entryCode", "REV24050738176"); + private static final boolean CALL = Boolean.getBoolean("edayun.probe.call"); + + @Test + void probeEntrySkuDetail() { + EdayunInboundQueryDtos.SelectEntrySkuRequest req = + EdayunInboundQueryMapper.toRequest(ENTRY_CODE, 1); + String bodyJson = new JacksonJsonCodec().toJson(req); + + System.out.println("\n================ edayun / POST " + + EdayunConstants.PATH_INBOUND_SKU_DETAIL + " ================"); + System.out.println("[probe] baseUrl=" + BASE_URL + " entryCode=" + ENTRY_CODE); + System.out.println("[request] " + bodyJson); + if (!APP_SECRET.trim().isEmpty()) { + System.out.println("[sign] " + common.ecommerce.edayun.http.EdayunRequestFactory + .sign(bodyJson, APP_SECRET)); + } + + Assumptions.assumeTrue(CALL, "dry-run:未加 -Dedayun.probe.call=true,不实际调用"); + Assumptions.assumeTrue(!CLIENT_ID.trim().isEmpty() && !CLIENT_SECRET.trim().isEmpty() + && !APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), + "真查需要 -Dedayun.probe.clientId / clientSecret / appKey / appSecret"); + + try { + WarehouseContext ctx = WarehouseContext.of("EDY-PROBE", WarehouseProvider.EDAYUN, null, + WarehouseConnection.of(BASE_URL, + ChannelSecret.builder() + .appKey(APP_KEY).appSecret(APP_SECRET) + .clientId(CLIENT_ID).clientSecret(CLIENT_SECRET) + .build()), + "probe-" + UUID.randomUUID(), Clock.systemUTC()); + EdayunAdapter adapter = new EdayunAdapter( + new OkHttpTransport("common-ecommerce/1.0.0 (edayun-probe)", 10_000, 60_000), + new JacksonJsonCodec()); + + InboundOrder order = adapter.get(ctx, ENTRY_CODE); + if (order == null) { + System.out.println("[OK] 空结果(单号不存在或账号无权查看)"); + return; + } + System.out.println("[OK] entryCode=" + order.providerInboundId() + + " status=" + order.status() + + " rawStatus=" + order.rawStatus() + + " planned=" + order.plannedQuantity() + + " received=" + order.receivedQuantity() + + " skus=" + order.lines().size()); + for (InboundOrderLine line : order.lines()) { + System.out.println(" " + line.providerSku() + + " plan=" + line.plannedQuantity() + + " checked=" + line.packedQuantity() + + " shelves=" + line.receivedQuantity()); + } + } 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, ""); + String trimmed = value == null ? "" : value.trim(); + return trimmed.isEmpty() ? fallback : trimmed; + } +} diff --git a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/probe/EdayunInventoryProbeTest.java b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/probe/EdayunInventoryProbeTest.java new file mode 100644 index 0000000..67691f0 --- /dev/null +++ b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/probe/EdayunInventoryProbeTest.java @@ -0,0 +1,140 @@ +package common.ecommerce.edayun.probe; + +import common.ecommerce.edayun.EdayunConstants; +import common.ecommerce.edayun.adapter.EdayunAdapter; +import common.ecommerce.edayun.adapter.EdayunInventoryMapper; +import common.ecommerce.edayun.dto.EdayunInventoryDtos; +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.Page; +import common.ecommerce.warehouse.enums.WarehouseProvider; +import common.ecommerce.warehouse.model.InventoryQuery; +import common.ecommerce.warehouse.model.InventorySnapshot; +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; + +/** + * 库存查询联调探针:只读,不会在仓侧产生任何数据。 + * + *
默认跳过,用 {@code -Dedayun.probe.inventory=true} 开启;凭据走系统属性, + * 真实值不入库:
+ * + *+ * # 只看报文(不联网) + * mvn -pl warehouse-sdk-edayun -DfailIfNoTests=false \ + * -Dedayun.probe.inventory=true -Dtest=EdayunInventoryProbeTest test + * + * # 真查(只读) + * ... -Dedayun.probe.inventory=true -Dedayun.probe.call=true \ + * -Dedayun.probe.clientId=... -Dedayun.probe.clientSecret=... \ + * -Dedayun.probe.appKey=... -Dedayun.probe.appSecret=... \ + * [-Dedayun.probe.warehouseId=2] [-Dedayun.probe.sku=ybtest] \ + * [-Dedayun.probe.zeroStock=true] [-Dedayun.probe.page=1] + *+ * + *
异常只打印不抛出,便于一次跑完对照真实报文。
+ */ +@EnabledIfSystemProperty(named = "edayun.probe.inventory", matches = "true") +class EdayunInventoryProbeTest { + + 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", ""); + 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 String WAREHOUSE_ID = System.getProperty("edayun.probe.warehouseId", ""); + private static final String SKU = System.getProperty("edayun.probe.sku", ""); + private static final int PAGE = Integer.getInteger("edayun.probe.page", 1); + private static final boolean ZERO_STOCK = Boolean.getBoolean("edayun.probe.zeroStock"); + private static final boolean CALL = Boolean.getBoolean("edayun.probe.call"); + + @Test + void probeInventory() { + InventoryQuery query = InventoryQuery.builder() + .sku(emptyToNull(SKU)) + .cursor(PAGE <= 1 ? null : String.valueOf(PAGE)) + .includeZeroStock(ZERO_STOCK ? Boolean.TRUE : null) + .build(); + + EdayunInventoryDtos.QueryInventoryRequest req = + EdayunInventoryMapper.toRequest(query, emptyToNull(WAREHOUSE_ID), PAGE); + String bodyJson = new JacksonJsonCodec().toJson(req); + + System.out.println("\n================ edayun / POST " + + EdayunConstants.PATH_INVENTORY + " ================"); + System.out.println("[probe] baseUrl=" + BASE_URL + + " warehouseId=" + mask(WAREHOUSE_ID) + + " sku=" + mask(SKU) + " page=" + PAGE + + " includeZeroStock=" + ZERO_STOCK); + System.out.println("[request] " + bodyJson); + if (!APP_SECRET.trim().isEmpty()) { + System.out.println("[sign] " + common.ecommerce.edayun.http.EdayunRequestFactory + .sign(bodyJson, APP_SECRET)); + } + + Assumptions.assumeTrue(CALL, "dry-run:未加 -Dedayun.probe.call=true,不实际调用"); + Assumptions.assumeTrue(!CLIENT_ID.trim().isEmpty() && !CLIENT_SECRET.trim().isEmpty() + && !APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), + "真查需要 -Dedayun.probe.clientId / clientSecret / appKey / appSecret"); + + try { + WarehouseContext ctx = WarehouseContext.of("EDY-PROBE", WarehouseProvider.EDAYUN, + emptyToNull(WAREHOUSE_ID), + WarehouseConnection.of(BASE_URL, + ChannelSecret.builder() + .appKey(APP_KEY).appSecret(APP_SECRET) + .clientId(CLIENT_ID).clientSecret(CLIENT_SECRET) + .build()), + "probe-" + UUID.randomUUID(), Clock.systemUTC()); + EdayunAdapter adapter = new EdayunAdapter( + new OkHttpTransport("common-ecommerce/1.0.0 (edayun-probe)", 10_000, 60_000), + new JacksonJsonCodec()); + + Page默认跳过,用 {@code -Dedayun.probe.rent=true} 开启;凭据走系统属性, + * 真实值不入库:
+ * + *+ * # 只看报文(不联网) + * mvn -pl warehouse-sdk-edayun -DfailIfNoTests=false \ + * -Dedayun.probe.rent=true -Dtest=EdayunRentProbeTest test + * + * # 真查(只读) + * ... -Dedayun.probe.rent=true -Dedayun.probe.call=true \ + * -Dedayun.probe.clientId=... -Dedayun.probe.clientSecret=... \ + * -Dedayun.probe.appKey=... -Dedayun.probe.appSecret=... \ + * -Dedayun.probe.warehouseId=98 \ + * [-Dedayun.probe.days=30] [-Dedayun.probe.bizNo=98-N9490-20260928] + *+ * + *
异常只打印不抛出,便于一次跑完对照真实报文。
+ */ +@EnabledIfSystemProperty(named = "edayun.probe.rent", matches = "true") +class EdayunRentProbeTest { + + 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", ""); + 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 String WAREHOUSE_ID = System.getProperty("edayun.probe.warehouseId", ""); + private static final String BIZ_NO = System.getProperty("edayun.probe.bizNo", ""); + private static final boolean CALL = Boolean.getBoolean("edayun.probe.call"); + + /** 查询窗口天数;仓租文档上限 3 个月,默认取 30 天避免拉太多。 */ + private static final int DAYS = Integer.getInteger("edayun.probe.days", 30); + + @Test + void probeRentDetail() { + Instant end = Instant.now(); + Instant begin = end.minus(DAYS, ChronoUnit.DAYS); + + FeeQuery query = FeeQuery.builder() + .settledAfter(begin) + .settledBefore(end) + .costType(WarehouseFeeType.STORAGE) + .externalOrderNo(emptyToNull(BIZ_NO)) + .build(); + + EdayunRentDetailDtos.SelectRentDetailRequest req = + EdayunRentDetailMapper.toRequest(query, emptyToNull(WAREHOUSE_ID)); + String bodyJson = new JacksonJsonCodec().toJson(req); + + System.out.println("\n================ edayun / POST " + + EdayunConstants.PATH_RENT_DETAIL + " ================"); + System.out.println("[probe] baseUrl=" + BASE_URL + + " warehouseId=" + mask(WAREHOUSE_ID) + + " begin=" + begin + " end=" + end); + System.out.println("[request] " + bodyJson); + if (!APP_SECRET.trim().isEmpty()) { + System.out.println("[sign] " + common.ecommerce.edayun.http.EdayunRequestFactory + .sign(bodyJson, APP_SECRET)); + } + + Assumptions.assumeTrue(CALL, "dry-run:未加 -Dedayun.probe.call=true,不实际调用"); + Assumptions.assumeTrue(!CLIENT_ID.trim().isEmpty() && !CLIENT_SECRET.trim().isEmpty() + && !APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), + "真查需要 -Dedayun.probe.clientId / clientSecret / appKey / appSecret"); + + try { + WarehouseContext ctx = WarehouseContext.of("EDY-PROBE", WarehouseProvider.EDAYUN, + emptyToNull(WAREHOUSE_ID), + WarehouseConnection.of(BASE_URL, + ChannelSecret.builder() + .appKey(APP_KEY).appSecret(APP_SECRET) + .clientId(CLIENT_ID).clientSecret(CLIENT_SECRET) + .build()), + "probe-" + UUID.randomUUID(), Clock.systemUTC()); + EdayunAdapter adapter = new EdayunAdapter( + // 仓租查询实测很慢:pageSize=200 单页 6~13 秒,默认 30 秒读超时不够稳 + new OkHttpTransport("common-ecommerce/1.0.0 (edayun-probe)", 10_000, 120_000), + new JacksonJsonCodec()); + + List