You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 lines
18 KiB

package common.ecommerce.walmart.mapper;
import common.ecommerce.channel.model.order.OrderLine;
import common.ecommerce.channel.model.order.SalesOrder;
import common.ecommerce.channel.model.order.ShipToAddress;
import common.ecommerce.shared.model.ChannelProvider;
import common.ecommerce.shared.support.Money;
import common.ecommerce.shared.support.PlatformTime;
import common.ecommerce.walmart.dto.WalmartOrderDtos;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 沃尔玛订单 → 统一 {@link SalesOrder}。
*
* <p>只做字段搬运与必要的单位/格式转换,不做业务判断:</p>
* <ul>
* <li>时间:订单接口是 epoch 毫秒,统一转 {@link PlatformTime}</li>
* <li>数量:{@code orderLineQuantity.amount} 是字符串,解析失败记 0 而不是抛异常,
* 避免一行脏数据卡住整页同步</li>
* <li>单价:沃尔玛的 {@code ItemPrice.chargeAmount} 是<b>整行金额</b>,
* 必须除以行数量才是 {@link OrderLine#unitPrice()};数量为 0 时无法拆分,
* 保留整行金额(此时它等于单价,因为只有 1 件)</li>
* <li>行税额:取该行所有 charge 上 {@code tax.taxAmount} 的合计</li>
* <li>订单总额:按行合计(商品金额 + 税),币种取第一个非空币种</li>
* </ul>
*/
public final class WalmartOrderMapper {
private WalmartOrderMapper() {
}
/**
* 映射一个订单。
*
* <p><b>不完整的订单返回 null</b>,由调用方跳过并记一条 WARN:
* {@code purchaseOrderId} 与 {@code orderDate} 在统一模型里是必填
* (前者进 canonicalKey,后者进 {@code occurredAt}),平台漏给时硬造一个值
* 会把脏数据写进主键。宁可少一条,也不能写错一条。</p>
*
* @param dto 平台订单
* @param omsStoreId 宿主店铺 ID
* @param marketplaceZone 市场时区,用于 {@link PlatformTime}
* @return 统一订单;{@code dto} 为 null、缺订单号或缺下单时间时返回 null
*/
public static SalesOrder toSalesOrder(WalmartOrderDtos.Order dto, String omsStoreId,
ZoneId marketplaceZone) {
if (dto == null || isBlank(dto.purchaseOrderId) || dto.orderDate == null) {
return null;
}
List<OrderLine> lines = toOrderLines(dto);
return SalesOrder.builder()
.omsStoreId(omsStoreId)
.channelOrderId(dto.purchaseOrderId)
.status(statusOf(dto))
.buyerName(dto.shippingInfo == null || dto.shippingInfo.postalAddress == null
? null : dto.shippingInfo.postalAddress.name)
.buyerEmail(dto.customerEmailId)
.shipToCountryCode(countryCodeOf(dto))
.shipToAddress(toShipToAddress(dto))
.lines(lines)
.totalAmount(totalOf(dto))
.occurredAt(toPlatformTime(dto.orderDate, marketplaceZone))
.sourceProvider(ChannelProvider.DIRECT)
.sourceAccountId(null)
.build();
}
/** 平台必填字段缺失时的判定;只 trim,不做其它归一。 */
private static boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
/**
* 订单级状态:沃尔玛没有这个字段,按行状态聚合。
*
* <p>一行的 {@code orderLineStatus[]} 不是纯历史:部分发货时
* {@code Created(3)} 与 {@code Shipped(1)} 会同时存在,数量各不相同。所以先按数量
* 把每行<b>归一</b>成一个当前状态(见 {@link #resolveLineStatus}),再交给
* {@link common.ecommerce.walmart.enums.WalmartOrderStatus#aggregate}。</p>
*
* @see common.ecommerce.walmart.enums.WalmartOrderStatus#aggregate(Iterable)
*/
static String statusOf(WalmartOrderDtos.Order dto) {
if (dto.orderLines == null || dto.orderLines.orderLine == null) {
return null;
}
List<String> statuses = new ArrayList<String>();
for (WalmartOrderDtos.OrderLine line : dto.orderLines.orderLine) {
if (line == null) {
continue;
}
String resolved = resolveLineStatus(line);
if (resolved != null) {
statuses.add(resolved);
}
}
return common.ecommerce.walmart.enums.WalmartOrderStatus.aggregate(statuses).raw();
}
/**
* 按订单行数量把行状态归一成一个「当前」状态。
*
* <p>规则(数量缺失时退化为「取状态列表最后一条」):</p>
* <ol>
* <li>取消数量 ≥ 订量 → {@code Cancelled}</li>
* <li>发货数量({@code Shipped} + {@code Delivered})≥ 订量 - 取消数量:
* 全部 {@code Delivered} 时给 {@code Delivered},否则 {@code Shipped}</li>
* <li>还有没发的余量 → {@code Created}(订单层面仍需发货动作)</li>
* <li>什么都不匹配 → 状态列表最后一条的原值</li>
* </ol>
*
* <p>{@code OrderLine.status()} 保留的是<b>平台原值</b>(状态列表最后一条),
* 需要判断「这一行还差多少没发」时以 {@link #resolveLineStatus} 的结果为准。</p>
*/
static String resolveLineStatus(WalmartOrderDtos.OrderLine line) {
int ordered = parseQuantity(line.orderLineQuantity);
if (ordered <= 0 || line.orderLineStatuses == null
|| line.orderLineStatuses.orderLineStatus == null) {
return currentLineStatus(line);
}
int shipped = 0;
int delivered = 0;
int cancelled = 0;
boolean anyQuantity = false;
for (WalmartOrderDtos.OrderLineStatus s : line.orderLineStatuses.orderLineStatus) {
if (s == null || s.status == null) {
continue;
}
int qty = parseQuantity(s.statusQuantity);
if (qty > 0) {
anyQuantity = true;
}
if ("Shipped".equals(s.status)) {
shipped += qty;
} else if ("Delivered".equals(s.status)) {
delivered += qty;
} else if ("Cancelled".equals(s.status)) {
cancelled += qty;
}
}
if (!anyQuantity) {
return currentLineStatus(line);
}
if (cancelled >= ordered) {
return "Cancelled";
}
int fulfilled = shipped + delivered;
int expected = ordered - cancelled;
if (fulfilled >= expected) {
return delivered >= expected ? "Delivered" : "Shipped";
}
return "Created";
}
/** 收货地址;平台未返回地址时返回 null(全空对象不挂到订单上)。 */
static ShipToAddress toShipToAddress(WalmartOrderDtos.Order dto) {
if (dto.shippingInfo == null || dto.shippingInfo.postalAddress == null) {
return null;
}
WalmartOrderDtos.PostalAddress a = dto.shippingInfo.postalAddress;
ShipToAddress address = ShipToAddress.builder()
.name(a.name)
.address1(a.address1)
.address2(a.address2)
.city(a.city)
.state(a.state)
.postalCode(a.postalCode)
.countryCode(a.country)
.addressType(a.addressType)
.phone(dto.shippingInfo.phone)
.build();
return address.isEmpty() ? null : address;
}
/** 收货国家:优先地址里的国家;没有地址时返回 null。 */
static String countryCodeOf(WalmartOrderDtos.Order dto) {
return dto.shippingInfo == null || dto.shippingInfo.postalAddress == null
? null : dto.shippingInfo.postalAddress.country;
}
/**
* 订单总额:逐行商品金额 + 税合计;一行都算不出来时返回 null。
*
* <p><b>币种不一致时返回 null</b>:沃尔玛一个订单只有一个币种,
* 出现两个说明数据有问题;把不同币种直接相加会得到一个无意义的数。</p>
*/
static Money totalOf(WalmartOrderDtos.Order dto) {
if (dto.orderLines == null || dto.orderLines.orderLine == null) {
return null;
}
BigDecimal total = BigDecimal.ZERO;
String currency = null;
boolean any = false;
for (WalmartOrderDtos.OrderLine line : dto.orderLines.orderLine) {
if (line == null || line.charges == null || line.charges.charge == null) {
continue;
}
for (WalmartOrderDtos.Charge charge : line.charges.charge) {
if (charge == null || charge.chargeAmount == null || charge.chargeAmount.amount == null) {
continue;
}
if (charge.chargeAmount.currency == null) {
continue;
}
if (currency == null) {
currency = charge.chargeAmount.currency;
} else if (!currency.equals(charge.chargeAmount.currency)) {
// 同单多币种:数据异常,宁可不给总额,也不给一个加错的数
return null;
}
total = total.add(charge.chargeAmount.amount);
any = true;
if (charge.tax != null && charge.tax.taxAmount != null
&& charge.tax.taxAmount.amount != null) {
total = total.add(charge.tax.taxAmount.amount);
}
}
}
if (!any) {
return null;
}
try {
return Money.of(total, currency);
} catch (IllegalArgumentException e) {
// 平台给了非法币种代码:不阻断整页,按「金额不可用」处理
return null;
}
}
/** 订单行。 */
static List<OrderLine> toOrderLines(WalmartOrderDtos.Order dto) {
if (dto.orderLines == null || dto.orderLines.orderLine == null) {
return Collections.emptyList();
}
List<OrderLine> out = new ArrayList<OrderLine>(dto.orderLines.orderLine.size());
for (WalmartOrderDtos.OrderLine line : dto.orderLines.orderLine) {
if (line == null) {
continue;
}
int quantity = parseQuantity(line.orderLineQuantity);
out.add(OrderLine.builder()
.lineId(line.lineNumber)
.platformSku(line.item == null || line.item.sku == null ? "" : line.item.sku)
.quantity(quantity)
.lineAmount(lineAmountOf(line))
.unitPrice(unitPriceOf(line, quantity))
.tax(taxOf(line))
.status(currentLineStatus(line))
.build());
}
return out;
}
/** 行当前状态:取状态列表里最后一条。 */
static String currentLineStatus(WalmartOrderDtos.OrderLine line) {
if (line.orderLineStatuses == null || line.orderLineStatuses.orderLineStatus == null
|| line.orderLineStatuses.orderLineStatus.isEmpty()) {
return null;
}
List<WalmartOrderDtos.OrderLineStatus> list = line.orderLineStatuses.orderLineStatus;
for (int i = list.size() - 1; i >= 0; i--) {
WalmartOrderDtos.OrderLineStatus s = list.get(i);
if (s != null && s.status != null) {
return s.status;
}
}
return null;
}
/**
* 行<b>金额</b>:{@code ItemPrice.chargeAmount} 原值,不做任何除法。
*
* <p>这是金额的权威来源;{@link #unitPriceOf} 由它派生,除不尽时会给 null。</p>
*/
static Money lineAmountOf(WalmartOrderDtos.OrderLine line) {
BigDecimal amount = itemPriceTotalOf(line);
String currency = itemPriceCurrencyOf(line);
if (amount == null || currency == null) {
return null;
}
try {
return Money.of(amount, currency);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* 商品<b>单价</b>:由行金额除以数量得到,<b>除不尽时为 null</b>。
*
* <p>示例:2 件共 99.98 → 单价 49.99,可精确表示;3 件共 100.00 → 33.3333…,
* 除不尽,返回 null——用 33.3333 会让人误以为 {@code ×3} 等于原金额,
* 实际差 0.0001。需要行金额时用 {@link OrderLine#lineAmount()}。</p>
*
* <p>数量缺失或为 0 时不拆:只有 1 件(或数量未知)时行金额即单价。</p>
*/
static Money unitPriceOf(WalmartOrderDtos.OrderLine line, int quantity) {
Money amount = lineAmountOf(line);
if (amount == null) {
return null;
}
if (quantity <= 1) {
return amount;
}
BigDecimal divisor = BigDecimal.valueOf(quantity);
// 先按 4 位小数试除,再回乘校验:只有 unitPrice × quantity 精确等于行金额才认可
BigDecimal unit = amount.amount().divide(divisor, 4, java.math.RoundingMode.HALF_UP);
if (unit.multiply(divisor).compareTo(amount.amount()) != 0) {
// 除不尽:不四舍五入倒推,避免单价 × 数量 ≠ 行金额
return null;
}
return Money.of(unit.stripTrailingZeros(), amount.currencyCode());
}
/** {@code ItemPrice} 的整行金额;没有则该行第一条带金额的 charge。 */
static BigDecimal itemPriceTotalOf(WalmartOrderDtos.OrderLine line) {
WalmartOrderDtos.Charge charge = itemPriceChargeOf(line);
return charge == null || charge.chargeAmount == null ? null : charge.chargeAmount.amount;
}
/** 与 {@link #itemPriceTotalOf} 同一条 charge 上的币种。 */
static String itemPriceCurrencyOf(WalmartOrderDtos.OrderLine line) {
WalmartOrderDtos.Charge charge = itemPriceChargeOf(line);
return charge == null || charge.chargeAmount == null ? null : charge.chargeAmount.currency;
}
/**
* 行金额对应的 charge:优先 {@code ItemPrice},其次<b>同类型商品费</b>。
*
* <p><b>不把运费 / 手续费当商品价</b>:只有 {@code chargeType=PRODUCT} 的 charge
* 才能退而求其次;一条商品费都没有时返回 null,让单价保持 null,
* 而不是把 {@code Shipping} 的金额除以数量冒充单价。</p>
*/
static WalmartOrderDtos.Charge itemPriceChargeOf(WalmartOrderDtos.OrderLine line) {
if (line.charges == null || line.charges.charge == null) {
return null;
}
WalmartOrderDtos.Charge productFallback = null;
for (WalmartOrderDtos.Charge charge : line.charges.charge) {
if (charge == null || charge.chargeAmount == null || charge.chargeAmount.amount == null) {
continue;
}
if ("ItemPrice".equals(charge.chargeName)) {
return charge;
}
if (productFallback == null && "PRODUCT".equals(charge.chargeType)) {
productFallback = charge;
}
}
return productFallback;
}
/** 行税额:取所有 charge 上 tax 的合计;一条都没有时为 null。 */
static Money taxOf(WalmartOrderDtos.OrderLine line) {
if (line.charges == null || line.charges.charge == null) {
return null;
}
BigDecimal total = BigDecimal.ZERO;
String currency = null;
boolean any = false;
for (WalmartOrderDtos.Charge charge : line.charges.charge) {
if (charge == null || charge.tax == null || charge.tax.taxAmount == null
|| charge.tax.taxAmount.amount == null) {
continue;
}
total = total.add(charge.tax.taxAmount.amount);
if (currency == null) {
currency = charge.tax.taxAmount.currency;
}
any = true;
}
if (!any || currency == null) {
return null;
}
try {
return Money.of(total, currency);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* 数量解析:沃尔玛把数量放在字符串里({@code "1"}),也见过数字形式。
*
* <p>非法值记 0,与「0 表示平台未给」的约定一致,不因一行脏数据卡住整页。</p>
*/
static int parseQuantity(WalmartOrderDtos.Quantity quantity) {
if (quantity == null || quantity.amount == null || quantity.amount.trim().isEmpty()) {
return 0;
}
try {
return new BigDecimal(quantity.amount.trim()).intValue();
} catch (NumberFormatException e) {
return 0;
}
}
/** epoch 毫秒 → 三轴时间;null 时返回当前时钟(订单下单时间不该为空,兜底不抛)。 */
static PlatformTime toPlatformTime(Long epochMillis, ZoneId zone) {
if (epochMillis == null) {
return null;
}
return PlatformTime.of(Instant.ofEpochMilli(epochMillis.longValue()), zone);
}
private static Money money(WalmartOrderDtos.Amount amount) {
if (amount == null || amount.amount == null || amount.currency == null) {
return null;
}
try {
return Money.of(amount.amount, amount.currency);
} catch (IllegalArgumentException e) {
return null;
}
}
}