feat(fleet): enforce reviewed trips and original fee coverage for dispatch

This commit is contained in:
2026-10-03 04:18:52 +08:00
parent c50e9f97d1
commit 5e683da3b9
162 changed files with 9642 additions and 218 deletions
@@ -0,0 +1,17 @@
package com.baiyue.lastleg.client;
import com.baiyue.common.core.api.ApiResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
@FeignClient(name = "finance-service", contextId = "financeFeeCoverageClient", url = "${baiyue.clients.finance.url:}")
public interface FinanceFeeCoverageClient {
@PostMapping("/internal/finance/v1/delivery-fee-coverage/sources")
ApiResponse<List<Fee>> sources(@RequestHeader("X-Internal-Service-Token") String token, @RequestBody Query query);
record Query(Long customerId, List<Long> inboundIds) { }
record Fee(Long financeFeeId, Long sourceFeeId, String sourceType, int sourceVersion,
Long customerId, Long sourceInboundId, String inboundCode, String feeItemCode, String feeItemName,
String currency, BigDecimal amount, String sourceHash, String status) { }
}
@@ -23,6 +23,14 @@ import org.springframework.web.server.ResponseStatusException;
public class DeliveryTransferController {
@Resource private DeliveryTransferService service;
@GetMapping("/dispatches/{dispatchNo}/external-freight")
@PreAuthorize("hasAuthority('" + OverseasPermissions.DISPATCH_LIST + "')")
public ApiResponse<com.baiyue.lastleg.fleet.trip.FleetBookingFreight.Preview> externalFreight(
@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String dispatchNo) {
requirePlatform(user);
return ApiResponse.success(service.externalFreight(dispatchNo));
}
@PostMapping("/dispatches/{dispatchNo}/transfer-delivery")
@PreAuthorize("hasAuthority('" + OverseasPermissions.DISPATCH_TRANSFER_DELIVERY + "')")
@Operation(summary = "Create one pending outbound order and one delivery order per destination FBA warehouse")
@@ -116,7 +124,7 @@ public class DeliveryTransferController {
@PathVariable String outboundNo,
@Valid @RequestBody DeliveryRequests.Cancel request) {
requirePlatform(user);
service.cancelOutbound(outboundNo, request);
service.cancelOutbound(outboundNo, operator(user), request);
return ApiResponse.success(null);
}
@@ -0,0 +1,28 @@
package com.baiyue.lastleg.delivery.controller;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels;
import com.baiyue.lastleg.delivery.service.DeliveryFeeCoverageService;
import com.baiyue.lastleg.security.OverseasPermissions;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/platform/v1/last-leg/dispatches")
public class PlatformDeliveryFeeCoverageController {
private final DeliveryFeeCoverageService service;
@GetMapping("/{dispatchNo}/fee-coverage")
@PreAuthorize("hasAuthority('" + OverseasPermissions.DISPATCH_LIST + "')")
public ApiResponse<DeliveryFeeCoverageModels.Preview> preview(@AuthenticationPrincipal AuthenticatedUser user,
@PathVariable String dispatchNo) {
if (user == null || user.tenantId() == null) throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
if (!"PLATFORM".equals(user.appCode()) || user.tenantId() != 0L) throw new ResponseStatusException(HttpStatus.FORBIDDEN);
return ApiResponse.success(service.preview(dispatchNo));
}
}
@@ -0,0 +1,18 @@
package com.baiyue.lastleg.delivery.dto;
import com.baiyue.lastleg.client.FinanceFeeCoverageClient;
import java.util.List;
import java.time.Instant;
import jakarta.validation.constraints.*;
public final class DeliveryFeeCoverageModels {
private DeliveryFeeCoverageModels() { }
public record Cargo(Long dispatchItemId, Long warehousePalletId, String palletNo, Long orderId,
String sourceRegion, String sourceInboundId, String inboundCode, long packages, String dispatchInboundCode) { }
public record Preview(String dispatchNo, boolean sourceComplete, String blockReason, String cargoHash,
List<Cargo> cargo, List<FinanceFeeCoverageClient.Fee> feeSources) { }
public record Selection(@NotNull @Positive Long financeFeeId, @Min(1) int sourceVersion,
@NotBlank @Size(max=128) String sourceHash, @NotEmpty @Size(max=3) List<@NotBlank @Pattern(regexp="DELIVERY_FEE|LOADING_FEE|APPOINTMENT_FEE") String> services) { }
public record Reference(FinanceFeeCoverageClient.Fee source, List<String> services) { }
public record Evidence(String cargoHash, List<Cargo> cargo, List<Reference> references, String operatorId, Instant confirmedAt) { }
}
@@ -6,6 +6,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.validation.Valid;
import com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels.Selection;
import java.util.List;
import java.util.Collections;
import java.math.BigDecimal;
@@ -30,7 +31,10 @@ public final class DeliveryRequests {
@Size(max = 128) String appointmentAccount,
@Size(max = 128) String sellerName,
@Size(max = 1000) String remark,
@NotNull @Valid @Size(min = 1, max = 20) List<FeeItem> fees) {}
@NotNull @Valid @Size(max = 20) List<FeeItem> fees,
@Size(max = 64) String externalFreightHash,
@Size(max = 64) String feeCoverageCargoHash,
@Size(max = 2000) List<@NotNull @Valid Selection> feeCoverage) {}
public record FeeItem(@NotBlank @Size(max = 64) String feeType,
@NotBlank @Size(max = 128) String feeName,
@@ -42,13 +42,14 @@ public final class DeliveryResponses {
BigDecimal weightKg, BigDecimal volumeCbm) {}
public record DeliveryFeeRow(Long id, String feeDirection, String feeType, String currency,
BigDecimal amount, String remark) {}
BigDecimal amount, String remark, String reviewStatus, String sourceStatus, String voidStatus) {}
public record DeliveryOperationRow(Long id, LocalDateTime operatedAt, String operationNode,
String operatorName, String result) {}
public record DeliveryDetail(DeliveryRow order, List<DeliverySku> skus,
List<DeliveryFeeRow> fees, List<DeliveryOperationRow> operations) {}
List<DeliveryFeeRow> fees, List<DeliveryOperationRow> operations,
DeliveryFeeCoverageModels.Evidence feeCoverage) {}
/** palletNo is the warehouse-authoritative physical pallet code after inbound assignment. */
public record OutboundPalletRow(Long id, String palletNo, String cartonMarks, String inboundCode,
@@ -30,6 +30,7 @@ public class OutboundOrder {
private BigDecimal volumeCbm;
private String idempotencyKey;
private String requestHash;
private String feeCoverageJson;
private String createdBy;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@@ -10,6 +10,8 @@ import java.util.List;
@Mapper
public interface DeliveryOperationMapper extends BaseMapper<DeliveryOperation> {
@Select("SELECT MAX(created_at) FROM ll_delivery_operation WHERE customer_id=#{customerId} AND delivery_order_id=#{deliveryOrderId} AND operation_node='RETURN_COMPLETED'")
java.time.LocalDateTime returnedAt(@Param("customerId") String customerId, @Param("deliveryOrderId") Long deliveryOrderId);
@Select("SELECT * FROM ll_delivery_operation WHERE customer_id=#{customerId} AND delivery_order_id=#{deliveryOrderId} ORDER BY created_at,id")
List<DeliveryOperation> findByDelivery(@Param("customerId") String customerId,
@Param("deliveryOrderId") Long deliveryOrderId);
@@ -9,6 +9,8 @@ import java.util.List;
@Mapper
public interface DeliveryOrderMapper extends BaseMapper<DeliveryOrder> {
@Select("SELECT * FROM ll_delivery_order WHERE customer_id=#{customerId} AND outbound_order_id=#{outboundOrderId} ORDER BY id")
List<DeliveryOrder> findByOutbound(@Param("customerId") String customerId, @Param("outboundOrderId") Long outboundOrderId);
@Select("SELECT * FROM ll_delivery_order WHERE customer_id=#{customerId} AND delivery_no=#{deliveryNo} LIMIT 1")
DeliveryOrder findByNo(@Param("customerId") String customerId, @Param("deliveryNo") String deliveryNo);
@Select("SELECT * FROM ll_delivery_order WHERE customer_id=#{customerId} AND delivery_no=#{deliveryNo} LIMIT 1 FOR UPDATE")
@@ -0,0 +1,34 @@
package com.baiyue.lastleg.delivery.mapper;
import com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** Reconstruct every selected inbound source, including shared pallets and already picked quantities. */
@Mapper
public interface DispatchFeeCargoMapper {
@Select("""
SELECT di.id AS dispatchItemId,di.warehouse_pallet_id AS warehousePalletId,di.pallet_no AS palletNo,
b.inbound_order_id AS orderId,o.source_region AS sourceRegion,o.source_inbound_id AS sourceInboundId,
b.inbound_code AS inboundCode,SUM(p.available_packages+COALESCE(picked.packages,0)) AS packages,di.inbound_code AS dispatchInboundCode
FROM ll_dispatch_item di
JOIN ll_inventory_position p ON p.customer_id=di.customer_id AND p.pallet_id=di.warehouse_pallet_id
AND p.overseas_warehouse_id=di.overseas_warehouse_id
JOIN ll_inventory_balance b ON b.id=p.balance_id AND b.customer_id=di.customer_id
LEFT JOIN ll_order o ON o.id=b.inbound_order_id AND o.customer_id=di.customer_id
LEFT JOIN (SELECT pk.dispatch_item_id,pk.inventory_position_id,SUM(pk.packages) AS packages
FROM ll_dispatch_pda_pick pk JOIN ll_dispatch_pda_task task ON task.id=pk.task_id AND task.customer_id=pk.customer_id
WHERE task.dispatch_order_id=#{dispatchId} AND pk.customer_id=#{customerId}
GROUP BY pk.dispatch_item_id,pk.inventory_position_id) picked
ON picked.dispatch_item_id=di.id AND picked.inventory_position_id=p.id
WHERE di.dispatch_order_id=#{dispatchId} AND di.customer_id=#{customerId}
AND (di.plan_pallet_id IS NULL OR EXISTS (
SELECT 1 FROM ll_inbound_plan_pallet_allocation a
JOIN ll_inbound_plan_line line ON line.id=a.line_id AND line.customer_id=di.customer_id
WHERE a.pallet_id=di.plan_pallet_id AND line.order_id=b.inbound_order_id))
GROUP BY di.id,di.warehouse_pallet_id,di.pallet_no,b.inbound_order_id,o.source_region,o.source_inbound_id,b.inbound_code,di.inbound_code
HAVING SUM(p.available_packages+COALESCE(picked.packages,0))>0
ORDER BY di.id,b.inbound_order_id
""")
List<DeliveryFeeCoverageModels.Cargo> list(@Param("customerId") String customerId, @Param("dispatchId") long dispatchId);
}
@@ -27,6 +27,7 @@ import java.util.*;
@Service
public class DeliveryDocumentService {
@Resource private DeliveryOrderMapper orders;
@Resource private OutboundOrderMapper outboundOrders;
@Resource private DeliveryDocumentRevisionMapper revisions;
@Resource private DeliveryOperationMapper operations;
@Resource private DeliveryDocumentFileGateway files;
@@ -84,16 +85,19 @@ public class DeliveryDocumentService {
return new Category(category, values.isEmpty() ? "MISSING" : "UPLOADED", values.size(), values);
}).toList();
LocalDateTime now = LocalDateTime.now();
boolean receiptSaved = !bindings.getOrDefault(DeliveryDocumentCategory.RECEIPT, List.of()).isEmpty();
boolean autoCompleted = receiptSaved && !"DELIVERED".equals(order.getStatus());
if (autoCompleted) {
if (!DeliveryStatusPolicy.canTransition(order.getStatus(), "DELIVERED")) throw conflict("当前派送状态不允许通过签收文件完成");
// A read avoids reversing outbound -> delivery lock order. An uncommitted departure remains ineligible.
var outbound = outboundOrders.findByNo(customerId, order.getOutboundNo());
if (outbound == null || !"OUTBOUNDED".equals(outbound.getStatus())) throw conflict("请先完成实际出库,再保存签收资料完成派送");
}
order.setBolNo(request.bolNo() == null ? "" : request.bolNo().trim());
order.setDocumentsJson(write(categories));
order.setVersion(version(order) + 1);
order.setUpdatedAt(now);
boolean receiptSaved = !bindings.getOrDefault(DeliveryDocumentCategory.RECEIPT, List.of()).isEmpty();
boolean autoCompleted = receiptSaved && !"DELIVERED".equals(order.getStatus());
if (autoCompleted) {
if (!DeliveryStatusPolicy.canTransition(order.getStatus(), "DELIVERED")) {
throw conflict("当前派送状态不允许通过签收文件完成");
}
order.setStatus("DELIVERED");
order.setSignedAt(now);
}
@@ -1,6 +1,7 @@
package com.baiyue.lastleg.delivery.model;
package com.baiyue.lastleg.delivery.service;
import com.baiyue.lastleg.delivery.dto.DeliveryDocumentDtos.*;
import com.baiyue.lastleg.delivery.model.DeliveryDocumentCategory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -0,0 +1,121 @@
package com.baiyue.lastleg.delivery.service;
import com.baiyue.lastleg.client.FinanceFeeCoverageClient;
import com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels;
import com.baiyue.lastleg.delivery.dto.DeliveryRequests;
import java.time.Instant;
import com.baiyue.lastleg.delivery.mapper.DispatchFeeCargoMapper;
import com.baiyue.lastleg.dispatch.entity.DispatchItem;
import com.baiyue.lastleg.dispatch.mapper.DispatchItemMapper;
import com.baiyue.lastleg.dispatch.mapper.DispatchOrderMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class DeliveryFeeCoverageService {
private final DispatchOrderMapper dispatches;
private final DispatchItemMapper items;
private final DispatchFeeCargoMapper sources;
private final FinanceFeeCoverageClient finance;
private final ObjectMapper json;
private final String token;
public DeliveryFeeCoverageService(DispatchOrderMapper dispatches, DispatchItemMapper items, DispatchFeeCargoMapper sources,
FinanceFeeCoverageClient finance, ObjectMapper json, @Value("${baiyue.security.internal-service-token}") String token) {
this.dispatches=dispatches; this.items=items; this.sources=sources; this.finance=finance; this.json=json; this.token=token;
}
@Transactional(readOnly = true, isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public DeliveryFeeCoverageModels.Preview preview(String dispatchNo) {
var dispatch = dispatches.findGlobalByDispatchNo(dispatchNo.trim());
if (dispatch == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "排车单不存在");
var selected = items.findByDispatchOrder(dispatch.getCustomerId(), dispatch.getId());
var cargo = sources.list(dispatch.getCustomerId(), dispatch.getId());
String reason = incomplete(selected, cargo);
var inboundIds = new TreeSet<Long>();
if (reason == null) for (var row : cargo) if ("FIRSTLEG".equals(row.sourceRegion())) {
try { long id = Long.parseLong(row.sourceInboundId()); if (id < 1) throw new NumberFormatException(); inboundIds.add(id); }
catch (RuntimeException invalid) { reason = "货物缺少原头程入仓单关联,请先核对来源"; break; }
}
List<FinanceFeeCoverageClient.Fee> fees = List.of();
if (reason == null && !inboundIds.isEmpty()) fees = load(dispatch.getCustomerId(), List.copyOf(inboundIds));
try {
String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(
json.writeValueAsString(List.of(dispatch.getDispatchNo(), dispatch.getCustomerId(), cargo,
selected.stream().map(item -> Arrays.asList(item.getId(), item.getPackageCount(), item.getOverseasWarehouseId(),
item.getDestinationType(), item.getDestinationWarehouseCode(), item.getFbaWarehouseCode(),
item.getDeliveryAddress(), item.getPostalCode())).toList())).getBytes(StandardCharsets.UTF_8)));
return new DeliveryFeeCoverageModels.Preview(dispatch.getDispatchNo(), reason == null, reason, hash, cargo, fees);
} catch (java.security.NoSuchAlgorithmException | com.fasterxml.jackson.core.JsonProcessingException error) { throw new IllegalStateException(error); }
}
private List<FinanceFeeCoverageClient.Fee> load(String customerId, List<Long> inboundIds) {
try {
var result = finance.sources(token, new FinanceFeeCoverageClient.Query(Long.valueOf(customerId), inboundIds));
if (result == null || !result.successful() || result.data() == null) throw unavailable();
if (result.data().stream().anyMatch(fee -> fee.financeFeeId() == null || fee.financeFeeId() < 1 || fee.sourceFeeId() == null
|| !Objects.equals(fee.customerId(), Long.valueOf(customerId)) || fee.sourceVersion() < 1
|| !inboundIds.contains(fee.sourceInboundId()) || fee.sourceHash() == null || fee.sourceHash().isBlank()
|| fee.amount() == null || fee.amount().signum() < 0 || !"CNY".equals(fee.currency())
|| !Set.of("INBOUND_FEE", "CONTAINER_FEE").contains(fee.sourceType())
|| !Set.of("AVAILABLE", "SETTLED").contains(fee.status()))) throw unavailable();
return result.data();
} catch (RuntimeException error) { throw unavailable(); }
}
private static String incomplete(List<DispatchItem> selected, List<DeliveryFeeCoverageModels.Cargo> cargo) {
if (selected.isEmpty()) return "排车单没有待发运货物";
var totals = cargo.stream().collect(Collectors.groupingBy(DeliveryFeeCoverageModels.Cargo::dispatchItemId,
Collectors.summingLong(DeliveryFeeCoverageModels.Cargo::packages)));
var ids = selected.stream().map(DispatchItem::getId).collect(Collectors.toSet());
if (!ids.equals(totals.keySet())) return "实际货物来源尚未齐全,请先完成收货并核对实物托盘";
for (var item : selected) if (item.getPackageCount() == null || totals.get(item.getId()).longValue() != item.getPackageCount())
return "实物库存及本次已拣数量与排车箱数不一致,请先核对货物范围";
return null;
}
public record Decision(Set<String> includedServices, DeliveryFeeCoverageModels.Evidence evidence, Set<Long> externalItems) {
public static Decision none() { return new Decision(Set.of(), null, Set.of()); }
public List<DeliveryFeeCoverageModels.Cargo> uncovered(String service) {
if (evidence == null) return List.of();
return evidence.cargo().stream().filter(row -> !covers(row, service, evidence.references(), externalItems)).toList();
}
}
public Decision confirm(String dispatchNo, DeliveryRequests.Transfer request, String operator, Set<Long> externalItems) {
if (request.feeCoverage() == null || request.feeCoverage().isEmpty()) return Decision.none();
var preview = preview(dispatchNo);
if (!preview.sourceComplete()) throw conflict(preview.blockReason());
if (!Objects.equals(preview.cargoHash(), request.feeCoverageCargoHash())) throw conflict("原费用对应货物已变化,请重新核对覆盖范围");
var references = new ArrayList<DeliveryFeeCoverageModels.Reference>();
var scopes = new HashSet<String>();
for (var selection : request.feeCoverage()) {
var fee = preview.feeSources().stream().filter(row -> Objects.equals(row.financeFeeId(), selection.financeFeeId())).findFirst()
.orElseThrow(() -> conflict("原费用不属于本次实际货物,或已审核状态/有效性发生变化"));
if (fee.sourceVersion() != selection.sourceVersion() || !Objects.equals(fee.sourceHash(), selection.sourceHash()))
throw conflict("原费用版本已变化,请重新确认服务覆盖范围");
var services = new TreeSet<>(selection.services());
if (services.isEmpty() || !Set.of("DELIVERY_FEE", "LOADING_FEE", "APPOINTMENT_FEE").containsAll(services))
throw conflict("请选择本票原费用明确包含的服务");
for (var service : services) if (!scopes.add(fee.sourceInboundId() + ":" + service))
throw conflict("同一票同一服务只能引用一项原费用");
references.add(new DeliveryFeeCoverageModels.Reference(fee, List.copyOf(services)));
}
var included = new HashSet<String>();
for (String service : List.of("DELIVERY_FEE", "LOADING_FEE", "APPOINTMENT_FEE"))
if (preview.cargo().stream().allMatch(row -> covers(row, service, references, externalItems))) included.add(service);
return new Decision(Set.copyOf(included), new DeliveryFeeCoverageModels.Evidence(preview.cargoHash(), preview.cargo(),
List.copyOf(references), operator, Instant.now()), Set.copyOf(externalItems));
}
private static boolean covers(DeliveryFeeCoverageModels.Cargo cargo, String service,
List<DeliveryFeeCoverageModels.Reference> references, Set<Long> externalItems) {
if ("DELIVERY_FEE".equals(service) && externalItems.contains(cargo.dispatchItemId())) return true;
return "FIRSTLEG".equals(cargo.sourceRegion()) && references.stream().anyMatch(reference ->
reference.source().sourceInboundId().toString().equals(cargo.sourceInboundId()) && reference.services().contains(service));
}
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
private static ResponseStatusException unavailable() { return new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "原费用来源暂不可用,请稍后重试"); }
}
@@ -1,5 +1,9 @@
package com.baiyue.lastleg.delivery.service;
import com.baiyue.lastleg.fleet.trip.FleetDispatchBindingGuard;
import com.baiyue.lastleg.fleet.trip.FleetDispatchGateway;
import com.baiyue.lastleg.fleet.trip.FleetBookingFreight;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -123,6 +127,25 @@ public class DeliveryTransferService {
@Resource private RelabelApplicationService relabelService;
@Resource private LastlegOrderNoGenerator orderNoGenerator;
@Resource private ObjectMapper objectMapper;
@Resource private FleetDispatchBindingGuard fleetBindings;
@Resource private FleetBookingFreight bookingFreight;
@Resource private DeliveryFeeCoverageService feeCoverage;
@Transactional(readOnly = true, isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public FleetBookingFreight.Preview externalFreight(String dispatchNo) {
DispatchOrder dispatch = dispatchOrders.findGlobalByDispatchNo(trim(dispatchNo));
if (dispatch == null) throw notFound("Dispatch order not found");
return externalFreight(dispatch, dispatchItems.findByDispatchOrder(dispatch.getCustomerId(), dispatch.getId()));
}
private FleetBookingFreight.Preview externalFreight(DispatchOrder dispatch, List<DispatchItem> items) {
return bookingFreight.preview(dispatch.getId(), dispatch.getDispatchNo(), dispatch.getCustomerId(), items.stream()
.map(item -> new FleetDispatchGateway.SourceCargo(item.getInboundCode(),
item.getWarehousePalletId() == null ? null : item.getWarehousePalletId().toString(), item.getPalletNo(),
Objects.requireNonNullElse(item.getPackageCount(), 0), FleetDispatchGateway.destinationKey(item.getDestinationType(),
item.getDestinationWarehouseCode(), item.getFbaWarehouseCode(), item.getDeliveryAddress(), item.getPostalCode())))
.toList());
}
@Transactional
public DeliveryResponses.TransferResult platformTransfer(String dispatchNo, String operatorId,
@@ -135,6 +158,8 @@ public class DeliveryTransferService {
@Transactional
public DeliveryResponses.TransferResult merchantTransfer(String customerId, String dispatchNo, String operatorId,
DeliveryRequests.Transfer request) {
if (request.feeCoverage() != null && !request.feeCoverage().isEmpty())
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "原运费服务覆盖由平台确认");
DispatchOrder found = dispatchOrders.findByDispatchNo(customerId, dispatchNo);
if (found == null) throw notFound("Dispatch order not found");
DispatchOrder dispatch = dispatchOrders.lockById(customerId, found.getId());
@@ -145,16 +170,20 @@ public class DeliveryTransferService {
private DeliveryResponses.TransferResult transferResolved(DispatchOrder dispatch, String operatorId,
DeliveryRequests.Transfer request) {
String customerId = dispatch.getCustomerId();
String requestHash = transferRequestHash(request);
OutboundOrder replay = outboundOrders.findByIdempotency(customerId, request.idempotencyKey().trim());
if (replay != null) {
if (!dispatch.getId().equals(replay.getDispatchOrderId())) throw conflict("Idempotency key belongs to another dispatch");
return result(replay, requireDeliveries(customerId, replay.getId()), true);
return replayTransfer(replay, requestHash);
}
OutboundOrder existing = outboundOrders.lockByDispatch(customerId, dispatch.getId());
if (existing != null) return result(existing, requireDeliveries(customerId, existing.getId()), true);
if (existing != null) return replayTransfer(existing, requestHash);
if (Set.of("CANCELLED", "DEPARTED", "PARTIAL_DEPARTED", "COMPLETED").contains(dispatch.getStatus())) {
throw conflict("Dispatch cannot be transferred to delivery in its current status");
}
fleetBindings.requireMatchingAssignment(dispatch.getId(),
new FleetDispatchGateway.Assignment(dispatch.getVehiclePlate(), dispatch.getDriverName(), dispatch.getDriverPhone()),
new FleetDispatchGateway.Assignment(request.vehiclePlate(), request.driverName(), request.driverPhone()));
dispatchItems.bindReceivedPallets(customerId, dispatch.getId());
List<DispatchItem> items = dispatchItems.findByDispatchOrder(customerId, dispatch.getId());
if (items.isEmpty()) throw conflict("Dispatch has no pallets");
@@ -162,7 +191,16 @@ public class DeliveryTransferService {
throw conflict("All dispatch pallets must be received before transfer to delivery");
}
if (!StringUtils.hasText(dispatch.getOverseasWarehouseId())) throw conflict("Dispatch warehouse is required");
validateTransferFees(request);
var freight = externalFreight(dispatch, items);
if ((!freight.quotes().isEmpty() || StringUtils.hasText(request.externalFreightHash()))
&& !Objects.equals(freight.snapshotHash(), request.externalFreightHash()))
throw conflict("外接实收或约定运费已变化,请重新打开转派送核对");
var quotedIncomingNos = freight.quotes().stream().map(FleetBookingFreight.Quote::incomingNo).collect(Collectors.toSet());
var externalItems = items.stream().filter(item -> quotedIncomingNos.contains(item.getInboundCode())).map(DispatchItem::getId).collect(Collectors.toSet());
var coverage = request.feeCoverage() == null || request.feeCoverage().isEmpty() ? DeliveryFeeCoverageService.Decision.none()
: feeCoverage.confirm(dispatch.getDispatchNo(), request, operatorId, externalItems);
validateTransferFees(request, freight.requiresDeliveryFee(), coverage.includedServices());
if (!freight.priorInboundCodes().isEmpty()) feeSources.requireNoActiveDeliveryReceivables(customerId, freight.priorInboundCodes());
LocalDateTime now = LocalDateTime.now();
OutboundOrder outbound = new OutboundOrder();
@@ -173,10 +211,15 @@ public class DeliveryTransferService {
outbound.setLxCodes(resolveLxCodes(customerId, items));
outbound.setPackageCount(items.stream().map(DispatchItem::getPackageCount).filter(Objects::nonNull).mapToInt(Integer::intValue).sum());
outbound.setPalletCount(items.size());
outbound.setGrossWeightKg(sum(items, DispatchItem::getGrossWeightKg));
outbound.setGrossWeightKg(sumKnownPhysicalWeight(items, DispatchItem::getGrossWeightKg));
outbound.setVolumeWeightKg(sum(items, DispatchItem::getVolumeWeightKg));
outbound.setVolumeCbm(sum(items, DispatchItem::getVolumeCbm));
outbound.setIdempotencyKey(request.idempotencyKey().trim());
outbound.setRequestHash(requestHash);
if (coverage.evidence() != null) {
try { outbound.setFeeCoverageJson(objectMapper.writeValueAsString(coverage.evidence())); }
catch (JsonProcessingException exception) { throw new IllegalStateException("费用覆盖确认无法保存", exception); }
}
outbound.setCreatedBy(operatorId); outbound.setCreatedAt(now); outbound.setUpdatedAt(now);
try {
outboundOrders.insert(outbound);
@@ -185,11 +228,11 @@ public class DeliveryTransferService {
// the document created by the winning transaction rather than receive a false failure.
OutboundOrder concurrent = outboundOrders.findByIdempotency(customerId, request.idempotencyKey().trim());
if (concurrent != null && dispatch.getId().equals(concurrent.getDispatchOrderId())) {
return result(concurrent, requireDeliveries(customerId, concurrent.getId()), true);
return replayTransfer(concurrent, requestHash);
}
concurrent = outboundOrders.lockByDispatch(customerId, dispatch.getId());
if (concurrent != null) {
return result(concurrent, requireDeliveries(customerId, concurrent.getId()), true);
return replayTransfer(concurrent, requestHash);
}
throw conflict("Dispatch was concurrently transferred to delivery");
}
@@ -250,25 +293,57 @@ public class DeliveryTransferService {
delivery.setPackageCount(groupItems.stream().map(DispatchItem::getPackageCount).filter(Objects::nonNull).mapToInt(Integer::intValue).sum());
delivery.setPalletCount(groupItems.size());
delivery.setTotalVolumeCbm(sum(groupItems, DispatchItem::getVolumeCbm));
delivery.setTotalWeightKg(sum(groupItems, DispatchItem::getGrossWeightKg)); delivery.setExpectedArrivalAt(dispatch.getEstimatedArrivalAt()); delivery.setRemark(trim(request.remark()));
delivery.setTotalWeightKg(sumKnownPhysicalWeight(groupItems, DispatchItem::getGrossWeightKg)); delivery.setExpectedArrivalAt(dispatch.getEstimatedArrivalAt()); delivery.setRemark(trim(request.remark()));
delivery.setIdempotencyKey(childKey(request.idempotencyKey(), "DEST-" + groupIndex++)); delivery.setCreatedBy(operatorId);
delivery.setCreatedAt(now); delivery.setUpdatedAt(now); deliveryOrders.insert(delivery);
recordOperation(customerId, delivery.getId(), operatorId, "CREATE_DELIVERY", "按目的FBA仓生成派送单", now);
bindTailOrders(customerId, groupItems, outbound.getOutboundNo(), delivery.getDeliveryNo(), request.remark(), now);
deliveries.add(delivery);
}
for (var quote : freight.quotes()) {
var source = items.stream().filter(item -> quote.incomingNo().equals(item.getInboundCode())).findFirst().orElseThrow();
var destination = deliveries.stream().filter(item -> deliveryGroupKey(source).equals(item.getDeliveryGroupKey())).findFirst().orElseThrow();
recordOperation(customerId, destination.getId(), operatorId, "CONFIRM_EXTERNAL_FREIGHT",
"外接预订 " + quote.bookingNo() + ";实收确认版本 " + quote.recordVersion() + ";约定运费 "
+ quote.currency() + " " + quote.amount().toPlainString(), now);
// An explicitly agreed free shipment remains a commercial fact, not a fabricated zero fee.
if (quote.amount().signum() == 0) continue;
feeSources.publishApproved(operatorId, "FLEET:" + quote.bookingNo() + ":" + dispatch.getDispatchNo() + ":FREIGHT",
new OverseasFeeSourceDtos.SaveRequest(customerId, quote.customerName(),
"OVERSEAS_DELIVERY_FEE", "DELIVERY_ORDER", destination.getId(), destination.getDeliveryNo(),
null, null, quote.inboundCode(), null, null, null, parseLong(destination.getOverseasWarehouseId()),
"DELIVERY_FEE", "外接运费(" + quote.bookingNo() + ")", "RECEIVABLE", null, null, null,
null, null, null, null, null, LocalDate.now(), quote.currency(), quote.amount(), quote.quantity(),
quote.quantityUnit(), quote.unitPrice(), null, null));
}
DeliveryOrder feeDelivery = deliveries.get(0);
LastlegOrder firstOrder = firstTailOrder(customerId, items);
List<DeliveryRequests.FeeItem> feeInputs = request.fees() == null ? List.of() : request.fees();
var quotedIncoming = freight.quotes().stream().map(FleetBookingFreight.Quote::incomingNo).collect(Collectors.toSet());
for (DeliveryRequests.FeeItem input : feeInputs) {
feeSources.publishApproved(operatorId, childKey(request.idempotencyKey(), input.feeType()),
new OverseasFeeSourceDtos.SaveRequest(customerId, feeDelivery.getCustomerName(),
"OVERSEAS_DELIVERY_FEE", "DELIVERY_ORDER", feeDelivery.getId(), feeDelivery.getDeliveryNo(),
String feeCode = input.feeType().trim().toUpperCase(Locale.ROOT);
var uncovered = coverage.uncovered(feeCode);
var uncoveredItemIds = uncovered.stream().map(com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels.Cargo::dispatchItemId).collect(Collectors.toSet());
var chargeItems = coverage.evidence() != null && "RECEIVABLE".equals(input.direction())
? items.stream().filter(item -> uncoveredItemIds.contains(item.getId())).toList()
: "RECEIVABLE".equals(input.direction()) && "DELIVERY_FEE".equals(feeCode) && freight.requiresDeliveryFee()
? items.stream().filter(item -> !quotedIncoming.contains(item.getInboundCode())).toList() : items;
var feeDestination = "DELIVERY_FEE".equalsIgnoreCase(input.feeType()) && !chargeItems.isEmpty()
? deliveries.stream().filter(item -> deliveryGroupKey(chargeItems.get(0)).equals(item.getDeliveryGroupKey())).findFirst().orElseThrow()
: feeDelivery;
LastlegOrder firstOrder = firstTailOrder(customerId, chargeItems);
if (coverage.evidence() != null && "RECEIVABLE".equals(input.direction())) {
var uncoveredOrderIds = uncovered.stream().map(com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels.Cargo::orderId).filter(Objects::nonNull).distinct().toList();
firstOrder = uncoveredOrderIds.size() == 1 ? tailOrders.selectById(uncoveredOrderIds.get(0)) : null;
if (firstOrder != null && !customerId.equals(firstOrder.getCustomerId())) throw conflict("新增费用来源客户不一致");
}
feeSources.publishApproved(operatorId, childKey(request.idempotencyKey(), input.direction() + ":" + feeCode),
new OverseasFeeSourceDtos.SaveRequest(customerId, feeDestination.getCustomerName(),
"OVERSEAS_DELIVERY_FEE", "DELIVERY_ORDER", feeDestination.getId(), feeDestination.getDeliveryNo(),
firstOrder == null ? null : firstOrder.getId(), null,
firstOrder == null ? null : firstOrder.getInboundCode(), null,
firstOrder == null ? null : parseLong(firstOrder.getSourceContainerBookingId()),
firstOrder == null ? null : firstOrder.getContainerNo(), parseLong(feeDelivery.getOverseasWarehouseId()),
input.feeType().trim(), input.feeName().trim(), input.direction(), input.supplierId(),
firstOrder == null ? null : firstOrder.getContainerNo(), parseLong(feeDestination.getOverseasWarehouseId()),
feeCode, input.feeName().trim(), input.direction(), input.supplierId(),
input.supplierName(), input.supplierCategory(), input.settlementMode(), input.paidAt(),
input.paymentMethod(), input.paymentReferenceNo(), input.paymentVoucherFileIds(), LocalDate.now(),
input.currency(), input.amount(), input.chargeableQuantity(), input.quantityUnit(), input.unitPrice(),
@@ -277,27 +352,45 @@ public class DeliveryTransferService {
return result(outbound, deliveries, false);
}
private void validateTransferFees(DeliveryRequests.Transfer request) {
private DeliveryResponses.TransferResult replayTransfer(OutboundOrder outbound, String requestHash) {
if (!requestHash.equals(outbound.getRequestHash()))
throw conflict("转派送请求与原已保存内容不一致,请查看原单据;费用调整须通过正式费用更正流程");
return result(outbound, requireDeliveries(outbound.getCustomerId(), outbound.getId()), true);
}
String transferRequestHash(DeliveryRequests.Transfer request) {
// A new command key cannot change an already transferred dispatch's business content.
com.fasterxml.jackson.databind.node.ObjectNode content = objectMapper.valueToTree(request);
content.remove("idempotencyKey");
if (request.feeCoverage() == null || request.feeCoverage().isEmpty()) {
content.remove("feeCoverage"); content.remove("feeCoverageCargoHash");
}
return hash(content);
}
private void validateTransferFees(DeliveryRequests.Transfer request, boolean requiresDeliveryFee, Set<String> covered) {
List<DeliveryRequests.FeeItem> inputs = request.fees() == null ? List.of() : request.fees();
if (inputs.isEmpty()) throw conflict("Delivery fee is required");
Set<String> allowed = Set.of("DELIVERY_FEE", "LOADING_FEE", "APPOINTMENT_FEE");
Set<String> seen = new HashSet<>();
for (DeliveryRequests.FeeItem input : inputs) {
String feeType = input.feeType().trim().toUpperCase(Locale.ROOT);
if (!allowed.contains(feeType)) throw conflict("Unsupported delivery fee type: " + feeType);
if (!seen.add(feeType)) throw conflict("Duplicate delivery fee type: " + feeType);
if (!seen.add(input.direction() + ":" + feeType)) throw conflict("Duplicate delivery fee type: " + feeType);
if ("RECEIVABLE".equals(input.direction()) && covered.contains(feeType)) throw conflict("本次货物的该服务已由原费用覆盖,请勿重复登记应收");
if (!Set.of("CNY", "USD").contains(input.currency().trim().toUpperCase(Locale.ROOT)))
throw conflict("Delivery fees only support CNY or USD");
if (input.amount().signum() <= 0) throw conflict("Delivery fee amount must be greater than zero");
}
if (!seen.contains("DELIVERY_FEE")) throw conflict("Delivery fee is required");
if (requiresDeliveryFee && !covered.contains("DELIVERY_FEE") && !seen.contains("RECEIVABLE:DELIVERY_FEE")) throw conflict("尚未有约定运费的货物须填写派送费");
if (!requiresDeliveryFee && inputs.stream().anyMatch(item -> "DELIVERY_FEE".equalsIgnoreCase(item.feeType().trim())
&& "RECEIVABLE".equals(item.direction()))) throw conflict("本排车全部货物已带入外接约定运费,请勿重复填写派送应收");
if (Set.of("FLOOR", "MIXED").contains(request.loadingType().trim().toUpperCase(Locale.ROOT))
&& !seen.contains("LOADING_FEE")) {
&& !covered.contains("LOADING_FEE") && !seen.contains("RECEIVABLE:LOADING_FEE")) {
throw conflict("Loading fee is required for floor or mixed loading");
}
if ("BUY_APPOINTMENT".equalsIgnoreCase(trim(request.appointmentAccount()))) {
if (!StringUtils.hasText(request.sellerName())) throw conflict("Seller name is required when buying an appointment");
if (!seen.contains("APPOINTMENT_FEE")) throw conflict("Appointment fee is required when buying an appointment");
if (!covered.contains("APPOINTMENT_FEE") && !seen.contains("RECEIVABLE:APPOINTMENT_FEE")) throw conflict("Appointment fee is required when buying an appointment");
}
}
@@ -976,10 +1069,21 @@ public class DeliveryTransferService {
}
@Transactional
public void cancelOutbound(String outboundNo, DeliveryRequests.Cancel request) {
public void cancelOutbound(String outboundNo, String operatorId, DeliveryRequests.Cancel request) {
OutboundOrder observed = outboundOrders.findGlobalByNo(trim(outboundNo));
if (observed == null) throw notFound("Outbound order not found");
// Dispatch picking/departure owns the same dispatch -> outbound lock order.
DispatchOrder dispatch = observed.getDispatchOrderId() == null ? null
: dispatchOrders.lockById(observed.getCustomerId(), observed.getDispatchOrderId());
OutboundOrder outbound = outboundOrders.lockGlobalByNo(trim(outboundNo));
if (outbound == null) throw notFound("Outbound order not found");
if ("CANCELLED".equals(outbound.getStatus())) return;
if (outbound.getDispatchOrderId() != null) {
if (dispatch == null || !Objects.equals(dispatch.getId(), outbound.getDispatchOrderId())
|| !"PENDING_DEPARTURE".equals(dispatch.getStatus()) || value(dispatch.getPickedPackageCount()) > 0
|| value(dispatch.getShippedPackageCount()) > 0) throw conflict("排车已开始执行,不能直接取消出库");
fleetBindings.requireUnbound(dispatch.getId());
}
if (!Set.of("WAIT_OUTBOUND", "WAIT_PICK").contains(outbound.getStatus())) {
throw conflict("Only an unexecuted outbound order can be cancelled");
}
@@ -994,6 +1098,22 @@ public class DeliveryTransferService {
throw conflict("Outbound order cannot be cancelled while delivery is in progress");
LocalDateTime now = LocalDateTime.now();
for (DeliveryOrder delivery : existingDeliveries) {
int voidRequests = 0;
for (var fee : feeSources.listForBusiness(customerId, "DELIVERY_ORDER", delivery.getId())) {
if ("RECEIVABLE".equals(fee.getDirection()) && "DELIVERY_FEE".equals(fee.getFeeItemCode())
&& "APPROVED".equals(fee.getReviewStatus()) && "ACTIVE".equals(fee.getSourceStatus())) {
feeSources.voidSource(fee.getSourceFeeId(), operatorId, new OverseasFeeSourceDtos.VoidRequest(
fee.getSourceVersion(), "取消出库 " + outboundNo + ";详见派送单取消原因",
"CANCEL_OUTBOUND:" + outbound.getId() + ":" + fee.getSourceFeeId()));
voidRequests++;
}
}
recordOperation(customerId, delivery.getId(), operatorId, "CANCEL_OUTBOUND",
"出库取消;" + voidRequests + "笔未履行派送应收已申请撤销,其他费用保留待核对", now);
String reason = request.reason().trim();
for (int offset = 0; offset < reason.length(); offset += 480)
recordOperation(customerId, delivery.getId(), operatorId, "CANCEL_OUTBOUND_REASON",
"(" + (offset / 480 + 1) + ") " + reason.substring(offset, Math.min(offset + 480, reason.length())), now);
delivery.setStatus("CANCELLED"); delivery.setVersion(value(delivery.getVersion()) + 1);
delivery.setUpdatedAt(now); deliveryOrders.updateById(delivery);
}
@@ -1019,9 +1139,26 @@ public class DeliveryTransferService {
return;
}
if (!existingDeliveries.isEmpty()) {
for (LastlegOrder order : tailOrders.selectList(new LambdaQueryWrapper<LastlegOrder>().eq(LastlegOrder::getCustomerId, customerId).eq(LastlegOrder::getOutboundOrderNo, outboundNo))) {
String from = order.getCurrentStatus(); order.setCurrentStatus("RECEIVED"); order.setSubOrderStatus(null); order.setOutboundOrderNo(null); order.setDeliveryOrderNo(null); order.setUpdatedAt(now); tailOrders.updateById(order);
LastlegOrderStatusHistory history = new LastlegOrderStatusHistory(); history.setCustomerId(customerId); history.setOrderId(order.getId()); history.setFromStatus(from); history.setToStatus("RECEIVED"); history.setEventId("CANCEL_OUTBOUND:" + outboundNo); history.setRemark(request.reason().trim()); history.setCreatedAt(now); histories.insert(history);
var transferEvents = existingDeliveries.stream().map(delivery -> "TRANSFER_DELIVERY:" + delivery.getDeliveryNo()).toList();
for (LastlegOrder selected : tailOrders.selectList(new LambdaQueryWrapper<LastlegOrder>().eq(LastlegOrder::getCustomerId, customerId)
.eq(LastlegOrder::getOutboundOrderNo, outboundNo).orderByAsc(LastlegOrder::getId))) {
var order = tailOrders.lockById(customerId, selected.getId());
if (order == null || !outboundNo.equals(order.getOutboundOrderNo())) continue;
var previous = histories.selectOne(new LambdaQueryWrapper<LastlegOrderStatusHistory>()
.eq(LastlegOrderStatusHistory::getCustomerId, customerId).eq(LastlegOrderStatusHistory::getOrderId, order.getId())
.in(LastlegOrderStatusHistory::getEventId, transferEvents)
.orderByAsc(LastlegOrderStatusHistory::getCreatedAt, LastlegOrderStatusHistory::getId).last("LIMIT 1"));
if (previous == null || !StringUtils.hasText(previous.getFromStatus())) throw conflict("缺少本次转派送前的订单状态记录,请先核对来源");
String from = order.getCurrentStatus();
if (tailOrders.update(null, new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<LastlegOrder>()
.eq(LastlegOrder::getId, order.getId()).eq(LastlegOrder::getCustomerId, customerId)
.eq(LastlegOrder::getOutboundOrderNo, outboundNo)
.set(LastlegOrder::getCurrentStatus, previous.getFromStatus())
.set(LastlegOrder::getSubOrderStatus, "OUTBOUND:CANCELLED;DELIVERY:CANCELLED")
.set(LastlegOrder::getOutboundOrderNo, null).set(LastlegOrder::getDeliveryOrderNo, null)
.set(LastlegOrder::getVersion, value(order.getVersion()) + 1).set(LastlegOrder::getUpdatedAt, now)) != 1)
throw conflict("订单关联已变化,请刷新后重试");
LastlegOrderStatusHistory history = new LastlegOrderStatusHistory(); history.setCustomerId(customerId); history.setOrderId(order.getId()); history.setFromStatus(from); history.setToStatus(previous.getFromStatus()); history.setEventId("CANCEL_OUTBOUND:" + outboundNo); history.setRemark(request.reason().trim()); history.setCreatedAt(now); histories.insert(history);
}
}
}
@@ -1225,7 +1362,22 @@ public class DeliveryTransferService {
List<DeliveryResponses.DeliverySku> skus = details.stream().map(detail -> sku(detail, ordersById.get(detail.getOrderId()))).toList();
return new DeliveryResponses.DeliveryDetail(deliveryRow(delivery), skus,
feeSources.listForBusiness(customerId, "DELIVERY_ORDER", delivery.getId()).stream().map(this::feeRow).toList(),
deliveryOperations.findByDelivery(customerId, delivery.getId()).stream().map(this::operationRow).toList());
deliveryOperations.findByDelivery(customerId, delivery.getId()).stream().map(this::operationRow).toList(),
feeCoverageEvidence(customerId, delivery.getOutboundNo(), items));
}
private com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels.Evidence feeCoverageEvidence(String customerId, String outboundNo, List<DispatchItem> items) {
var outbound = outboundNo == null ? null : outboundOrders.findByNo(customerId, outboundNo);
if (outbound == null || outbound.getFeeCoverageJson() == null) return null;
try {
var evidence = objectMapper.readValue(outbound.getFeeCoverageJson(), com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels.Evidence.class);
var ids = items.stream().map(DispatchItem::getId).collect(Collectors.toSet());
var cargo = evidence.cargo().stream().filter(row -> ids.contains(row.dispatchItemId())).toList();
var inboundIds = cargo.stream().filter(row -> "FIRSTLEG".equals(row.sourceRegion()))
.map(com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels.Cargo::sourceInboundId).collect(Collectors.toSet());
var references = evidence.references().stream().filter(row -> inboundIds.contains(row.source().sourceInboundId().toString())).toList();
return new com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels.Evidence(evidence.cargoHash(), cargo, references, evidence.operatorId(), evidence.confirmedAt());
} catch (JsonProcessingException exception) { throw new IllegalStateException("费用覆盖确认无法读取", exception); }
}
private void bindTailOrders(String customerId, List<DispatchItem> items, String outboundNo, String deliveryNo,
@@ -1286,9 +1438,9 @@ public class DeliveryTransferService {
allocateMetric(candidate.getSourceVolumeWeightKg(), candidate.getSourcePackageCount(), available, 3),
allocateMetric(candidate.getSourceVolumeCbm(), candidate.getSourcePackageCount(), available, 4));
}
private DeliveryResponses.DeliveryRow deliveryRow(DeliveryOrder d) { return new DeliveryResponses.DeliveryRow(d.getId(), d.getCustomerId(), d.getCustomerName(), d.getDeliveryNo(), d.getOutboundNo(), d.getDispatchNo(), d.getOverseasWarehouseId(), d.getOverseasWarehouseName(), d.getStatus(), d.getWaybillNo(), d.getDeliveryMethod(), d.getCarrierName(), d.getPickupMethod(), d.getLoadingType(), d.getVehicleType(), d.getVehicleSize(), d.getVehiclePlate(), d.getDriverName(), d.getDriverPhone(), d.getAppointmentAccount(), d.getSellerName(), value(d.getPalletCount()), value(d.getPackageCount()), d.getTotalWeightKg(), d.getTotalVolumeCbm(), d.getPlannedDeliveryAt(), d.getDispatchedAt(), d.getExpectedArrivalAt(), d.getSignedAt(), d.getRemark(), d.getCreatedAt(), value(d.getVersion()), DeliveryStatusPolicy.allowedActions(d.getStatus()), d.getBolNo(), com.baiyue.lastleg.delivery.model.DeliveryDocumentSnapshot.summary(d.getDocumentsJson()), d.getDestinationWarehouseId(), d.getDestinationWarehouseCode(), d.getDestinationWarehouseName(), d.getDestinationType(), d.getDeliveryAddress(), d.getContactName(), d.getContactPhone(), d.getPostalCode()); }
private DeliveryResponses.DeliveryRow deliveryRow(DeliveryOrder d) { return new DeliveryResponses.DeliveryRow(d.getId(), d.getCustomerId(), d.getCustomerName(), d.getDeliveryNo(), d.getOutboundNo(), d.getDispatchNo(), d.getOverseasWarehouseId(), d.getOverseasWarehouseName(), d.getStatus(), d.getWaybillNo(), d.getDeliveryMethod(), d.getCarrierName(), d.getPickupMethod(), d.getLoadingType(), d.getVehicleType(), d.getVehicleSize(), d.getVehiclePlate(), d.getDriverName(), d.getDriverPhone(), d.getAppointmentAccount(), d.getSellerName(), value(d.getPalletCount()), value(d.getPackageCount()), d.getTotalWeightKg(), d.getTotalVolumeCbm(), d.getPlannedDeliveryAt(), d.getDispatchedAt(), d.getExpectedArrivalAt(), d.getSignedAt(), d.getRemark(), d.getCreatedAt(), value(d.getVersion()), DeliveryStatusPolicy.allowedActions(d.getStatus()), d.getBolNo(), DeliveryDocumentSnapshot.summary(d.getDocumentsJson()), d.getDestinationWarehouseId(), d.getDestinationWarehouseCode(), d.getDestinationWarehouseName(), d.getDestinationType(), d.getDeliveryAddress(), d.getContactName(), d.getContactPhone(), d.getPostalCode()); }
private DeliveryResponses.DeliverySku sku(LastlegOrderDetail d, LastlegOrder order) { return new DeliveryResponses.DeliverySku(order == null ? null : order.getInboundCode(), order == null ? null : order.getCustomerName(), d.getDestinationWarehouseCode(), null, d.getShipmentNo(), d.getFbaTrackingNo(), d.getSkuCode(), firstText(d.getProductNameZh(), d.getProductNameEn()), value(d.getPackageCount()), d.getGrossWeightKg(), d.getVolumeCbm()); }
private DeliveryResponses.DeliveryFeeRow feeRow(OverseasFeeSource f) { return new DeliveryResponses.DeliveryFeeRow(f.getId(), f.getDirection(), f.getFeeItemCode(), f.getOriginalCurrency(), f.getOriginalAmount(), f.getReviewReason()); }
private DeliveryResponses.DeliveryFeeRow feeRow(OverseasFeeSource f) { return new DeliveryResponses.DeliveryFeeRow(f.getId(), f.getDirection(), f.getFeeItemCode(), f.getOriginalCurrency(), f.getOriginalAmount(), f.getReviewReason(), f.getReviewStatus(), f.getSourceStatus(), f.getVoidStatus()); }
private DeliveryResponses.DeliveryOperationRow operationRow(DeliveryOperation o) { return new DeliveryResponses.DeliveryOperationRow(o.getId(), o.getCreatedAt(), o.getOperationNode(), firstText(o.getOperatorName(), o.getOperatorId()), o.getResult()); }
private void recordOperation(String customerId, Long deliveryId, String operatorId, String node, String result, LocalDateTime now) { DeliveryOperation operation = new DeliveryOperation(); operation.setCustomerId(customerId); operation.setDeliveryOrderId(deliveryId); operation.setOperationNode(node); operation.setOperatorId(operatorId); operation.setOperatorName(operatorId); operation.setResult(result); operation.setCreatedAt(now); deliveryOperations.insert(operation); }
private LastlegOrder firstTailOrder(String customerId, List<DispatchItem> items) { return items.stream().map(DispatchItem::getOrderId).filter(Objects::nonNull).map(tailOrders::selectById).filter(Objects::nonNull).filter(order -> customerId.equals(order.getCustomerId())).findFirst().orElse(null); }
@@ -1344,6 +1496,11 @@ public class DeliveryTransferService {
java.util.function.Function<T, BigDecimal> getter) {
return items.stream().map(getter).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
}
private static <T> BigDecimal sumKnownPhysicalWeight(List<T> items,
java.util.function.Function<T, BigDecimal> getter) {
if (items.isEmpty() || items.stream().map(getter).anyMatch(weight -> weight == null || weight.signum() <= 0)) return null;
return items.stream().map(getter).reduce(BigDecimal.ZERO, BigDecimal::add);
}
private static BigDecimal allocateMetric(BigDecimal sourceValue, Long sourcePackages,
long selectedPackages, int scale) {
if (sourceValue == null || sourceValue.signum() == 0 || sourcePackages == null
@@ -0,0 +1,183 @@
package com.baiyue.lastleg.dispatch.fleet;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baiyue.lastleg.delivery.entity.DeliveryOrder;
import com.baiyue.lastleg.delivery.mapper.DeliveryOrderMapper;
import com.baiyue.lastleg.delivery.mapper.DeliveryOperationMapper;
import com.baiyue.lastleg.delivery.mapper.OutboundOrderMapper;
import com.baiyue.lastleg.dispatch.entity.DispatchOrder;
import com.baiyue.lastleg.dispatch.mapper.DispatchOrderMapper;
import com.baiyue.lastleg.dispatch.mapper.DispatchItemMapper;
import com.baiyue.lastleg.dispatch.pda.mapper.DispatchPdaPickMapper;
import com.baiyue.lastleg.dispatch.pda.mapper.DispatchPdaTaskMapper;
import com.baiyue.lastleg.dispatch.pda.service.DispatchPdaWorkflowService;
import com.baiyue.lastleg.dispatch.pda.dto.DispatchPdaRequests;
import com.baiyue.lastleg.fleet.trip.FleetExecutionModels;
import com.baiyue.lastleg.fleet.trip.FleetCompletionModels;
import com.baiyue.lastleg.fleet.trip.FleetDispatchGateway;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
@Component
@Transactional(propagation = Propagation.MANDATORY)
public class DispatchFleetAdapter implements FleetDispatchGateway {
private final DispatchOrderMapper orders;
private final DispatchPdaTaskMapper tasks;
private final OutboundOrderMapper outbounds;
private final DeliveryOrderMapper deliveries;
private final DeliveryOperationMapper deliveryOperations;
private final DispatchItemMapper items;
private final DispatchPdaPickMapper picks;
private final DispatchPdaWorkflowService workflow;
public DispatchFleetAdapter(DispatchOrderMapper orders, DispatchPdaTaskMapper tasks,
OutboundOrderMapper outbounds, DeliveryOrderMapper deliveries, DispatchItemMapper items,
DispatchPdaPickMapper picks, DispatchPdaWorkflowService workflow, DeliveryOperationMapper deliveryOperations) {
this.orders = orders; this.tasks = tasks; this.outbounds = outbounds; this.deliveries = deliveries;
this.items = items; this.picks = picks; this.workflow = workflow;
this.deliveryOperations = deliveryOperations;
}
@Override
public Snapshot lockForPlanning(String dispatchNo) {
return lockBeforeDeparture(dispatchNo, false);
}
@Override
public Snapshot lockForAssignment(String dispatchNo) {
return lockBeforeDeparture(dispatchNo, true);
}
private Snapshot lockBeforeDeparture(String dispatchNo, boolean allowPicking) {
var dispatch = orders.lockGlobalByDispatchNo(dispatchNo);
if (dispatch == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "排车单不存在");
var allowedStatuses = allowPicking ? java.util.Set.of("PENDING_DEPARTURE", "PICKING", "READY_TO_DEPART") : java.util.Set.of("PENDING_DEPARTURE");
if (dispatch.getStatus() == null || !allowedStatuses.contains(dispatch.getStatus())
|| (!allowPicking && Objects.requireNonNullElse(dispatch.getPickedPackageCount(), 0) > 0)
|| Objects.requireNonNullElse(dispatch.getShippedPackageCount(), 0) > 0)
throw conflict("排车单 " + dispatchNo + " 已开始执行,不能修改车次关联或改派");
// Keep the same dispatch -> outbound -> PDA task lock order as departure.
var outbound = outbounds.lockByDispatch(dispatch.getCustomerId(), dispatch.getId());
if (outbound != null && !"WAIT_OUTBOUND".equals(outbound.getStatus()))
throw conflict("排车单 " + dispatchNo + " 的出库状态不允许修改关联");
var task = tasks.lockByDispatch(dispatch.getCustomerId(), dispatch.getId());
var allowedTaskStatuses = allowPicking ? java.util.Set.of("PDA_PENDING", "PICKING", "COMPLETED") : java.util.Set.of("PDA_PENDING");
if (task != null && (task.getStatus() == null || !allowedTaskStatuses.contains(task.getStatus())))
throw conflict("排车单 " + dispatchNo + " 已开始拣货,不能修改车次关联或改派");
if (task != null && !Objects.equals(task.getWarehouseId(), dispatch.getOverseasWarehouseId()))
throw conflict("拣货任务所属仓不一致");
if (task == null && Objects.requireNonNullElse(dispatch.getPickedPackageCount(), 0) > 0)
throw conflict("排车单缺少已拣货的作业依据");
if (dispatch.getPackageCount() == null || dispatch.getPackageCount() <= 0)
throw conflict("排车单 " + dispatchNo + " 没有待发运货物");
return new Snapshot(dispatch.getId(), dispatch.getDispatchNo(), dispatch.getCustomerId(), dispatch.getOverseasWarehouseId(), dispatch.getPackageCount());
}
@Override
public void assign(Snapshot dispatch, Assignment assignment) {
var now = LocalDateTime.now();
// Explicit SET is needed when unbinding: MyBatis entity updates omit null fields.
if (orders.update(null, new LambdaUpdateWrapper<DispatchOrder>().eq(DispatchOrder::getId, dispatch.dispatchId())
.eq(DispatchOrder::getCustomerId, dispatch.customerId()).in(DispatchOrder::getStatus, "PENDING_DEPARTURE", "PICKING", "READY_TO_DEPART")
.set(DispatchOrder::getVehiclePlate, assignment.vehiclePlate()).set(DispatchOrder::getDriverName, assignment.driverName())
.set(DispatchOrder::getDriverPhone, assignment.driverPhone()).set(DispatchOrder::getUpdatedAt, now)) != 1)
throw conflict("排车单已变化,请刷新后重试");
var outbound = outbounds.lockByDispatch(dispatch.customerId(), dispatch.dispatchId());
if (outbound == null) return;
for (var delivery : deliveries.lockByOutbound(dispatch.customerId(), outbound.getId())) {
if (!"WAIT_DELIVERY".equals(delivery.getStatus()) || delivery.getDispatchedAt() != null || delivery.getSignedAt() != null)
throw conflict("派送单 " + delivery.getDeliveryNo() + " 已执行,不能覆盖车辆司机");
if (deliveries.update(null, new LambdaUpdateWrapper<DeliveryOrder>().eq(DeliveryOrder::getId, delivery.getId())
.eq(DeliveryOrder::getCustomerId, dispatch.customerId()).eq(DeliveryOrder::getVersion, delivery.getVersion())
.set(DeliveryOrder::getVehiclePlate, assignment.vehiclePlate()).set(DeliveryOrder::getDriverName, assignment.driverName())
.set(DeliveryOrder::getDriverPhone, assignment.driverPhone()).set(DeliveryOrder::getVersion, delivery.getVersion() + 1)
.set(DeliveryOrder::getUpdatedAt, now)) != 1) throw conflict("派送单已变化,请刷新后重试");
}
}
@Override
public FleetExecutionModels.Manifest manifest(String dispatchNo, boolean lock) {
var dispatch = lock ? orders.lockGlobalByDispatchNo(dispatchNo) : orders.findGlobalByDispatchNo(dispatchNo);
if (dispatch == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "排车单不存在");
var outbound = lock ? outbounds.lockByDispatch(dispatch.getCustomerId(), dispatch.getId()) : outbounds.findByDispatch(dispatch.getCustomerId(), dispatch.getId());
var task = lock ? tasks.lockByDispatch(dispatch.getCustomerId(), dispatch.getId()) : tasks.findByDispatch(dispatch.getCustomerId(), dispatch.getId());
var selected = items.findByDispatchOrder(dispatch.getCustomerId(), dispatch.getId());
Map<Long, Long> picked = new HashMap<>();
if (task != null) for (var pick : picks.listTask(dispatch.getCustomerId(), task.getId())) picked.merge(pick.getDispatchItemId(), pick.getPackages(), Math::addExact);
var cargo = selected.stream().map(item -> new FleetExecutionModels.Cargo(dispatchNo, dispatch.getCustomerId(), item.getId().toString(),
item.getWarehousePalletId() == null ? null : item.getWarehousePalletId().toString(), item.getPalletNo(), Objects.requireNonNullElse(item.getPackageCount(), 0),
destination(item.getDestinationType(), item.getDestinationWarehouseCode(), item.getFbaWarehouseCode(), item.getDeliveryAddress(), item.getPostalCode()),
"PRIVATE".equals(item.getDestinationType()) ? item.getDeliveryAddress() : first(item.getDestinationWarehouseCode(), item.getFbaWarehouseCode()))).toList();
String reason = null;
if (!"READY_TO_DEPART".equals(dispatch.getStatus()) || task == null || !"COMPLETED".equals(task.getStatus())) reason = "请完成拣货并核平全部箱数";
else if (!Objects.equals(dispatch.getOverseasWarehouseId(), task.getWarehouseId())) reason = "拣货任务所属仓不一致";
else if (selected.isEmpty() || selected.stream().anyMatch(item -> item.getPackageCount() == null || item.getPackageCount() <= 0
|| picked.getOrDefault(item.getId(), 0L).longValue() != item.getPackageCount().longValue())) reason = "每条货物须与实际拣货箱数核平";
else if (!picked.keySet().equals(selected.stream().map(com.baiyue.lastleg.dispatch.entity.DispatchItem::getId).collect(java.util.stream.Collectors.toSet()))) reason = "拣货记录包含不属于当前发运的货物";
else if (outbound == null || !"WAIT_OUTBOUND".equals(outbound.getStatus())) reason = "请先转派送并生成待出库单";
else if (cargo.stream().anyMatch(item -> item.warehousePalletId() == null || item.palletNo() == null || item.destinationKey() == null)) reason = "实物托盘或目的地未确认";
return new FleetExecutionModels.Manifest(dispatchNo, dispatch.getOverseasWarehouseId(), dispatch.getVehiclePlate(), dispatch.getDriverName(), dispatch.getDriverPhone(), cargo, reason);
}
@Override
public FleetExecutionModels.DepartedDispatch depart(String warehouseId, String dispatchNo, String operator,
String idempotencyKey, String remark, Instant departedAt) {
var result = workflow.depart(warehouseId, dispatchNo, operator, new DispatchPdaRequests.Depart(idempotencyKey, remark),
LocalDateTime.ofInstant(departedAt, ZoneId.systemDefault()));
return new FleetExecutionModels.DepartedDispatch(result.dispatchNo(), result.shippedPackages());
}
private static String destination(String type, String code, String fba, String address, String postalCode) {
return FleetDispatchGateway.destinationKey(type,code,fba,address,postalCode);
}
@Override public java.util.List<SourceCargo> sourceCargo(String dispatchNo) {
var dispatch=orders.findGlobalByDispatchNo(dispatchNo);
if(dispatch==null)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"排车单不存在");
return items.findByDispatchOrder(dispatch.getCustomerId(),dispatch.getId()).stream().map(item->new SourceCargo(item.getInboundCode(),
item.getWarehousePalletId()==null?null:item.getWarehousePalletId().toString(),item.getPalletNo(),Objects.requireNonNullElse(item.getPackageCount(),0),
destination(item.getDestinationType(),item.getDestinationWarehouseCode(),item.getFbaWarehouseCode(),item.getDeliveryAddress(),item.getPostalCode()))).toList();
}
@Override
public FleetCompletionModels.DispatchCompletion completion(String dispatchNo, boolean lock) {
var dispatch = lock ? orders.lockGlobalByDispatchNo(dispatchNo) : orders.findGlobalByDispatchNo(dispatchNo);
if (dispatch == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "排车单不存在");
var outbound = lock ? outbounds.lockByDispatch(dispatch.getCustomerId(), dispatch.getId()) : outbounds.findByDispatch(dispatch.getCustomerId(), dispatch.getId());
var rows = outbound == null ? java.util.List.<DeliveryOrder>of() : lock
? deliveries.lockByOutbound(dispatch.getCustomerId(), outbound.getId()) : deliveries.findByOutbound(dispatch.getCustomerId(), outbound.getId());
var outcomes = rows.stream().map(row -> new FleetCompletionModels.Outcome(dispatchNo, row.getDeliveryNo(), dispatch.getCustomerId(),
"PRIVATE".equals(row.getDestinationType()) ? row.getDeliveryAddress() : first(row.getDestinationWarehouseCode(), row.getDestinationWarehouseName()),
originallySigned(row) ? "DELIVERED" : row.getStatus(), Objects.requireNonNullElse(row.getPackageCount(), 0),
originallySigned(row) ? instant(row.getSignedAt()) : "RETURNED".equals(row.getStatus())
? instant(deliveryOperations.returnedAt(dispatch.getCustomerId(), row.getId())) : null)).toList();
String reason = null;
if (!"DEPARTED".equals(dispatch.getStatus()) || outbound == null || !"OUTBOUNDED".equals(outbound.getStatus())) reason = "排车出库尚未完成";
else if (outcomes.isEmpty()) reason = "缺少对应派送单";
else if (outcomes.stream().mapToLong(FleetCompletionModels.Outcome::packages).sum() != Objects.requireNonNullElse(dispatch.getShippedPackageCount(), 0)
|| !Objects.equals(dispatch.getShippedPackageCount(), outbound.getPackageCount())) reason = "派送单数量未覆盖本次全部实发货物";
else if (outcomes.stream().anyMatch(row -> row.packages() <= 0 || !java.util.Set.of("DELIVERED", "RETURNED").contains(row.status()) || row.terminalAt() == null))
reason = "所有派送单须已签收,或完成真实退回入仓";
return new FleetCompletionModels.DispatchCompletion(dispatchNo, dispatch.getOverseasWarehouseId(), outcomes, reason);
}
// Existing delivery commands persist LocalDateTime.now(); convert in that server zone, never the browser zone.
private static Instant instant(LocalDateTime value) { return value == null ? null : value.atZone(ZoneId.systemDefault()).toInstant(); }
private static boolean originallySigned(DeliveryOrder order) {
return order.getSignedAt() != null && java.util.Set.of("DELIVERED", "RETURN_PENDING", "RETURNED").contains(order.getStatus());
}
private static String first(String a, String b) { return a != null && !a.isBlank() ? a : b == null || b.isBlank() ? null : b; }
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
}
@@ -9,6 +9,11 @@ import java.util.List;
@Mapper
public interface DispatchCandidateMapper {
// Billing volume weight is never a substitute for physical cargo mass.
String SOURCE_GROSS_WEIGHT =
"COALESCE((SELECT CASE WHEN COUNT(*)&gt;0 AND COUNT(*)=COUNT(d.gross_weight_kg) AND MIN(d.gross_weight_kg)&gt;0 " +
"THEN SUM(d.gross_weight_kg) END FROM ll_order_detail d WHERE d.customer_id=ip.customer_id AND d.order_id=l.order_id)," +
"(SELECT inbound.gross_weight_kg FROM ll_inbound_order inbound WHERE inbound.id=l.order_id AND inbound.customer_id=ip.customer_id LIMIT 1))";
@Select("<script>" +
"SELECT DISTINCT customer_id FROM ll_inbound_plan WHERE id IN " +
"<foreach collection='planIds' item='id' open='(' separator=',' close=')'>#{id}</foreach> " +
@@ -29,14 +34,11 @@ public interface DispatchCandidateMapper {
"MIN(l.order_id) AS orderId," +
"MIN(ip.customer_id) AS customerId,MIN(o.customer_name) AS customerName," +
"MIN(ip.plan_no) AS planNo,MIN(o.order_type) AS orderType,MIN(o.volume_weight_kg) AS volumeWeightKg," +
"COALESCE(NULLIF(SUM(CASE WHEN COALESCE(l.volume_cbm,0)&gt;0 THEN " +
"COALESCE((SELECT SUM(d.gross_weight_kg) FROM ll_order_detail d WHERE d.customer_id=ip.customer_id AND d.order_id=l.order_id)," +
"(SELECT inbound.gross_weight_kg FROM ll_inbound_order inbound WHERE inbound.id=l.order_id AND inbound.customer_id=ip.customer_id LIMIT 1),0) " +
"* COALESCE(a.allocated_volume_cbm,0) / l.volume_cbm ELSE " +
"COALESCE((SELECT SUM(d.gross_weight_kg) FROM ll_order_detail d WHERE d.customer_id=ip.customer_id AND d.order_id=l.order_id)," +
"(SELECT inbound.gross_weight_kg FROM ll_inbound_order inbound WHERE inbound.id=l.order_id AND inbound.customer_id=ip.customer_id LIMIT 1),0) " +
"/ NULLIF((SELECT COUNT(*) FROM ll_inbound_plan_pallet_allocation a2 WHERE a2.line_id=a.line_id),0) END),0)," +
"MIN(o.volume_weight_kg)) AS grossWeightKg," +
"CASE WHEN MIN(CASE WHEN " + SOURCE_GROSS_WEIGHT +
" &gt;0 AND (COALESCE(l.volume_cbm,0)&lt;=0 OR COALESCE(a.allocated_volume_cbm,0)&gt;0) THEN 1 ELSE 0 END)=1 THEN " +
"NULLIF(SUM(CASE WHEN COALESCE(l.volume_cbm,0)&gt;0 THEN " + SOURCE_GROSS_WEIGHT +
" * a.allocated_volume_cbm / l.volume_cbm ELSE " + SOURCE_GROSS_WEIGHT +
" / NULLIF((SELECT COUNT(*) FROM ll_inbound_plan_pallet_allocation a2 WHERE a2.line_id=a.line_id),0) END),0) ELSE NULL END AS grossWeightKg," +
"MIN(ip.container_no) AS containerNo," +
"(SELECT MAX(fa.appointment_at) FROM ll_inbound_fba_appointment_item fi " +
"JOIN ll_inbound_fba_appointment fa ON fa.id=fi.appointment_id WHERE fi.line_id IN " +
@@ -142,14 +144,11 @@ public interface DispatchCandidateMapper {
"MIN(l.order_id) AS orderId," +
"MIN(ip.customer_id) AS customerId,MIN(o.customer_name) AS customerName," +
"MIN(ip.plan_no) AS planNo,MIN(o.order_type) AS orderType,MIN(o.volume_weight_kg) AS volumeWeightKg," +
"COALESCE(NULLIF(SUM(CASE WHEN COALESCE(l.volume_cbm,0)&gt;0 THEN " +
"COALESCE((SELECT SUM(d.gross_weight_kg) FROM ll_order_detail d WHERE d.customer_id=ip.customer_id AND d.order_id=l.order_id)," +
"(SELECT inbound.gross_weight_kg FROM ll_inbound_order inbound WHERE inbound.id=l.order_id AND inbound.customer_id=ip.customer_id LIMIT 1),0) " +
"* COALESCE(a.allocated_volume_cbm,0) / l.volume_cbm ELSE " +
"COALESCE((SELECT SUM(d.gross_weight_kg) FROM ll_order_detail d WHERE d.customer_id=ip.customer_id AND d.order_id=l.order_id)," +
"(SELECT inbound.gross_weight_kg FROM ll_inbound_order inbound WHERE inbound.id=l.order_id AND inbound.customer_id=ip.customer_id LIMIT 1),0) " +
"/ NULLIF((SELECT COUNT(*) FROM ll_inbound_plan_pallet_allocation a2 WHERE a2.line_id=a.line_id),0) END),0)," +
"MIN(o.volume_weight_kg)) AS grossWeightKg," +
"CASE WHEN MIN(CASE WHEN " + SOURCE_GROSS_WEIGHT +
" &gt;0 AND (COALESCE(l.volume_cbm,0)&lt;=0 OR COALESCE(a.allocated_volume_cbm,0)&gt;0) THEN 1 ELSE 0 END)=1 THEN " +
"NULLIF(SUM(CASE WHEN COALESCE(l.volume_cbm,0)&gt;0 THEN " + SOURCE_GROSS_WEIGHT +
" * a.allocated_volume_cbm / l.volume_cbm ELSE " + SOURCE_GROSS_WEIGHT +
" / NULLIF((SELECT COUNT(*) FROM ll_inbound_plan_pallet_allocation a2 WHERE a2.line_id=a.line_id),0) END),0) ELSE NULL END AS grossWeightKg," +
"MIN(ip.container_no) AS containerNo," +
"(SELECT MAX(fa.appointment_at) FROM ll_inbound_fba_appointment_item fi " +
"JOIN ll_inbound_fba_appointment fa ON fa.id=fi.appointment_id WHERE fi.line_id IN " +
@@ -5,6 +5,8 @@ import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.dispatch.pda.dto.DispatchPdaRequests;
import com.baiyue.lastleg.dispatch.pda.dto.DispatchPdaResponses;
import com.baiyue.lastleg.dispatch.pda.service.DispatchPdaWorkflowService;
import com.baiyue.lastleg.fleet.trip.FleetTripExecutionService;
import com.baiyue.lastleg.fleet.trip.FleetExecutionModels;
import com.baiyue.lastleg.pda.security.PdaWarehouseIdentity;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
@@ -19,19 +21,24 @@ import java.util.List;
@PreAuthorize("hasAuthority('lastleg:pda:operate') and hasAuthority('ROLE_OVERSEAS_WAREHOUSE_PDA_OPERATOR')")
public class DispatchPdaController {
@Resource private DispatchPdaWorkflowService service;
@Resource private FleetTripExecutionService trips;
@GetMapping
public ApiResponse<List<DispatchPdaResponses.Task>> list(@AuthenticationPrincipal AuthenticatedUser user,
@RequestParam(required = false) String status) {
PdaWarehouseIdentity identity = PdaWarehouseIdentity.require(user);
return ApiResponse.success(service.list(String.valueOf(identity.overseasWarehouseId()), status));
String warehouse = String.valueOf(identity.overseasWarehouseId());
var tasks = service.list(warehouse, status);
var gates = trips.gates(warehouse, tasks.stream().map(DispatchPdaResponses.Task::dispatchNo).toList());
return ApiResponse.success(tasks.stream().map(task -> task.withGate(gates.get(task.dispatchNo()))).toList());
}
@GetMapping("/{dispatchNo}")
public ApiResponse<DispatchPdaResponses.Task> task(@AuthenticationPrincipal AuthenticatedUser user,
@PathVariable String dispatchNo) {
PdaWarehouseIdentity identity = PdaWarehouseIdentity.require(user);
return ApiResponse.success(service.task(String.valueOf(identity.overseasWarehouseId()), dispatchNo));
String warehouse = String.valueOf(identity.overseasWarehouseId());
return ApiResponse.success(service.task(warehouse, dispatchNo).withGate(trips.gate(warehouse, dispatchNo)));
}
@PostMapping("/{dispatchNo}/items/{itemId}/pick")
@@ -54,11 +61,11 @@ public class DispatchPdaController {
}
@PostMapping("/{dispatchNo}/depart")
public ApiResponse<DispatchPdaResponses.Departed> depart(@AuthenticationPrincipal AuthenticatedUser user,
public ApiResponse<FleetExecutionModels.Departed> depart(@AuthenticationPrincipal AuthenticatedUser user,
@PathVariable String dispatchNo,
@Valid @RequestBody DispatchPdaRequests.Depart request) {
@Valid @RequestBody FleetExecutionModels.Depart request) {
PdaWarehouseIdentity identity = PdaWarehouseIdentity.require(user);
return ApiResponse.success(service.depart(String.valueOf(identity.overseasWarehouseId()), dispatchNo,
return ApiResponse.success(trips.depart(String.valueOf(identity.overseasWarehouseId()), dispatchNo,
identity.operatorKey(), request));
}
}
@@ -1,11 +1,18 @@
package com.baiyue.lastleg.dispatch.pda.dto;
import java.util.List;
import com.baiyue.lastleg.fleet.trip.FleetExecutionModels;
public final class DispatchPdaResponses {
private DispatchPdaResponses() {}
public record Task(Long id, String taskNo, String dispatchNo, String vehiclePlate, String warehouseId, String status,
boolean canDepart, String departBlockReason, List<Item> items) {}
boolean canDepart, String departBlockReason, List<Item> items, String tripNo, Long tripRecordVersion, int tripDispatchCount, String driverWarning,
boolean canPick, String pickBlockReason) {
public Task withGate(FleetExecutionModels.Gate gate) {
return new Task(id, taskNo, dispatchNo, vehiclePlate, warehouseId, status, gate.canDepart(), gate.blockReason(), items,
gate.tripNo(), gate.recordVersion(), gate.dispatchCount(), gate.driverWarning(), gate.canPick(), gate.pickBlockReason());
}
}
public record Item(Long dispatchItemId, String palletNo, String destinationWarehouseCode,
String destinationWarehouseName, String fbaWarehouseCode, String warehouseRouteLabel,
int scheduledPackages,
@@ -1,5 +1,7 @@
package com.baiyue.lastleg.dispatch.pda.service;
import com.baiyue.lastleg.fleet.trip.FleetDispatchBindingGuard;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baiyue.lastleg.delivery.entity.OutboundOrder;
import com.baiyue.lastleg.delivery.mapper.OutboundOrderMapper;
@@ -36,6 +38,7 @@ import java.util.stream.Collectors;
@Service
public class DispatchPdaWorkflowService {
@Resource private FleetDispatchBindingGuard fleetBindings;
@Resource private DispatchOrderMapper orders;
@Resource private OutboundOrderMapper outboundOrders;
@Resource private OutboundPalletItemMapper outboundPalletItems;
@@ -100,6 +103,7 @@ public class DispatchPdaWorkflowService {
}
requirePdaStatus(order);
requireVehicle(order);
fleetBindings.requirePickingApproved(order.getId());
items.bindReceivedPallets(customerId, order.getId());
if (!("PDA_PENDING".equals(task.getStatus()) || "PICKING".equals(task.getStatus()))) {
throw conflict("Dispatch PDA task is not available for picking");
@@ -169,6 +173,7 @@ public class DispatchPdaWorkflowService {
if (replay != null) return read(replay, DispatchPdaResponses.PickingCompleted.class).withReplay();
requireVehicle(order);
DispatchPdaTask task = tasks.lockByDispatch(customerId, order.getId());
fleetBindings.requirePickingApproved(order.getId());
if (task != null && "COMPLETED".equals(task.getStatus())) {
List<DispatchItem> completedItems = items.findByDispatchOrder(customerId, order.getId());
long planned = completedItems.stream().map(DispatchItem::getPackageCount).filter(Objects::nonNull)
@@ -204,15 +209,16 @@ public class DispatchPdaWorkflowService {
}
/** Final warehouse exit: only fully PDA-picked dispatches can consume picked inventory. */
@Transactional
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY)
public DispatchPdaResponses.Departed depart(String warehouseId, String dispatchNo, String operatorId,
DispatchPdaRequests.Depart request) {
DispatchPdaRequests.Depart request, LocalDateTime departedAt) {
DispatchOrder found = requireWarehouseOrder(warehouseId, dispatchNo);
String customerId = found.getCustomerId();
DispatchOrder order = orders.lockById(customerId, found.getId());
if (order == null) throw notFound("Dispatch order not found");
DispatchPdaOperation replay = replay(customerId, "DEPART", request.idempotencyKey(), request);
if (replay != null) return read(replay, DispatchPdaResponses.Departed.class).withReplay();
fleetBindings.requireCoordinatedDeparture(order.getId());
requireVehicle(order);
OutboundOrder outbound = outboundOrders.lockByDispatch(customerId, order.getId());
if (outbound == null || !"WAIT_OUTBOUND".equals(outbound.getStatus())) {
@@ -232,7 +238,7 @@ public class DispatchPdaWorkflowService {
List<DispatchPdaPick> dispatchPicks = picks.listTask(customerId, task.getId());
if (dispatchPicks.isEmpty()) throw conflict("Dispatch has no PDA picks to ship");
long shipped = dispatchPicks.stream().mapToLong(p -> n(p.getPackages())).sum();
LocalDateTime now = LocalDateTime.now();
LocalDateTime now = Objects.requireNonNull(departedAt, "departedAt");
pickAttribution.depart(customerId, outbound.getOutboundNo(), order.getDispatchNo(), dispatchPicks, now);
if (outboundPalletItems != null) {
for (var outboundItem : outboundPalletItems.findByOutbound(customerId, outbound.getId())) {
@@ -292,7 +298,8 @@ public class DispatchPdaWorkflowService {
OutboundOrder outbound = outboundOrders.findByDispatch(customerId, order.getId());
String departBlockReason = departBlockReason(order, task, source, outbound);
return new DispatchPdaResponses.Task(task.getId(), task.getTaskNo(), order.getDispatchNo(), order.getVehiclePlate(),
task.getWarehouseId(), task.getStatus(), departBlockReason == null, departBlockReason, values);
task.getWarehouseId(), "DEPARTED".equals(order.getStatus()) ? "DEPARTED" : task.getStatus(),
departBlockReason == null, departBlockReason, values, null, null, 0, null, false, "请先关联车次并通过调度审核");
}
private String departBlockReason(DispatchOrder order, DispatchPdaTask task, List<DispatchItem> source,
@@ -26,6 +26,7 @@ import com.baiyue.lastleg.dispatch.pda.mapper.DispatchPdaTaskMapper;
import com.baiyue.lastleg.entity.LastlegOrder;
import com.baiyue.lastleg.mapper.LastlegOrderMapper;
import com.baiyue.lastleg.delivery.mapper.OutboundOrderMapper;
import com.baiyue.lastleg.fleet.trip.FleetDispatchBindingGuard;
import com.baiyue.lastleg.relabel.entity.RelabelApplication;
import com.baiyue.lastleg.relabel.mapper.RelabelApplicationMapper;
import com.baiyue.lastleg.relabel.service.RelabelApplicationService;
@@ -65,6 +66,7 @@ public class DispatchService {
@Resource private LastlegOrderNoGenerator orderNoGenerator;
@Resource private LastlegOrderMapper tailOrders;
@Resource private OutboundOrderMapper outboundOrders;
@Resource private FleetDispatchBindingGuard fleetBindings;
@Resource private RelabelApplicationMapper relabelApplications;
@Resource private com.baiyue.lastleg.relabel.service.RelabelBindingGuard relabelBindingGuard;
@@ -410,7 +412,7 @@ public class DispatchService {
item.setContactName(candidate.contactName());
item.setContactPhone(candidate.contactPhone());
item.setPackageCount(Objects.requireNonNullElse(candidate.packageCount(), 0));
item.setGrossWeightKg(Objects.requireNonNullElse(candidate.grossWeightKg(), BigDecimal.ZERO));
item.setGrossWeightKg(candidate.grossWeightKg());
item.setVolumeWeightKg(Objects.requireNonNullElse(candidate.volumeWeightKg(), BigDecimal.ZERO));
item.setVolumeCbm(Objects.requireNonNullElse(candidate.volumeCbm(), BigDecimal.ZERO));
item.setSourceStage(candidate.sourceStage());
@@ -459,7 +461,7 @@ public class DispatchService {
DispatchOrder dispatch = new DispatchOrder(); dispatch.setId(IdWorker.getId()); dispatch.setCustomerId(customerId);
dispatch.setDispatchNo(orderNoGenerator.next("DISPATCH", warehouse, dispatch.getId())); dispatch.setOverseasWarehouseId(warehouse); dispatch.setOverseasWarehouseName(selected.get(0).overseasWarehouseName());
dispatch.setRoute(candidateRoute(selected)); dispatch.setFbaAppointmentNo(trimToNull(request.fbaAppointmentNo())); dispatch.setFbaAppointmentStatus(defaultStatus(request.fbaAppointmentStatus())); dispatch.setVehicleAppointmentStatus(defaultStatus(request.vehicleAppointmentStatus())); dispatch.setStatus(PENDING_DEPARTURE); dispatch.setItemCount(selected.size()); dispatch.setPalletCount(selected.size()); dispatch.setPackageCount(selected.stream().map(DispatchPalletCandidate::packageCount).filter(Objects::nonNull).mapToInt(Integer::intValue).sum()); dispatch.setPickedPackageCount(0); dispatch.setShippedPackageCount(0); dispatch.setCreatedBy(trimToNull(operatorId)); dispatch.setCreatedAt(now); dispatch.setUpdatedAt(now); orders.insert(dispatch);
for (DispatchPalletCandidate candidate : selected) { DispatchItem item = new DispatchItem(); item.setId(IdWorker.getId()); item.setDispatchOrderId(dispatch.getId()); item.setCustomerId(customerId); item.setWarehousePalletId(candidate.warehousePalletId()); item.setOrderId(candidate.orderId()); item.setOverseasWarehouseId(candidate.overseasWarehouseId()); item.setOverseasWarehouseName(candidate.overseasWarehouseName()); item.setOrderNo(candidate.orderNo()); item.setOrderRefs(candidate.orderRefs()); item.setInboundCode(candidate.inboundCode()); item.setPalletNo(candidate.palletNo()); item.setDestinationWarehouseCode(candidate.destinationWarehouseCode()); item.setDestinationWarehouseName(candidate.destinationWarehouseName()); item.setFbaWarehouseCode(candidate.fbaWarehouseCode()); item.setPackageCount(Objects.requireNonNullElse(candidate.packageCount(), 0)); item.setGrossWeightKg(Objects.requireNonNullElse(candidate.grossWeightKg(), BigDecimal.ZERO)); item.setVolumeWeightKg(Objects.requireNonNullElse(candidate.volumeWeightKg(), BigDecimal.ZERO)); item.setVolumeCbm(Objects.requireNonNullElse(candidate.volumeCbm(), BigDecimal.ZERO)); item.setSourceStage("RELABEL"); item.setCartonMarks(candidate.relabelCartonMarks()); item.setSourceBusinessType("RELABEL_ORDER"); item.setSourceBusinessNo(request.relabelNo()); item.setCreatedAt(now); items.insert(item); }
for (DispatchPalletCandidate candidate : selected) { DispatchItem item = new DispatchItem(); item.setId(IdWorker.getId()); item.setDispatchOrderId(dispatch.getId()); item.setCustomerId(customerId); item.setWarehousePalletId(candidate.warehousePalletId()); item.setOrderId(candidate.orderId()); item.setOverseasWarehouseId(candidate.overseasWarehouseId()); item.setOverseasWarehouseName(candidate.overseasWarehouseName()); item.setOrderNo(candidate.orderNo()); item.setOrderRefs(candidate.orderRefs()); item.setInboundCode(candidate.inboundCode()); item.setPalletNo(candidate.palletNo()); item.setDestinationWarehouseCode(candidate.destinationWarehouseCode()); item.setDestinationWarehouseName(candidate.destinationWarehouseName()); item.setFbaWarehouseCode(candidate.fbaWarehouseCode()); item.setPackageCount(Objects.requireNonNullElse(candidate.packageCount(), 0)); item.setGrossWeightKg(candidate.grossWeightKg()); item.setVolumeWeightKg(Objects.requireNonNullElse(candidate.volumeWeightKg(), BigDecimal.ZERO)); item.setVolumeCbm(Objects.requireNonNullElse(candidate.volumeCbm(), BigDecimal.ZERO)); item.setSourceStage("RELABEL"); item.setCartonMarks(candidate.relabelCartonMarks()); item.setSourceBusinessType("RELABEL_ORDER"); item.setSourceBusinessNo(request.relabelNo()); item.setCreatedAt(now); items.insert(item); }
DispatchPdaTask task = new DispatchPdaTask(); task.setId(IdWorker.getId()); task.setCustomerId(customerId); task.setDispatchOrderId(dispatch.getId()); task.setTaskNo("DPDA" + task.getId()); task.setStatus("PDA_PENDING"); task.setWarehouseId(warehouse); task.setPushedAt(now); task.setCreatedAt(now); task.setUpdatedAt(now); pdaTasks.insert(task);
if (candidates.markRelabelPreDispatched(customerId, request.relabelNo()) != 1) throw new ResponseStatusException(HttpStatus.CONFLICT, "换标订单已被其他排车占用");
return response(dispatch, items.findByDispatchOrder(customerId, dispatch.getId()));
@@ -528,6 +530,7 @@ public class DispatchService {
public DispatchResponse update(String dispatchNo, DispatchRequests.Update request) {
DispatchOrder dispatch = orders.lockGlobalByDispatchNo(trimToNull(dispatchNo));
if (dispatch == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Dispatch order not found");
fleetBindings.requireUnbound(dispatch.getId());
if (!PENDING_DEPARTURE.equals(dispatch.getStatus())) {
throw new ResponseStatusException(HttpStatus.CONFLICT,
"Only a pending dispatch can be edited");
@@ -585,6 +588,7 @@ public class DispatchService {
}
private void requirePalletEditingAllowed(DispatchOrder dispatch) {
fleetBindings.requireUnbound(dispatch.getId());
if (!PENDING_DEPARTURE.equals(dispatch.getStatus())
|| Objects.requireNonNullElse(dispatch.getPickedPackageCount(), 0) > 0) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Only an unpicked pending dispatch can edit pallets");
@@ -598,6 +602,7 @@ public class DispatchService {
public void cancel(String dispatchNo) {
DispatchOrder dispatch = orders.lockGlobalByDispatchNo(trimToNull(dispatchNo));
if (dispatch == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Dispatch order not found");
fleetBindings.requireUnbound(dispatch.getId());
if (CANCELLED.equals(dispatch.getStatus())) return;
if (!(PENDING_DEPARTURE.equals(dispatch.getStatus()))) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Only a pending dispatch can be cancelled");
@@ -58,6 +58,7 @@ public class OverseasFeeSource {
private String reviewStatus;
private String publicationStatus;
private String sourceStatus;
@TableField(exist = false) private String voidStatus;
private String reviewReason;
private String reviewerId;
private LocalDateTime reviewedAt;
@@ -15,6 +15,9 @@ import java.util.List;
@RequiredArgsConstructor
public class OverseasFeeOutboxRepository {
private final LastlegEventOutboxMapper mapper;
private final com.baiyue.lastleg.financefee.state.OverseasFeeCancellation cancellation;
public boolean prerequisitePublished(LastlegEventOutbox row) { return cancellation.prerequisitePublished(row); }
public List<LastlegEventOutbox> pending(int limit, LocalDateTime now, LocalDateTime stale) {
return mapper.selectList(new LambdaQueryWrapper<LastlegEventOutbox>()
@@ -22,6 +25,12 @@ public class OverseasFeeOutboxRepository {
.and(status -> status.eq(LastlegEventOutbox::getStatus, "PENDING")
.and(retry -> retry.isNull(LastlegEventOutbox::getNextRetryAt).or().le(LastlegEventOutbox::getNextRetryAt, now))
.or(processing -> processing.eq(LastlegEventOutbox::getStatus, "PROCESSING").le(LastlegEventOutbox::getLockedAt, stale)))
.and(eligible -> eligible.eq(LastlegEventOutbox::getStatus, "PROCESSING")
.or().isNull(LastlegEventOutbox::getEventKey).or().notLikeLeft(LastlegEventOutbox::getEventKey, ":VOIDED")
.or().apply("EXISTS (SELECT 1 FROM ll_event_outbox prerequisite WHERE prerequisite.event_key IN ("
+ "CONCAT(SUBSTRING(ll_event_outbox.event_key,1,LENGTH(ll_event_outbox.event_key)-6),'PUBLISHED'),"
+ "CONCAT(SUBSTRING(ll_event_outbox.event_key,1,LENGTH(ll_event_outbox.event_key)-6),'ADJUSTED')) "
+ "AND prerequisite.status='PUBLISHED')"))
.orderByAsc(LastlegEventOutbox::getCreatedAt).last("LIMIT " + limit));
}
public boolean claim(long id, String worker, LocalDateTime now) {
@@ -47,9 +56,12 @@ public class OverseasFeeOutboxRepository {
return mapper.selectOne(new LambdaQueryWrapper<LastlegEventOutbox>().eq(LastlegEventOutbox::getId, id)
.eq(LastlegEventOutbox::getStatus, "PROCESSING").eq(LastlegEventOutbox::getLockedBy, worker));
}
@org.springframework.transaction.annotation.Transactional
public int published(long id, String worker, LocalDateTime now) {
return mapper.update(null, claimed(id, worker, "PUBLISHED").set(LastlegEventOutbox::getPublishedAt, now)
int changed = mapper.update(null, claimed(id, worker, "PUBLISHED").set(LastlegEventOutbox::getPublishedAt, now)
.set(LastlegEventOutbox::getNextRetryAt, null).set(LastlegEventOutbox::getLastError, null));
if (changed == 1) cancellation.acknowledge(mapper.selectById(id));
return changed;
}
public int dead(long id, String worker, int failures, String error) {
return mapper.update(null, claimed(id, worker, "DEAD")
@@ -54,6 +54,7 @@ public class OverseasFeeOutboxRelay implements EventDeliveryProducer {
failures, next, "投递租约超时,消费结果未知"));
continue; // Recovery always waits for the new backoff window; never sends in this pass.
}
if (!repository.prerequisitePublished(candidate)) continue;
String worker = UUID.randomUUID().toString();
String type = Stream.FEE.type(candidate.getEventType());
if (!journal.begin(worker, Stream.FEE.service, type, String.valueOf(candidate.getId()),
@@ -11,6 +11,7 @@ import com.baiyue.lastleg.financefee.entity.OverseasFeeCommand;
import com.baiyue.lastleg.financefee.entity.OverseasFeeSource;
import com.baiyue.lastleg.financefee.mapper.OverseasFeeCommandMapper;
import com.baiyue.lastleg.financefee.mapper.OverseasFeeSourceMapper;
import com.baiyue.lastleg.financefee.state.OverseasFeeCancellation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
@@ -41,31 +42,43 @@ public class OverseasFeeSourceService {
private final OverseasFeeOutboxService outbox;
private final OverseasFeeCurrencyConverter currencyConverter;
private final ObjectMapper objectMapper;
private final OverseasFeeCancellation cancellation;
public List<OverseasFeeSource> list(String customerId, String businessType, String businessNo,
Long containerBookingId) {
return mapper.selectList(new LambdaQueryWrapper<OverseasFeeSource>()
return cancellation.describe(mapper.selectList(new LambdaQueryWrapper<OverseasFeeSource>()
.eq(text(customerId) != null, OverseasFeeSource::getCustomerId, text(customerId))
.eq(text(businessType) != null, OverseasFeeSource::getBusinessType, text(businessType))
.like(text(businessNo) != null, OverseasFeeSource::getBusinessNo, text(businessNo))
.eq(containerBookingId != null, OverseasFeeSource::getContainerBookingId, containerBookingId)
.inSql(OverseasFeeSource::getId, "SELECT MAX(v.id) FROM ll_finance_fee_source v GROUP BY v.source_fee_id")
.orderByDesc(OverseasFeeSource::getCreatedAt).orderByDesc(OverseasFeeSource::getId));
.orderByDesc(OverseasFeeSource::getCreatedAt).orderByDesc(OverseasFeeSource::getId)));
}
public List<OverseasFeeSource> listForBusiness(String customerId, String businessType, long businessId) {
return mapper.selectList(new LambdaQueryWrapper<OverseasFeeSource>()
return cancellation.describe(mapper.selectList(new LambdaQueryWrapper<OverseasFeeSource>()
.eq(OverseasFeeSource::getCustomerId, customerId)
.eq(OverseasFeeSource::getBusinessType, businessType)
.eq(OverseasFeeSource::getBusinessId, businessId)
.inSql(OverseasFeeSource::getId, "SELECT MAX(v.id) FROM ll_finance_fee_source v GROUP BY v.source_fee_id")
.orderByAsc(OverseasFeeSource::getCreatedAt).orderByAsc(OverseasFeeSource::getId));
.orderByAsc(OverseasFeeSource::getCreatedAt).orderByAsc(OverseasFeeSource::getId)));
}
public List<ContainerCustomerOption> listContainerCustomers(long containerBookingId) {
return businessGuard.listContainerCustomers(containerBookingId);
}
public void requireNoActiveDeliveryReceivables(String customerId, List<String> inboundCodes) {
if (inboundCodes.isEmpty()) return;
long existing = mapper.selectCount(new LambdaQueryWrapper<OverseasFeeSource>()
.eq(OverseasFeeSource::getCustomerId, customerId).eq(OverseasFeeSource::getBusinessType, "DELIVERY_ORDER")
.eq(OverseasFeeSource::getDirection, "RECEIVABLE").eq(OverseasFeeSource::getFeeItemCode, "DELIVERY_FEE")
.in(OverseasFeeSource::getInboundCode, inboundCodes).ne(OverseasFeeSource::getSourceStatus, "VOIDED")
.and(state -> state.eq(OverseasFeeSource::getReviewStatus, "APPROVED").or().gt(OverseasFeeSource::getSourceVersion, 1))
.inSql(OverseasFeeSource::getId, "SELECT MAX(v.id) FROM ll_finance_fee_source v GROUP BY v.source_fee_id"));
if (existing > 0) throw conflict("外接货已有派送应收尚未确认作废,请先完成原费用处理再重新转派送");
}
@Transactional
public OverseasFeeSource create(String operatorId, String key, SaveRequest request) {
OverseasFeeCommand replay = replay(operatorId, "CREATE", key, request);
@@ -125,11 +138,12 @@ public class OverseasFeeSourceService {
return value;
}
@Transactional
@Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED)
public OverseasFeeSource adjust(long sourceFeeId, String operatorId, AdjustRequest request) {
OverseasFeeCommand replay = replay(operatorId, "ADJUST", request.idempotencyKey(), request);
if (replay != null) return current(replay.getSourceFeeId());
OverseasFeeSource old = lock(sourceFeeId);
if (cancellation.requested(old)) throw conflict("该费用已申请作废,请先处理财务结果");
if (!"APPROVED".equals(old.getReviewStatus()) || !"ACTIVE".equals(old.getSourceStatus())
|| old.getSourceVersion() != request.expectedVersion()) throw conflict("只有当前已发布版本可以调整");
validate(request.fee()); businessGuard.requireOwned(request.fee());
@@ -157,10 +171,15 @@ public class OverseasFeeSourceService {
OverseasFeeSource value = lock(sourceFeeId);
if (!"APPROVED".equals(value.getReviewStatus()) || !"ACTIVE".equals(value.getSourceStatus())
|| value.getSourceVersion() != request.expectedVersion()) throw conflict("只有当前已发布版本可以作废");
value.setSourceStatus("VOIDED"); value.setReviewReason(request.reason().trim());
if (cancellation.requested(value)) return cancellation.describe(List.of(value)).get(0);
value.setReviewReason(request.reason().trim());
value.setUpdatedBy(operatorId); value.setUpdatedAt(now()); mapper.updateById(value);
outbox.publish(value, "VOIDED");
var pending = new OverseasFeeSource();
org.springframework.beans.BeanUtils.copyProperties(value, pending);
pending.setSourceStatus("VOIDED");
outbox.publish(pending, "VOIDED");
command(operatorId, "VOID", request.idempotencyKey(), request, sourceFeeId, value.getSourceVersion());
value.setVoidStatus("PENDING_FINANCE");
return value;
}
@@ -233,7 +252,7 @@ public class OverseasFeeSourceService {
private OverseasFeeSource current(long sourceFeeId) {
OverseasFeeSource value = mapper.selectOne(new LambdaQueryWrapper<OverseasFeeSource>()
.eq(OverseasFeeSource::getSourceFeeId, sourceFeeId).orderByDesc(OverseasFeeSource::getSourceVersion).last("LIMIT 1"));
if (value == null) throw notFound(); return value;
if (value == null) throw notFound(); return cancellation.describe(List.of(value)).get(0);
}
private OverseasFeeSource lock(long sourceFeeId) { OverseasFeeSource value = mapper.lockCurrent(sourceFeeId); if (value == null) throw notFound(); return value; }
private OverseasFeeCommand replay(String operator, String action, String key, Object request) {
@@ -0,0 +1,80 @@
package com.baiyue.lastleg.financefee.state;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baiyue.common.event.BusinessFeeSourceChangedV1;
import com.baiyue.common.event.EventEnvelope;
import com.baiyue.common.event.EventTypes;
import com.baiyue.lastleg.entity.LastlegEventOutbox;
import com.baiyue.lastleg.financefee.entity.OverseasFeeSource;
import com.baiyue.lastleg.financefee.mapper.OverseasFeeSourceMapper;
import com.baiyue.lastleg.mapper.LastlegEventOutboxMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;
/** A request is not a financial void. Only the matched durable consumer ACK confirms it. */
@Component
@RequiredArgsConstructor
public class OverseasFeeCancellation {
private final LastlegEventOutboxMapper events;
private final OverseasFeeSourceMapper fees;
private final ObjectMapper json;
public static String eventKey(OverseasFeeSource fee, String action) {
return EventTypes.BUSINESS_FEE_SOURCE_CHANGED + ":LASTLEG:" + fee.getSourceType() + ":"
+ fee.getSourceFeeId() + ":" + fee.getSourceVersion() + ":" + action;
}
public boolean requested(OverseasFeeSource fee) { return events.findByEventKey(eventKey(fee, "VOIDED")) != null; }
public List<OverseasFeeSource> describe(List<OverseasFeeSource> values) {
if (values.isEmpty()) return values;
var keys = values.stream().flatMap(value -> java.util.stream.Stream.of(eventKey(value, "VOIDED"),
eventKey(value, value.getSourceVersion() == 1 ? "PUBLISHED" : "ADJUSTED"))).toList();
var byKey = events.selectList(new LambdaQueryWrapper<LastlegEventOutbox>().in(LastlegEventOutbox::getEventKey, keys))
.stream().collect(Collectors.toMap(LastlegEventOutbox::getEventKey, row -> row));
for (var value : values) {
var request = byKey.get(eventKey(value, "VOIDED"));
var publish = byKey.get(eventKey(value, value.getSourceVersion() == 1 ? "PUBLISHED" : "ADJUSTED"));
value.setVoidStatus("VOIDED".equals(value.getSourceStatus()) ? "CONFIRMED" : request == null ? "NOT_REQUESTED"
: "DEAD".equals(request.getStatus()) || publish == null || "DEAD".equals(publish.getStatus())
? "FINANCE_ATTENTION" : "PENDING_FINANCE");
}
return values;
}
public boolean prerequisitePublished(LastlegEventOutbox request) {
if (request.getEventKey() == null || !request.getEventKey().endsWith(":VOIDED")) return true;
String prefix = request.getEventKey().substring(0, request.getEventKey().length() - "VOIDED".length());
return events.selectCount(new LambdaQueryWrapper<LastlegEventOutbox>()
.in(LastlegEventOutbox::getEventKey, List.of(prefix + "PUBLISHED", prefix + "ADJUSTED"))
.eq(LastlegEventOutbox::getStatus, "PUBLISHED")) > 0;
}
/** Invoked inside the same transaction as the lease-owner CAS and delivery journal completion. */
@Transactional(propagation = Propagation.MANDATORY)
public void acknowledge(LastlegEventOutbox event) {
if (event.getEventKey() == null || !event.getEventKey().endsWith(":VOIDED")) return;
try {
var envelope = json.readValue(event.getPayloadJson(), EventEnvelope.class).requireValid();
var payload = json.treeToValue(envelope.payload(), BusinessFeeSourceChangedV1.class);
if (!"VOIDED".equals(payload.action()) || !"LASTLEG".equals(payload.sourceSystem()))
throw new IllegalStateException("费用作废事件与来源不一致");
var source = fees.lockCurrent(Long.parseLong(payload.sourceFeeId()));
if (source == null || !Objects.equals(source.getSourceVersion(), payload.sourceVersion())
|| !Objects.equals(source.getCustomerId(), payload.customerId())
|| !Objects.equals(source.getSourceType(), payload.sourceType())
|| !eventKey(source, "VOIDED").equals(event.getEventKey()) || !"ACTIVE".equals(source.getSourceStatus()))
throw new IllegalStateException("财务已确认的作废来源与当前业务版本不一致");
source.setSourceStatus("VOIDED"); source.setUpdatedAt(LocalDateTime.now(ZoneOffset.UTC));
if (fees.updateById(source) != 1) throw new IllegalStateException("费用作废确认未能落账");
} catch (com.fasterxml.jackson.core.JsonProcessingException error) {
throw new IllegalStateException("费用作废事件无法解析", error);
}
}
}
@@ -0,0 +1,18 @@
package com.baiyue.lastleg.fleet.customer;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.core.api.PageResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(name = "iam-service", contextId = "fleetCustomerClient", url = "${baiyue.clients.iam.url:}")
public interface FleetCustomerClient {
@GetMapping("/internal/iam/finance-customers")
ApiResponse<PageResult<Customer>> customers(@RequestHeader("X-Internal-Service-Token") String token,
@RequestParam("page") long page, @RequestParam("size") long size, @RequestParam("keyword") String keyword,
@RequestParam("status") String status, @RequestParam("customerId") Long customerId);
@GetMapping("/internal/iam/tenants/{customerId}/order-eligibility")
ApiResponse<Eligibility> eligibility(@RequestHeader("X-Internal-Service-Token") String token, @PathVariable("customerId") long customerId);
record Customer(Long id, String tenantCode, String tenantName, String status, String contactName, String contactPhone) { }
record Eligibility(boolean eligible, String tenantStatus, String reason) { }
}
@@ -0,0 +1,39 @@
package com.baiyue.lastleg.fleet.customer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@Component
public class FleetCustomerDirectory {
public record Customer(String id, String code, String name, String contactName, String contactPhone) { }
private final FleetCustomerClient client;
private final String token;
public FleetCustomerDirectory(FleetCustomerClient client, @Value("${baiyue.security.internal-service-token}") String token) {
this.client = client; this.token = token;
}
public List<Customer> options(String keyword) { return load(keyword, null); }
public Customer required(long id) {
var customer = load(null, id).stream().filter(row -> row.id().equals(Long.toString(id))).findFirst()
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "请选择有效客户"));
try {
var result = client.eligibility(token, id);
if (result == null || !result.successful() || result.data() == null) throw unavailable();
if (!result.data().eligible()) throw new ResponseStatusException(HttpStatus.CONFLICT, "客户尚不具备下单资格,请先完成客户资料审核");
} catch (ResponseStatusException error) { throw error; }
catch (RuntimeException error) { throw unavailable(); }
return customer;
}
private List<Customer> load(String keyword, Long id) {
try {
var result = client.customers(token, 1, 30, keyword == null || keyword.isBlank() ? null : keyword.trim(), "ACTIVE", id);
if (result == null || !result.successful() || result.data() == null) throw unavailable();
return result.data().records().stream().filter(row -> row.id() != null && row.id() > 0 && "ACTIVE".equals(row.status()))
.map(row -> new Customer(row.id().toString(), row.tenantCode(), row.tenantName(), row.contactName(), row.contactPhone())).toList();
} catch (ResponseStatusException error) { throw error; }
catch (RuntimeException error) { throw unavailable(); }
}
private static ResponseStatusException unavailable() { return new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "客户目录暂不可用,请稍后重试"); }
}
@@ -0,0 +1,52 @@
package com.baiyue.lastleg.fleet.domain;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
/** Re-evaluated by the server when planning, changing or departing a trip. */
public final class DriverQualificationPolicy {
private DriverQualificationPolicy() { }
public enum ReviewStatus { PENDING, APPROVED, REJECTED }
public enum Reason {
ELIGIBLE, INACTIVE, MISSING_LICENSE, MISSING_EXPIRY, PENDING_REVIEW, REJECTED,
EXPIRED, MISSING_TRIP_END, INVALID_TRIP_END, EXPIRES_DURING_TRIP
}
public record Driver(boolean active, ReviewStatus reviewStatus, boolean hasLicense,
LocalDate licenseExpiresOn, ZoneId licenseZone) {
public Driver {
Objects.requireNonNull(reviewStatus, "reviewStatus");
Objects.requireNonNull(licenseZone, "licenseZone");
}
}
public record Qualification(boolean canDispatch, boolean expiringSoon, Reason reason,
LocalDate licenseExpiresOn) { }
public static Qualification evaluate(Driver driver, Instant now, Instant expectedEnd) {
Objects.requireNonNull(driver, "driver");
Objects.requireNonNull(now, "now");
LocalDate today = now.atZone(driver.licenseZone()).toLocalDate();
LocalDate expiry = driver.licenseExpiresOn();
long days = expiry == null ? Long.MAX_VALUE : ChronoUnit.DAYS.between(today, expiry);
boolean expiring = days >= 0 && days <= 30;
Reason reason;
if (!driver.active()) reason = Reason.INACTIVE;
else if (!driver.hasLicense()) reason = Reason.MISSING_LICENSE;
else if (expiry == null) reason = Reason.MISSING_EXPIRY;
else if (driver.reviewStatus() == ReviewStatus.REJECTED) reason = Reason.REJECTED;
else if (driver.reviewStatus() != ReviewStatus.APPROVED) reason = Reason.PENDING_REVIEW;
else if (days < 0) reason = Reason.EXPIRED;
else if (expectedEnd == null) reason = Reason.MISSING_TRIP_END;
else if (!expectedEnd.isAfter(now)) reason = Reason.INVALID_TRIP_END;
// A date-only licence is valid through that calendar day in its recorded zone.
else if (!expectedEnd.isBefore(expiry.plusDays(1).atStartOfDay(driver.licenseZone()).toInstant())) {
reason = Reason.EXPIRES_DURING_TRIP;
} else reason = Reason.ELIGIBLE;
return new Qualification(reason == Reason.ELIGIBLE, expiring, reason, expiry);
}
}
@@ -0,0 +1,69 @@
package com.baiyue.lastleg.fleet.domain;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
/** Pure capacity calculation; the caller must lock the trip before confirming reservations. */
public final class TripCapacityPolicy {
private TripCapacityPolicy() { }
public record Load(int palletSpaces, BigDecimal weightKg, BigDecimal volumeCbm) {
public Load {
if (palletSpaces < 0 || weightKg == null || volumeCbm == null
|| weightKg.signum() < 0 || volumeCbm.signum() < 0) {
throw new IllegalArgumentException("托位、重量和体积须为非负数");
}
}
public Load plus(Load other) {
return new Load(Math.addExact(palletSpaces, other.palletSpaces),
weightKg.add(other.weightKg), volumeCbm.add(other.volumeCbm));
}
}
public record Booking(String bookingNo, int pickupIndex, int deliveryIndex, Load load) {
public Booking {
if (bookingNo == null || bookingNo.isBlank()) throw new IllegalArgumentException("缺少承运业务编号");
if (pickupIndex < 0 || deliveryIndex <= pickupIndex) throw new IllegalArgumentException("卸货站必须在提货站之后");
Objects.requireNonNull(load, "load");
if (load.palletSpaces() == 0 || load.weightKg().signum() == 0 || load.volumeCbm().signum() == 0) {
throw new IllegalArgumentException("承运货物须有有效托位、重量和体积");
}
}
}
public record Segment(int fromIndex, int toIndex, Load occupied, Load remaining) { }
public static List<Segment> calculate(int stopCount, Load capacity, List<Booking> bookings) {
Objects.requireNonNull(capacity, "capacity");
Objects.requireNonNull(bookings, "bookings");
if (stopCount < 2 || stopCount > 200) throw new IllegalArgumentException("车次须有2至200个站点");
if (capacity.palletSpaces() <= 0 || capacity.weightKg().signum() <= 0 || capacity.volumeCbm().signum() <= 0) {
throw new IllegalArgumentException("车辆容量必须大于零");
}
var numbers = new HashSet<String>();
for (Booking booking : bookings) {
Objects.requireNonNull(booking, "booking");
if (!numbers.add(booking.bookingNo())) throw new IllegalArgumentException("承运明细重复分配");
if (booking.deliveryIndex() >= stopCount) throw new IllegalArgumentException("承运站点不属于当前路线");
}
List<Segment> segments = new ArrayList<>();
for (int index = 0; index < stopCount - 1; index++) {
Load occupied = new Load(0, BigDecimal.ZERO, BigDecimal.ZERO);
for (Booking booking : bookings) {
if (booking.pickupIndex() <= index && index < booking.deliveryIndex()) occupied = occupied.plus(booking.load());
}
if (occupied.palletSpaces() > capacity.palletSpaces()
|| occupied.weightKg().compareTo(capacity.weightKg()) > 0
|| occupied.volumeCbm().compareTo(capacity.volumeCbm()) > 0) {
throw new IllegalArgumentException("第" + (index + 1) + "段路线超过车辆托位、重量或容积限制");
}
Load remaining = new Load(capacity.palletSpaces() - occupied.palletSpaces(),
capacity.weightKg().subtract(occupied.weightKg()), capacity.volumeCbm().subtract(occupied.volumeCbm()));
segments.add(new Segment(index, index + 1, occupied, remaining));
}
return List.copyOf(segments);
}
}
@@ -0,0 +1,60 @@
package com.baiyue.lastleg.fleet.domain;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
/** Operating-cost allocation, not customer billing. One currency per calculation. */
public final class TripCostAllocationPolicy {
private TripCostAllocationPolicy() { }
public record Share(String bookingNo, long palletSpaces) {
public Share {
if (bookingNo == null || bookingNo.isBlank() || palletSpaces <= 0) {
throw new IllegalArgumentException("成本分摊须有承运编号及正数托位");
}
}
}
public record Allocation(String bookingNo, BigDecimal amount) { }
private record Fraction(String bookingNo, BigInteger cents, BigInteger remainder) { }
public static List<Allocation> allocate(BigDecimal total, String currency, List<Share> shares) {
Objects.requireNonNull(total, "total");
Objects.requireNonNull(shares, "shares");
if (!("USD".equals(currency) || "CNY".equals(currency))) throw new IllegalArgumentException("不支持的分摊币种");
if (total.signum() < 0) throw new IllegalArgumentException("直接成本不能为负数");
BigInteger cents;
try { cents = total.setScale(2, RoundingMode.UNNECESSARY).movePointRight(2).toBigIntegerExact(); }
catch (ArithmeticException e) { throw new IllegalArgumentException("金额最多两位小数", e); }
if (shares.isEmpty()) throw new IllegalArgumentException("没有可分摊的实运货物");
var numbers = new HashSet<String>();
BigInteger spaces = BigInteger.ZERO;
for (Share share : shares) {
if (!numbers.add(share.bookingNo())) throw new IllegalArgumentException("成本分摊承运编号重复");
spaces = spaces.add(BigInteger.valueOf(share.palletSpaces()));
}
List<Fraction> fractions = new ArrayList<>();
BigInteger assigned = BigInteger.ZERO;
for (Share share : shares) {
BigInteger[] result = cents.multiply(BigInteger.valueOf(share.palletSpaces())).divideAndRemainder(spaces);
fractions.add(new Fraction(share.bookingNo(), result[0], result[1]));
assigned = assigned.add(result[0]);
}
// Largest remainder with a stable business-number tie-break conserves every cent.
fractions.sort(Comparator.comparing(Fraction::remainder).reversed().thenComparing(Fraction::bookingNo));
int extraCents = cents.subtract(assigned).intValueExact();
List<Allocation> result = new ArrayList<>();
for (int i = 0; i < fractions.size(); i++) {
Fraction fraction = fractions.get(i);
BigInteger amount = fraction.cents().add(i < extraCents ? BigInteger.ONE : BigInteger.ZERO);
result.add(new Allocation(fraction.bookingNo(), new BigDecimal(amount, 2)));
}
result.sort(Comparator.comparing(Allocation::bookingNo));
return List.copyOf(result);
}
}
@@ -0,0 +1,44 @@
package com.baiyue.lastleg.fleet.driver;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@TableName("ll_fleet_driver")
public class DriverEntity {
@TableId(type = IdType.INPUT) private Long id;
private String driverNo;
private String name;
private String phone;
private String ownership;
private String region;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private Long warehouseId;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private String warehouseCode;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private String warehouseName;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private String vehicleModels;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private String languagesAndArea;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private LocalDate medicalExpiresOn;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private LocalDate trainingExpiresOn;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private LocalDate insuranceExpiresOn;
private Boolean active;
private String reviewStatus;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private String licenseNumber;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private String licenseType;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private LocalDate licenseIssuedOn;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private LocalDate licenseExpiresOn;
private String licenseZone;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private Long licenseFileId;
@TableField(updateStrategy = FieldStrategy.ALWAYS) private String remark;
private Long recordVersion;
private String createdBy;
private LocalDateTime createdAt;
private String updatedBy;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,9 @@
package com.baiyue.lastleg.fleet.driver;
import org.springframework.web.multipart.MultipartFile;
public interface DriverFileGateway {
DriverModels.File upload(long driverId, String operatorId, MultipartFile file);
DriverModels.File metadata(long driverId, long fileId);
byte[] download(long driverId, long fileId);
}
@@ -0,0 +1,22 @@
package com.baiyue.lastleg.fleet.driver;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("ll_fleet_driver_history")
public class DriverHistoryEntity {
@TableId(type = IdType.INPUT) private Long id;
private Long driverId;
private Long recordVersion;
private String action;
private String reason;
private Long licenseFileId;
private String snapshotJson;
private String operatorId;
private LocalDateTime occurredAt;
}
@@ -0,0 +1,7 @@
package com.baiyue.lastleg.fleet.driver;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DriverHistoryMapper extends BaseMapper<DriverHistoryEntity> { }
@@ -0,0 +1,24 @@
package com.baiyue.lastleg.fleet.driver;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import java.time.LocalDate;
import java.util.List;
@Mapper
public interface DriverMapper extends BaseMapper<DriverEntity> {
@Select("SELECT * FROM ll_fleet_driver WHERE id = #{id} FOR UPDATE")
DriverEntity lockById(@Param("id") long id);
@Select("SELECT DISTINCT license_zone FROM ll_fleet_driver")
List<String> licenseZones();
@Select("SELECT license_zone, license_expires_on, ownership, COUNT(*) AS driver_count FROM ll_fleet_driver ${ew.customSqlSegment} GROUP BY license_zone, license_expires_on, ownership")
List<DateGroup> dateGroups(@Param(Constants.WRAPPER) Wrapper<DriverEntity> query);
record DateGroup(String licenseZone, LocalDate licenseExpiresOn, String ownership, long driverCount) { }
}
@@ -0,0 +1,53 @@
package com.baiyue.lastleg.fleet.driver;
import com.baiyue.lastleg.fleet.domain.DriverQualificationPolicy;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
public final class DriverModels {
private DriverModels() { }
public record Query(@Min(1) Integer page, @Min(1) @Max(200) Integer size,
@Size(max = 128) String keyword, Boolean active, String reviewStatus,
String ownership, String region, String licenseState,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant expectedEnd) {
public Query { page = page == null ? 1 : page; size = size == null ? 20 : size; }
}
public record Draft(@NotBlank @Size(max = 128) String name,
@NotBlank @Size(max = 64) String phone,
@NotBlank @Pattern(regexp = "OWNED|DISPATCHED") String ownership,
@NotBlank @Pattern(regexp = "DOMESTIC|OVERSEAS") String region,
@Size(max = 128) String licenseNumber, @Size(max = 64) String licenseType,
LocalDate licenseIssuedOn, LocalDate licenseExpiresOn,
@NotBlank @Size(max = 64) String licenseZone,
@Size(max = 1000) String remark, @Valid Profile profile) { }
public record Profile(@Positive Long warehouseId, @Size(max = 128) String vehicleModels,
@Size(max = 256) String languagesAndArea, LocalDate medicalExpiresOn,
LocalDate trainingExpiresOn, LocalDate insuranceExpiresOn) { }
public record WarehouseOption(String id, String code, String name, String region) { }
public record Summary(long total, long owned, long dispatched, long expiringSoon, long expired) { }
public record DriverPage(java.util.List<Response> records, long page, long size, long total, long pages, Summary summary) { }
public record Update(@NotNull @Min(0) Long recordVersion, @NotNull @Valid Draft details) { }
public record Submit(@NotNull @Min(0) Long recordVersion) { }
public record ChangeStatus(@NotNull @Min(0) Long recordVersion, @NotNull Boolean active,
@NotBlank @Size(max = 1000) String reason) { }
public record Review(@NotNull @Min(0) Long recordVersion,
@NotBlank @Pattern(regexp = "APPROVED|REJECTED") String decision,
@Size(max = 1000) String reason) { }
public record Response(String id, String driverNo, Draft details, boolean active, String reviewStatus,
String licenseFileId, long recordVersion, String updatedBy, LocalDateTime updatedAt,
DriverQualificationPolicy.Qualification qualification, String licenseState,
String warehouseCode, String warehouseName) { }
public record History(long recordVersion, String action, String reason, String operatorId,
LocalDateTime occurredAt, Response snapshot) { }
public record File(String fileId, String fileName, String contentType, long sizeBytes) { }
public record Download(File metadata, byte[] content) { }
}
@@ -0,0 +1,346 @@
package com.baiyue.lastleg.fleet.driver;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baiyue.common.core.api.PageResult;
import com.baiyue.lastleg.fleet.domain.DriverQualificationPolicy;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.time.*;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@Service
public class DriverService {
private final DriverMapper drivers;
private final DriverHistoryMapper history;
private final DriverFileGateway files;
private final ObjectMapper json;
private final Clock clock;
private final FleetWarehouseDirectory warehouses;
@Autowired
public DriverService(DriverMapper drivers, DriverHistoryMapper history, DriverFileGateway files, ObjectMapper json, FleetWarehouseDirectory warehouses) {
this(drivers, history, files, json, Clock.systemUTC(), warehouses);
}
DriverService(DriverMapper drivers, DriverHistoryMapper history, DriverFileGateway files, ObjectMapper json, Clock clock, FleetWarehouseDirectory warehouses) {
this.drivers = drivers;
this.history = history;
this.files = files;
this.json = json;
this.clock = clock;
this.warehouses = warehouses;
}
@Transactional(readOnly = true, isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public DriverModels.DriverPage page(DriverModels.Query query) {
Instant now = clock.instant();
var filter = filter(query, now);
var summary = summary(drivers.dateGroups(filter), now);
filter.orderByDesc(DriverEntity::getUpdatedAt, DriverEntity::getId);
var page = drivers.selectPage(new Page<>(query.page(), query.size()), filter);
return new DriverModels.DriverPage(page.getRecords().stream().map(row -> response(row, now, query.expectedEnd())).toList(),
page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), summary);
}
private LambdaQueryWrapper<DriverEntity> filter(DriverModels.Query query, Instant now) {
String review = optionalChoice(query.reviewStatus(), Set.of("PENDING", "APPROVED", "REJECTED"), "审核状态");
String ownership = optionalChoice(query.ownership(), Set.of("OWNED", "DISPATCHED"), "司机归属");
String region = optionalChoice(query.region(), Set.of("DOMESTIC", "OVERSEAS"), "区域");
String keyword = trim(query.keyword());
var filter = new LambdaQueryWrapper<DriverEntity>()
.eq(query.active() != null, DriverEntity::getActive, query.active())
.eq(review != null, DriverEntity::getReviewStatus, review)
.eq(ownership != null, DriverEntity::getOwnership, ownership)
.eq(region != null, DriverEntity::getRegion, region);
if (keyword != null) filter.and(w -> w.like(DriverEntity::getName, keyword)
.or().like(DriverEntity::getPhone, keyword).or().like(DriverEntity::getDriverNo, keyword));
String state = optionalChoice(query.licenseState(), Set.of("MISSING", "VALID", "EXPIRING", "EXPIRED"), "驾驶证有效期");
if ("MISSING".equals(state)) filter.isNull(DriverEntity::getLicenseExpiresOn);
else if (state != null) {
List<String> zones = drivers.licenseZones();
if (zones.isEmpty()) filter.eq(DriverEntity::getId, -1L);
else filter.and(group -> {
for (String zone : zones) {
LocalDate today = now.atZone(ZoneId.of(zone)).toLocalDate();
group.or(part -> {
part.eq(DriverEntity::getLicenseZone, zone);
if ("EXPIRED".equals(state)) part.lt(DriverEntity::getLicenseExpiresOn, today);
else if ("EXPIRING".equals(state)) part.between(DriverEntity::getLicenseExpiresOn, today, today.plusDays(30));
else part.gt(DriverEntity::getLicenseExpiresOn, today.plusDays(30));
});
}
});
}
return filter;
}
private DriverModels.Summary summary(List<DriverMapper.DateGroup> groups, Instant now) {
long total = 0, owned = 0, dispatched = 0, expiring = 0, expired = 0;
for (var group : groups) {
long count = group.driverCount(); total += count;
if ("OWNED".equals(group.ownership())) owned += count; else dispatched += count;
String state = licenseState(group.licenseExpiresOn(), group.licenseZone(), now);
if ("EXPIRING".equals(state)) expiring += count;
if ("EXPIRED".equals(state)) expired += count;
}
return new DriverModels.Summary(total, owned, dispatched, expiring, expired);
}
public List<DriverModels.WarehouseOption> warehouseOptions(String region) { return warehouses.options(region); }
public DriverModels.Response detail(long id, Instant expectedEnd) {
return response(required(id), clock.instant(), expectedEnd);
}
@Transactional
public DriverModels.Response create(String operator, DriverModels.Draft draft) {
validate(draft);
var row = new DriverEntity();
row.setId(IdWorker.getId());
row.setDriverNo("DR-" + UUID.randomUUID().toString().replace("-", "").substring(0, 16).toUpperCase(java.util.Locale.ROOT));
assign(row, draft);
row.setActive(true);
row.setReviewStatus("PENDING");
row.setRecordVersion(0L);
row.setCreatedBy(operator);
row.setCreatedAt(now());
row.setUpdatedBy(operator);
row.setUpdatedAt(row.getCreatedAt());
if (drivers.insert(row) != 1) throw conflict();
record(row, "CREATE", null, operator);
return response(row, clock.instant(), null);
}
@Transactional
public DriverModels.Response update(long id, String operator, DriverModels.Update request) {
validate(request.details());
DriverEntity row = locked(id, request.recordVersion());
DriverModels.Draft next = request.details();
boolean credentialChanged = !Objects.equals(row.getName(), trim(next.name()))
|| !Objects.equals(row.getLicenseNumber(), trim(next.licenseNumber()))
|| !Objects.equals(row.getLicenseType(), trim(next.licenseType()))
|| !Objects.equals(row.getLicenseIssuedOn(), next.licenseIssuedOn())
|| !Objects.equals(row.getLicenseExpiresOn(), next.licenseExpiresOn())
|| !Objects.equals(row.getLicenseZone(), next.licenseZone());
assign(row, next);
if (credentialChanged) row.setReviewStatus("PENDING");
persist(row, request.recordVersion(), "UPDATE", credentialChanged ? "证照或身份信息变化,重新待审" : null, operator);
return response(row, clock.instant(), null);
}
@Transactional
public DriverModels.Response changeStatus(long id, String operator, DriverModels.ChangeStatus request) {
DriverEntity row = locked(id, request.recordVersion());
if (trim(request.reason()) == null) throw bad("启停原因不能为空");
row.setActive(request.active());
persist(row, request.recordVersion(), request.active() ? "ACTIVATE" : "DEACTIVATE", trim(request.reason()), operator);
return response(row, clock.instant(), null);
}
@Transactional
public DriverModels.Response submit(long id, String operator, DriverModels.Submit request) {
DriverEntity row = locked(id, request.recordVersion());
if (!"REJECTED".equals(row.getReviewStatus())) throw bad("仅已打回的司机档案需要重新提交");
requireLicense(row);
files.metadata(id, row.getLicenseFileId());
row.setReviewStatus("PENDING");
persist(row, request.recordVersion(), "RESUBMIT", "重新提交审核", operator);
return response(row, clock.instant(), null);
}
@Transactional
public DriverModels.Response review(long id, String operator, DriverModels.Review request) {
DriverEntity row = locked(id, request.recordVersion());
if (!"PENDING".equals(row.getReviewStatus())) throw bad("仅待审核司机可通过或打回;修改证照后重新提交审核");
String decision = optionalChoice(request.decision(), Set.of("APPROVED", "REJECTED"), "审核结果");
if (decision == null) throw bad("审核结果不能为空");
if ("REJECTED".equals(decision) && trim(request.reason()) == null) throw bad("打回原因不能为空");
if ("APPROVED".equals(decision)) {
requireLicense(row);
if (row.getLicenseIssuedOn() != null && row.getLicenseIssuedOn().isAfter(LocalDate.now(clock.withZone(ZoneId.of(row.getLicenseZone())))))
throw bad("驾驶证尚未生效");
if (row.getLicenseExpiresOn().isBefore(LocalDate.now(clock.withZone(ZoneId.of(row.getLicenseZone())))))
throw bad("驾驶证已过期,不能通过审核");
files.metadata(id, row.getLicenseFileId());
}
row.setReviewStatus(decision);
persist(row, request.recordVersion(), decision, trim(request.reason()), operator);
return response(row, clock.instant(), null);
}
@Transactional
public DriverModels.Response uploadLicense(long id, long version, String operator, MultipartFile file) {
DriverEntity row = locked(id, version);
DriverModels.File uploaded = files.upload(id, operator, file);
row.setLicenseFileId(Long.parseLong(uploaded.fileId()));
row.setReviewStatus("PENDING");
persist(row, version, "UPLOAD_LICENSE", "驾驶证附件更新,重新待审", operator);
return response(row, clock.instant(), null);
}
public PageResult<DriverModels.History> history(long id, int page, int size) {
required(id);
var result = history.selectPage(new Page<>(page, size), new LambdaQueryWrapper<DriverHistoryEntity>()
.eq(DriverHistoryEntity::getDriverId, id).orderByDesc(DriverHistoryEntity::getRecordVersion));
List<DriverModels.History> records = result.getRecords().stream().map(event -> {
try {
return new DriverModels.History(event.getRecordVersion(), event.getAction(), event.getReason(), event.getOperatorId(),
event.getOccurredAt(), json.readValue(event.getSnapshotJson(), DriverModels.Response.class));
} catch (JsonProcessingException e) { throw new IllegalStateException("司机历史快照读取失败", e); }
}).toList();
return new PageResult<>(records, result.getCurrent(), result.getSize(), result.getTotal(), result.getPages());
}
public DriverModels.Download download(long id, long fileId) {
DriverEntity row = required(id);
if (!Objects.equals(row.getLicenseFileId(), fileId) && history.selectCount(new LambdaQueryWrapper<DriverHistoryEntity>()
.eq(DriverHistoryEntity::getDriverId, id).eq(DriverHistoryEntity::getLicenseFileId, fileId)) == 0)
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "驾驶证附件未关联该司机");
var metadata = files.metadata(id, fileId);
return new DriverModels.Download(metadata, files.download(id, fileId));
}
/** Called by trip commands inside their transaction, so a concurrent credential edit cannot bypass the gate. */
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY)
public DriverModels.Response requireDispatchable(long id, Instant expectedEnd) {
DriverEntity row = drivers.lockById(id);
if (row == null) throw notFound();
var result = response(row, clock.instant(), expectedEnd);
if (!result.qualification().canDispatch()) throw bad(blockReason(result.qualification().reason()));
files.metadata(id, row.getLicenseFileId());
return result;
}
private DriverEntity required(long id) {
DriverEntity row = drivers.selectById(id);
if (row == null) throw notFound();
return row;
}
private DriverEntity locked(long id, long version) {
DriverEntity row = drivers.lockById(id);
if (row == null) throw notFound();
if (!Objects.equals(row.getRecordVersion(), version)) throw conflict();
return row;
}
private void persist(DriverEntity row, long version, String action, String reason, String operator) {
row.setRecordVersion(version + 1);
row.setUpdatedBy(operator);
row.setUpdatedAt(now());
if (drivers.update(row, new LambdaUpdateWrapper<DriverEntity>().eq(DriverEntity::getId, row.getId())
.eq(DriverEntity::getRecordVersion, version)) != 1) throw conflict();
record(row, action, reason, operator);
}
private void record(DriverEntity row, String action, String reason, String operator) {
var event = new DriverHistoryEntity();
event.setId(IdWorker.getId());
event.setDriverId(row.getId());
event.setRecordVersion(row.getRecordVersion());
event.setAction(action);
event.setReason(reason);
event.setLicenseFileId(row.getLicenseFileId());
event.setOperatorId(operator);
event.setOccurredAt(row.getUpdatedAt());
try { event.setSnapshotJson(json.writeValueAsString(response(row, clock.instant(), null))); }
catch (JsonProcessingException e) { throw new IllegalStateException("司机历史快照写入失败", e); }
if (history.insert(event) != 1) throw conflict();
}
private DriverModels.Response response(DriverEntity row, Instant now, Instant expectedEnd) {
var details = new DriverModels.Draft(row.getName(), row.getPhone(), row.getOwnership(), row.getRegion(),
row.getLicenseNumber(), row.getLicenseType(), row.getLicenseIssuedOn(), row.getLicenseExpiresOn(), row.getLicenseZone(), row.getRemark(),
new DriverModels.Profile(row.getWarehouseId(), row.getVehicleModels(), row.getLanguagesAndArea(), row.getMedicalExpiresOn(), row.getTrainingExpiresOn(), row.getInsuranceExpiresOn()));
var qualification = DriverQualificationPolicy.evaluate(new DriverQualificationPolicy.Driver(Boolean.TRUE.equals(row.getActive()),
DriverQualificationPolicy.ReviewStatus.valueOf(row.getReviewStatus()), row.getLicenseFileId() != null,
row.getLicenseExpiresOn(), ZoneId.of(row.getLicenseZone())), now, expectedEnd);
return new DriverModels.Response(row.getId().toString(), row.getDriverNo(), details, Boolean.TRUE.equals(row.getActive()),
row.getReviewStatus(), row.getLicenseFileId() == null ? null : row.getLicenseFileId().toString(),
row.getRecordVersion(), row.getUpdatedBy(), row.getUpdatedAt(), qualification,
licenseState(row.getLicenseExpiresOn(), row.getLicenseZone(), now), row.getWarehouseCode(), row.getWarehouseName());
}
private static void validate(DriverModels.Draft draft) {
if (trim(draft.name()) == null || trim(draft.phone()) == null) throw bad("司机姓名和电话不能为空");
if (optionalChoice(draft.ownership(), Set.of("OWNED", "DISPATCHED"), "司机归属") == null
|| optionalChoice(draft.region(), Set.of("DOMESTIC", "OVERSEAS"), "区域") == null) throw bad("司机归属和区域不能为空");
try { ZoneId.of(draft.licenseZone()); }
catch (DateTimeException | NullPointerException e) { throw bad("请选择有效的证照时区"); }
for (LocalDate date : new LocalDate[]{draft.licenseIssuedOn(), draft.licenseExpiresOn()}) {
if (date != null && (date.getYear() < 1900 || date.getYear() > 9998)) throw bad("证照日期超出允许范围");
}
if (draft.profile() != null) for (LocalDate date : new LocalDate[]{draft.profile().medicalExpiresOn(), draft.profile().trainingExpiresOn(), draft.profile().insuranceExpiresOn()}) {
if (date != null && (date.getYear() < 1900 || date.getYear() > 9998)) throw bad("其他资质日期超出允许范围");
}
if (draft.licenseIssuedOn() != null && draft.licenseExpiresOn() != null && draft.licenseIssuedOn().isAfter(draft.licenseExpiresOn()))
throw bad("驾驶证到期日期不能早于签发日期");
}
private void assign(DriverEntity row, DriverModels.Draft draft) {
row.setName(trim(draft.name())); row.setPhone(trim(draft.phone()));
row.setOwnership(draft.ownership()); row.setRegion(draft.region());
row.setLicenseNumber(trim(draft.licenseNumber())); row.setLicenseType(trim(draft.licenseType()));
row.setLicenseIssuedOn(draft.licenseIssuedOn()); row.setLicenseExpiresOn(draft.licenseExpiresOn());
row.setLicenseZone(draft.licenseZone()); row.setRemark(trim(draft.remark()));
var profile = draft.profile();
var warehouse = profile == null || profile.warehouseId() == null ? null : warehouses.required(profile.warehouseId(), draft.region());
row.setWarehouseId(warehouse == null ? null : Long.valueOf(warehouse.id()));
row.setWarehouseCode(warehouse == null ? null : warehouse.code());
row.setWarehouseName(warehouse == null ? null : warehouse.name());
row.setVehicleModels(profile == null ? null : trim(profile.vehicleModels()));
row.setLanguagesAndArea(profile == null ? null : trim(profile.languagesAndArea()));
row.setMedicalExpiresOn(profile == null ? null : profile.medicalExpiresOn());
row.setTrainingExpiresOn(profile == null ? null : profile.trainingExpiresOn());
row.setInsuranceExpiresOn(profile == null ? null : profile.insuranceExpiresOn());
}
private static String licenseState(LocalDate expiry, String zone, Instant now) {
if (expiry == null) return "MISSING";
LocalDate today = now.atZone(ZoneId.of(zone)).toLocalDate();
if (expiry.isBefore(today)) return "EXPIRED";
return expiry.isAfter(today.plusDays(30)) ? "VALID" : "EXPIRING";
}
private LocalDateTime now() { return LocalDateTime.ofInstant(clock.instant(), ZoneOffset.UTC); }
private static void requireLicense(DriverEntity row) {
if (row.getLicenseFileId() == null || trim(row.getLicenseNumber()) == null || trim(row.getLicenseType()) == null
|| row.getLicenseExpiresOn() == null) throw bad("请补齐驾驶证编号、类型、有效期及附件");
}
private static String blockReason(DriverQualificationPolicy.Reason reason) {
return switch (reason) {
case INACTIVE -> "司机已停用";
case MISSING_LICENSE -> "请上传驾驶证附件";
case MISSING_EXPIRY -> "请补齐驾驶证到期日期";
case PENDING_REVIEW -> "司机证照尚未审核通过";
case REJECTED -> "司机证照已被打回";
case EXPIRED -> "驾驶证已过期";
case MISSING_TRIP_END -> "请填写司机预计任务结束时间";
case INVALID_TRIP_END -> "司机预计任务结束时间必须晚于当前时间";
case EXPIRES_DURING_TRIP -> "驾驶证将在预计任务结束前到期,请更换司机或调整计划";
case ELIGIBLE -> "司机可派车";
};
}
private static String trim(String text) { return text == null || text.isBlank() ? null : text.trim(); }
private static String optionalChoice(String value, Set<String> allowed, String label) {
if (trim(value) == null) return null;
if (!allowed.contains(value)) throw bad(label + "不合法");
return value;
}
private static ResponseStatusException bad(String message) { return new ResponseStatusException(HttpStatus.BAD_REQUEST, message); }
private static ResponseStatusException notFound() { return new ResponseStatusException(HttpStatus.NOT_FOUND, "司机档案不存在"); }
private static ResponseStatusException conflict() { return new ResponseStatusException(HttpStatus.CONFLICT, "司机档案已被修改,请刷新后重试"); }
}
@@ -0,0 +1,14 @@
package com.baiyue.lastleg.fleet.driver;
import com.baiyue.common.core.api.ApiResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import java.util.List;
@FeignClient(name = "warehouse-service", contextId = "fleetWarehouseClient", url = "${baiyue.clients.domestic-warehouse.url:}")
public interface FleetWarehouseClient {
@GetMapping("/internal/warehouses/order-catalog")
ApiResponse<List<Warehouse>> activeWarehouses(@RequestHeader("X-Internal-Service-Token") String token);
record Warehouse(Long id, String warehouseCode, String warehouseName, String warehouseType, String countryCode) { }
}
@@ -0,0 +1,41 @@
package com.baiyue.lastleg.fleet.driver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Set;
@Component
public class FleetWarehouseDirectory {
private final FleetWarehouseClient client;
private final String token;
public FleetWarehouseDirectory(FleetWarehouseClient client, @Value("${baiyue.security.internal-service-token:}") String token) {
this.client = client; this.token = token;
}
public List<DriverModels.WarehouseOption> options(String region) {
if (!Set.of("DOMESTIC", "OVERSEAS").contains(region == null ? "" : region))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请选择国内或海外区域");
try {
var result = client.activeWarehouses(token);
if (result == null || !result.successful() || result.data() == null) throw unavailable();
return result.data().stream().filter(row -> row != null && row.id() != null && row.id() > 0
&& row.warehouseCode() != null && !row.warehouseCode().isBlank() && row.warehouseName() != null && !row.warehouseName().isBlank()
&& ("DOMESTIC".equals(region) ? "DOMESTIC".equals(row.warehouseType())
: Set.of("OVERSEAS", "OVERSEAS_PARTNER").contains(row.warehouseType() == null ? "" : row.warehouseType())))
.map(row -> new DriverModels.WarehouseOption(row.id().toString(), row.warehouseCode(), row.warehouseName(), region)).toList();
} catch (ResponseStatusException e) { throw e; }
catch (RuntimeException e) { throw unavailable(); }
}
public DriverModels.WarehouseOption required(long id, String region) {
return options(region).stream().filter(row -> row.id().equals(Long.toString(id))).findFirst()
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "所属仓库不存在、已停用或与区域不符"));
}
private static ResponseStatusException unavailable() {
return new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "仓库目录暂不可用,请重试");
}
}
@@ -0,0 +1,89 @@
package com.baiyue.lastleg.fleet.driver;
import com.baiyue.lastleg.config.LastlegRestClientFactory;
import com.baiyue.lastleg.config.LastlegRestClientProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;
@Component
public class HttpDriverFileGateway implements DriverFileGateway {
static final String TYPE = "FLEET_DRIVER_LICENSE";
static final long MAX_SIZE = 10L * 1024 * 1024;
private static final Set<String> CONTENT_TYPES = Set.of("application/pdf", "image/jpeg", "image/png");
private static final String PATH = "/internal/file/v1/business-files/0/FLEET_DRIVER_LICENSE/{driver}";
private final RestClient client;
private final String token;
public HttpDriverFileGateway(RestClient.Builder builder, LastlegRestClientFactory factory, LastlegRestClientProperties properties,
@Value("${baiyue.clients.file.url:http://127.0.0.1:9205}") String baseUrl,
@Value("${baiyue.security.internal-service-token:}") String token) {
this.client = factory.build(builder, baseUrl, properties.getCustomerVisitFile());
this.token = token;
}
@Override
public DriverModels.File upload(long driverId, String operatorId, MultipartFile file) {
if (file == null || file.isEmpty() || file.getSize() > MAX_SIZE || !CONTENT_TYPES.contains(Objects.toString(file.getContentType(), "")))
throw bad("驾驶证附件须为非空的 PDF、JPG 或 PNG,最大 10MiB");
var body = new MultipartBodyBuilder();
try {
body.part("file", new ByteArrayResource(file.getBytes()) {
@Override public String getFilename() { return file.getOriginalFilename(); }
}).contentType(MediaType.parseMediaType(file.getContentType()));
} catch (IOException e) { throw bad("无法读取驾驶证附件"); }
Envelope result = client.post().uri(PATH, driverId).header("X-Internal-Service-Token", token)
.header("X-Operator-Id", operatorId).contentType(MediaType.MULTIPART_FORM_DATA).body(body.build()).retrieve()
.onStatus(HttpStatusCode::isError, (request, response) -> { throw unavailable(response.getStatusCode()); })
.body(Envelope.class);
return verified(result, driverId, null);
}
@Override
public DriverModels.File metadata(long driverId, long fileId) {
Envelope result = client.get().uri(PATH + "/{file}", driverId, fileId).header("X-Internal-Service-Token", token).retrieve()
.onStatus(HttpStatusCode::isError, (request, response) -> { throw unavailable(response.getStatusCode()); })
.body(Envelope.class);
return verified(result, driverId, fileId);
}
@Override
public byte[] download(long driverId, long fileId) {
byte[] content = client.get().uri(PATH + "/{file}/content", driverId, fileId).header("X-Internal-Service-Token", token).retrieve()
.onStatus(HttpStatusCode::isError, (request, response) -> { throw unavailable(response.getStatusCode()); }).body(byte[].class);
if (content == null || content.length == 0 || content.length > MAX_SIZE) throw unavailable(HttpStatus.SERVICE_UNAVAILABLE);
return content;
}
static DriverModels.File verified(Envelope result, long driverId, Long fileId) {
if (result == null) throw unavailable(HttpStatus.SERVICE_UNAVAILABLE);
if (!"200".equals(result.code())) throw unavailable(result.code() != null && result.code().startsWith("A04")
? HttpStatus.BAD_REQUEST : HttpStatus.SERVICE_UNAVAILABLE);
Metadata data = result.data();
if (data == null || data.fileId() == null || data.fileId() <= 0 || !Objects.equals(data.tenantId(), 0L)
|| !TYPE.equals(data.businessType()) || !Long.toString(driverId).equals(data.businessId())
|| (fileId != null && !fileId.equals(data.fileId())) || data.fileName() == null || data.fileName().isBlank()
|| !CONTENT_TYPES.contains(Objects.toString(data.contentType(), "")) || data.sizeBytes() == null
|| data.sizeBytes() <= 0 || data.sizeBytes() > MAX_SIZE)
throw bad("文件不属于当前司机或不是有效驾驶证附件");
return new DriverModels.File(data.fileId().toString(), data.fileName(), data.contentType(), data.sizeBytes());
}
private static ResponseStatusException unavailable(HttpStatusCode status) {
return new ResponseStatusException(status.is4xxClientError() ? HttpStatus.BAD_REQUEST : HttpStatus.SERVICE_UNAVAILABLE,
"驾驶证文件不可用或归属校验失败");
}
private static ResponseStatusException bad(String message) { return new ResponseStatusException(HttpStatus.BAD_REQUEST, message); }
record Envelope(String code, Metadata data) { }
record Metadata(Long fileId, Long tenantId, String businessType, String businessId,
String fileName, String contentType, Long sizeBytes) { }
}
@@ -0,0 +1,119 @@
package com.baiyue.lastleg.fleet.driver;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.core.api.PageResult;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.fleet.domain.DriverQualificationPolicy;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
@RestController
@Validated
@RequestMapping("/api/platform/v1/last-leg/fleet/drivers")
@Tag(name = "Fleet drivers / 司机管理")
public class PlatformDriverController {
private final DriverService service;
public PlatformDriverController(DriverService service) { this.service = service; }
@GetMapping
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:list')")
public ApiResponse<DriverModels.DriverPage> page(@Valid DriverModels.Query query) {
return ApiResponse.success(service.page(query));
}
@GetMapping("/warehouse-options")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:list')")
public ApiResponse<java.util.List<DriverModels.WarehouseOption>> warehouseOptions(@RequestParam String region) {
return ApiResponse.success(service.warehouseOptions(region));
}
@GetMapping("/{id}")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:list')")
public ApiResponse<DriverModels.Response> detail(@PathVariable @Min(1) long id,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant expectedEnd) {
return ApiResponse.success(service.detail(id, expectedEnd));
}
@GetMapping("/{id}/qualification")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:list')")
public ApiResponse<DriverQualificationPolicy.Qualification> qualification(@PathVariable @Min(1) long id,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant expectedEnd) {
return ApiResponse.success(service.detail(id, expectedEnd).qualification());
}
@GetMapping("/{id}/history")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:list')")
public ApiResponse<PageResult<DriverModels.History>> history(@PathVariable @Min(1) long id,
@RequestParam(defaultValue = "1") @Min(1) int page, @RequestParam(defaultValue = "20") @Min(1) @Max(200) int size) {
return ApiResponse.success(service.history(id, page, size));
}
@PostMapping
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:create')")
public ApiResponse<DriverModels.Response> create(@AuthenticationPrincipal AuthenticatedUser user, @Valid @RequestBody DriverModels.Draft draft) {
return ApiResponse.success(service.create(operator(user), draft));
}
@PutMapping("/{id}")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:edit')")
public ApiResponse<DriverModels.Response> update(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable @Min(1) long id,
@Valid @RequestBody DriverModels.Update request) {
return ApiResponse.success(service.update(id, operator(user), request));
}
@PatchMapping("/{id}/status")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:status')")
public ApiResponse<DriverModels.Response> status(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable @Min(1) long id,
@Valid @RequestBody DriverModels.ChangeStatus request) {
return ApiResponse.success(service.changeStatus(id, operator(user), request));
}
@PostMapping("/{id}/review")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:review')")
public ApiResponse<DriverModels.Response> review(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable @Min(1) long id,
@Valid @RequestBody DriverModels.Review request) {
return ApiResponse.success(service.review(id, operator(user), request));
}
@PostMapping("/{id}/submit")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:edit')")
public ApiResponse<DriverModels.Response> submit(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable @Min(1) long id,
@Valid @RequestBody DriverModels.Submit request) {
return ApiResponse.success(service.submit(id, operator(user), request));
}
@PostMapping(value = "/{id}/license", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:upload')")
public ApiResponse<DriverModels.Response> upload(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable @Min(1) long id,
@RequestParam @Min(0) long recordVersion, @RequestPart("file") MultipartFile file) {
return ApiResponse.success(service.uploadLicense(id, recordVersion, operator(user), file));
}
@GetMapping("/{id}/license/{fileId}")
@PreAuthorize("hasAuthority('platform:overseas-master-data:driver:list')")
public ResponseEntity<byte[]> download(@PathVariable @Min(1) long id, @PathVariable @Min(1) long fileId) {
var file = service.download(id, fileId);
return ResponseEntity.ok().cacheControl(CacheControl.noStore())
.header("X-Content-Type-Options", "nosniff")
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(file.metadata().fileName(), StandardCharsets.UTF_8).build().toString())
.contentType(MediaType.parseMediaType(file.metadata().contentType())).body(file.content());
}
private static String operator(AuthenticatedUser user) {
if (user == null || user.userId() == null) throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "请重新登录");
return user.userId().toString();
}
}
@@ -0,0 +1,71 @@
package com.baiyue.lastleg.fleet.maintenance;
import com.baiyue.lastleg.config.LastlegRestClientFactory;
import com.baiyue.lastleg.config.LastlegRestClientProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;
@Component
public class HttpVehicleCareFileGateway implements VehicleCareFileGateway {
private static final String TYPE = "FLEET_VEHICLE_RECORD_PHOTO";
private static final String PATH = "/internal/file/v1/business-files/0/FLEET_VEHICLE_RECORD_PHOTO/{record}";
private static final long MAX_SIZE = 10L * 1024 * 1024;
private final RestClient client;
private final String token;
public HttpVehicleCareFileGateway(RestClient.Builder builder, LastlegRestClientFactory factory, LastlegRestClientProperties properties,
@Value("${baiyue.clients.file.url:http://127.0.0.1:9205}") String baseUrl,
@Value("${baiyue.security.internal-service-token:}") String token) {
client = factory.build(builder, baseUrl, properties.getCustomerVisitFile()); this.token = token;
}
@Override public VehicleCareModels.File upload(long recordId, String operatorId, MultipartFile file) {
if (file == null || file.isEmpty() || file.getSize() > MAX_SIZE || !image(file.getContentType())) throw bad("运维照片须为非空 JPG 或 PNG,最大 10MiB");
var body = new MultipartBodyBuilder();
try { body.part("file", new ByteArrayResource(file.getBytes()) {
@Override public String getFilename() { return file.getOriginalFilename(); }
}).contentType(MediaType.parseMediaType(file.getContentType())); }
catch (IOException error) { throw bad("无法读取运维照片"); }
var result = client.post().uri(PATH, recordId).header("X-Internal-Service-Token", token).header("X-Operator-Id", operatorId)
.contentType(MediaType.MULTIPART_FORM_DATA).body(body.build()).retrieve()
.onStatus(HttpStatusCode::isError, (request, response) -> { throw unavailable(response.getStatusCode()); }).body(Envelope.class);
return verified(result, recordId, null);
}
@Override public VehicleCareModels.File metadata(long recordId, long fileId) {
return verified(client.get().uri(PATH + "/{file}", recordId, fileId).header("X-Internal-Service-Token", token).retrieve()
.onStatus(HttpStatusCode::isError, (request, response) -> { throw unavailable(response.getStatusCode()); }).body(Envelope.class), recordId, fileId);
}
@Override public byte[] download(long recordId, long fileId) {
var response = client.get().uri(PATH + "/{file}/content", recordId, fileId).header("X-Internal-Service-Token", token).retrieve()
.onStatus(HttpStatusCode::isError, (request, result) -> { throw unavailable(result.getStatusCode()); }).toEntity(byte[].class);
return imageContent(response);
}
static byte[] imageContent(ResponseEntity<byte[]> response) {
byte[] content = response.getBody();
if (content == null || content.length == 0 || content.length > MAX_SIZE
|| !image(Objects.toString(response.getHeaders().getContentType(), ""))) throw unavailable(HttpStatus.SERVICE_UNAVAILABLE);
return content;
}
static VehicleCareModels.File verified(Envelope result, long recordId, Long fileId) {
if (result == null || !"200".equals(result.code())) throw unavailable(HttpStatus.SERVICE_UNAVAILABLE);
var data = result.data();
if (data == null || data.fileId() == null || data.fileId() <= 0 || !Objects.equals(data.tenantId(), 0L)
|| !TYPE.equals(data.businessType()) || !Long.toString(recordId).equals(data.businessId())
|| (fileId != null && !fileId.equals(data.fileId())) || data.fileName() == null || data.fileName().isBlank()
|| !image(data.contentType()) || data.sizeBytes() == null || data.sizeBytes() <= 0 || data.sizeBytes() > MAX_SIZE)
throw bad("文件不属于当前运维记录或不是有效照片");
return new VehicleCareModels.File(data.fileId().toString(), data.fileName(), data.contentType(), data.sizeBytes());
}
private static boolean image(String type) { return Set.of("image/jpeg", "image/png").contains(Objects.toString(type, "")); }
private static ResponseStatusException bad(String message) { return new ResponseStatusException(HttpStatus.BAD_REQUEST, message); }
private static ResponseStatusException unavailable(HttpStatusCode status) { return new ResponseStatusException(status.is4xxClientError() ? HttpStatus.BAD_REQUEST : HttpStatus.SERVICE_UNAVAILABLE, "运维照片不可用或归属校验失败"); }
record Envelope(String code, Metadata data) { }
record Metadata(Long fileId, Long tenantId, String businessType, String businessId, String fileName, String contentType, Long sizeBytes) { }
}
@@ -0,0 +1,69 @@
package com.baiyue.lastleg.fleet.maintenance;
import com.baiyue.common.core.api.*;
import com.baiyue.common.security.AuthenticatedUser;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
@RestController
@Validated
@RequestMapping("/api/platform/v1/last-leg/fleet/vehicles/{vehicleId}/records")
public class PlatformVehicleCareController {
private final VehicleCareService service;
public PlatformVehicleCareController(VehicleCareService service) { this.service = service; }
@GetMapping
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:list')")
public ApiResponse<PageResult<VehicleCareModels.Response>> page(@PathVariable @Min(1) long vehicleId, @Valid VehicleCareModels.Query query) {
return ApiResponse.success(service.page(vehicleId, query));
}
@GetMapping("/{recordNo}")
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:list')")
public ApiResponse<VehicleCareModels.Response> detail(@PathVariable @Min(1) long vehicleId, @PathVariable String recordNo) {
return ApiResponse.success(service.detail(vehicleId, recordNo));
}
@PostMapping
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:record-create')")
public ApiResponse<VehicleCareModels.Response> create(@PathVariable @Min(1) long vehicleId, @AuthenticationPrincipal AuthenticatedUser user,
@RequestBody @Valid VehicleCareModels.Create request) {
return ApiResponse.success(service.create(vehicleId, operator(user), request));
}
@PutMapping("/{recordNo}")
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:record-edit')")
public ApiResponse<VehicleCareModels.Response> update(@PathVariable @Min(1) long vehicleId, @PathVariable String recordNo,
@AuthenticationPrincipal AuthenticatedUser user, @RequestBody @Valid VehicleCareModels.Update request) {
return ApiResponse.success(service.update(vehicleId, recordNo, operator(user), request));
}
@PostMapping(value = "/{recordNo}/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:record-upload')")
public ApiResponse<VehicleCareModels.Response> upload(@PathVariable @Min(1) long vehicleId, @PathVariable String recordNo,
@AuthenticationPrincipal AuthenticatedUser user, @RequestParam @Min(0) long recordVersion,
@RequestParam @NotBlank @Size(max = 128) String idempotencyKey, @RequestPart("file") MultipartFile file) {
return ApiResponse.success(service.upload(vehicleId, recordNo, recordVersion, idempotencyKey, operator(user), file));
}
@GetMapping("/{recordNo}/files/{fileId}")
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:list')")
public ResponseEntity<byte[]> download(@PathVariable @Min(1) long vehicleId, @PathVariable String recordNo, @PathVariable @Min(1) long fileId) {
var file = service.download(vehicleId, recordNo, fileId);
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).header("X-Content-Type-Options", "nosniff")
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(file.metadata().fileName(), StandardCharsets.UTF_8).build().toString())
.contentType(MediaType.parseMediaType(file.metadata().contentType())).body(file.content());
}
@GetMapping("/{recordNo}/history")
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:list')")
public ApiResponse<PageResult<VehicleCareModels.History>> history(@PathVariable @Min(1) long vehicleId, @PathVariable String recordNo,
@RequestParam(defaultValue = "1") @Min(1) int page, @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
return ApiResponse.success(service.history(vehicleId, recordNo, page, size));
}
private static String operator(AuthenticatedUser user) {
if (user == null || user.userId() == null) throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "请重新登录");
return user.userId().toString();
}
}
@@ -0,0 +1,25 @@
package com.baiyue.lastleg.fleet.maintenance;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("ll_fleet_vehicle_record")
public class VehicleCareEntity {
@TableId(type = IdType.ASSIGN_ID) private Long id;
private String recordNo;
private Long vehicleId;
private String vehiclePlate;
private String recordType;
private LocalDateTime occurredAt;
private String detailsJson;
private String filesJson;
private String idempotencyKey;
private String requestHash;
private Long recordVersion;
private String createdBy;
private String updatedBy;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,9 @@
package com.baiyue.lastleg.fleet.maintenance;
import org.springframework.web.multipart.MultipartFile;
public interface VehicleCareFileGateway {
VehicleCareModels.File upload(long recordId, String operatorId, MultipartFile file);
VehicleCareModels.File metadata(long recordId, long fileId);
byte[] download(long recordId, long fileId);
}
@@ -0,0 +1,18 @@
package com.baiyue.lastleg.fleet.maintenance;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("ll_fleet_vehicle_record_history")
public class VehicleCareHistory {
@TableId(type = IdType.ASSIGN_ID) private Long id;
private Long recordId;
private Long recordVersion;
private String action;
private String reason;
private String operatorId;
private LocalDateTime occurredAt;
private String snapshotJson;
}
@@ -0,0 +1,7 @@
package com.baiyue.lastleg.fleet.maintenance;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface VehicleCareHistoryMapper extends BaseMapper<VehicleCareHistory> { }
@@ -0,0 +1,14 @@
package com.baiyue.lastleg.fleet.maintenance;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
@Mapper
public interface VehicleCareMapper extends BaseMapper<VehicleCareEntity> {
@Select("SELECT * FROM ll_fleet_vehicle_record WHERE vehicle_id=#{vehicleId} AND record_no=#{recordNo}")
VehicleCareEntity find(@Param("vehicleId") long vehicleId, @Param("recordNo") String recordNo);
@Select("SELECT * FROM ll_fleet_vehicle_record WHERE vehicle_id=#{vehicleId} AND record_no=#{recordNo} FOR UPDATE")
VehicleCareEntity lock(@Param("vehicleId") long vehicleId, @Param("recordNo") String recordNo);
@Select("SELECT * FROM ll_fleet_vehicle_record WHERE vehicle_id=#{vehicleId} AND created_by=#{operator} AND idempotency_key=#{key} FOR UPDATE")
VehicleCareEntity lockCreated(@Param("vehicleId") long vehicleId, @Param("operator") String operator, @Param("key") String key);
}
@@ -0,0 +1,42 @@
package com.baiyue.lastleg.fleet.maintenance;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
public final class VehicleCareModels {
private VehicleCareModels() { }
public record Query(@Min(1) Integer page, @Min(1) @Max(100) Integer size,
@Pattern(regexp = "MAINTENANCE|FUEL|REPAIR|BREAKDOWN|RESCUE|EXCEPTION") String recordType) {
public Query { page = page == null ? 1 : page; size = size == null ? 20 : size; }
}
public record Draft(@NotBlank @Pattern(regexp = "MAINTENANCE|FUEL|REPAIR|BREAKDOWN|RESCUE|EXCEPTION") String recordType,
@NotNull Instant occurredAt,
@Pattern(regexp = "KM|MI") String distanceUnit,
@DecimalMin("0") @Digits(integer = 10, fraction = 3) BigDecimal odometer,
@DecimalMin("0") @Digits(integer = 10, fraction = 3) BigDecimal lastServiceOdometer,
@DecimalMin("0") @Digits(integer = 10, fraction = 3) BigDecimal nextServiceOdometer,
@DecimalMin(value = "0", inclusive = false) @Digits(integer = 8, fraction = 3) BigDecimal fuelQuantity,
@Pattern(regexp = "L|US_GAL|IMP_GAL") String fuelUnit,
@Pattern(regexp = "PENDING|VERIFIED") String verificationStatus,
@Size(max = 1000) String remark, @Valid Incident incident) { }
public record Incident(@NotBlank @Size(max = 2000) String description,
@Size(max = 256) String item, @Size(max = 512) String place,
@Size(max = 128) String handler,
@NotBlank @Pattern(regexp = "PENDING|IN_PROGRESS|COMPLETED") String processingStatus,
@Pattern(regexp = "ROUTE|TIMEOUT|DELIVERY|VEHICLE_BREAKDOWN") String exceptionType,
@DecimalMin("0") @Digits(integer = 12, fraction = 2) BigDecimal reportedCost,
@Pattern(regexp = "[A-Z]{3}") String currency) { }
public record Create(@NotBlank @Size(max = 128) String idempotencyKey, @NotNull @Valid Draft details) { }
public record Update(@NotNull @Min(0) Long recordVersion, @NotBlank @Size(max = 1000) String reason,
@NotNull @Valid Draft details) { }
public record File(String fileId, String fileName, String contentType, long sizeBytes) { }
public record Attached(String uploadKey, String sha256, File file) { }
public record Response(String recordNo, String vehicleId, String vehiclePlate, Draft details,
List<File> files, long recordVersion, String updatedBy, Instant updatedAt, String paymentStatus) { }
public record History(long recordVersion, String action, String reason, String operatorId,
Instant occurredAt, Response snapshot) { }
public record Download(File metadata, byte[] content) { }
}
@@ -0,0 +1,181 @@
package com.baiyue.lastleg.fleet.maintenance;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baiyue.common.core.api.PageResult;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.time.*;
import java.util.*;
@Service
public class VehicleCareService {
private final VehicleCareMapper records;
private final VehicleCareHistoryMapper histories;
private final VehicleRepository vehicles;
private final VehicleCareFileGateway files;
private final ObjectMapper json;
public VehicleCareService(VehicleCareMapper records, VehicleCareHistoryMapper histories,
VehicleRepository vehicles, VehicleCareFileGateway files, ObjectMapper json) {
this.records = records; this.histories = histories; this.vehicles = vehicles; this.files = files; this.json = json;
}
public PageResult<VehicleCareModels.Response> page(long vehicleId, VehicleCareModels.Query query) {
vehicles.findById(vehicleId).orElseThrow(VehicleCareService::missing);
var page = records.selectPage(new Page<>(query.page(), query.size()), new LambdaQueryWrapper<VehicleCareEntity>()
.eq(VehicleCareEntity::getVehicleId, vehicleId)
.eq(query.recordType() != null, VehicleCareEntity::getRecordType, query.recordType())
.orderByDesc(VehicleCareEntity::getOccurredAt, VehicleCareEntity::getId));
return new PageResult<>(page.getRecords().stream().map(this::response).toList(), page.getCurrent(), page.getSize(), page.getTotal(), page.getPages());
}
public VehicleCareModels.Response detail(long vehicleId, String number) { return response(required(vehicleId, number, false)); }
@Transactional
public VehicleCareModels.Response create(long vehicleId, String operator, VehicleCareModels.Create request) {
// Serialize creation per vehicle; no empty-range locks or duplicate creation after a lost response.
var vehicle = vehicles.lockById(vehicleId).orElseThrow(VehicleCareService::missing);
String fingerprint = digest(write(request.details()).getBytes(StandardCharsets.UTF_8));
var prior = records.lockCreated(vehicleId, operator, request.idempotencyKey());
if (prior != null) {
if (!prior.getRequestHash().equals(fingerprint)) throw conflict("请求标识已用于其他运维记录内容");
return response(prior);
}
validate(request.details());
var row = new VehicleCareEntity(); row.setId(IdWorker.getId());
row.setRecordNo("VR-" + UUID.randomUUID().toString().replace("-", "").substring(0, 16).toUpperCase(Locale.ROOT));
row.setVehicleId(vehicleId); row.setVehiclePlate(vehicle.plateNumber()); row.setRecordType(request.details().recordType());
row.setOccurredAt(utc(request.details().occurredAt())); row.setDetailsJson(write(request.details())); row.setFilesJson("[]");
row.setIdempotencyKey(request.idempotencyKey()); row.setRequestHash(fingerprint); row.setRecordVersion(0L);
row.setCreatedBy(operator); row.setUpdatedBy(operator); row.setCreatedAt(utc(Instant.now())); row.setUpdatedAt(row.getCreatedAt());
if (records.insert(row) != 1) throw conflict("运维记录保存失败");
record(row, "CREATE", null, operator);
return response(row);
}
@Transactional
public VehicleCareModels.Response update(long vehicleId, String number, String operator, VehicleCareModels.Update request) {
var row = required(vehicleId, number, true); version(row, request.recordVersion()); validate(request.details());
if (!row.getRecordType().equals(request.details().recordType())) throw conflict("已保存记录不能改变运维类型");
if (request.reason() == null || request.reason().isBlank()) throw bad("请填写更正原因");
row.setOccurredAt(utc(request.details().occurredAt())); row.setDetailsJson(write(request.details()));
persist(row, request.recordVersion(), "UPDATE", request.reason(), operator);
return response(row);
}
@Transactional
public VehicleCareModels.Response upload(long vehicleId, String number, long expectedVersion, String uploadKey, String operator, MultipartFile file) {
var row = required(vehicleId, number, true);
if (uploadKey == null || uploadKey.isBlank() || uploadKey.length() > 128) throw bad("附件请求标识无效");
if (file == null || file.isEmpty() || file.getSize() > 10L * 1024 * 1024
|| !Set.of("image/jpeg", "image/png").contains(Objects.toString(file.getContentType(), ""))) throw bad("请选择非空 JPG 或 PNG 图片,最大 10MiB");
String fingerprint;
try { fingerprint = digest(file.getBytes()); } catch (IOException error) { throw bad("无法读取附件"); }
var attached = new ArrayList<>(attached(row));
var replay = attached.stream().filter(item -> item.uploadKey().equals(uploadKey)).findFirst();
if (replay.isPresent()) {
if (!replay.get().sha256().equals(fingerprint)) throw conflict("附件请求标识已用于不同图片");
return response(row);
}
version(row, expectedVersion);
if (attached.size() >= 20) throw bad("每条记录最多保存 20 张图片");
var uploaded = files.upload(row.getId(), operator, file);
attached.add(new VehicleCareModels.Attached(uploadKey, fingerprint, uploaded)); row.setFilesJson(write(attached));
persist(row, expectedVersion, "UPLOAD", uploaded.fileName(), operator);
return response(row);
}
public VehicleCareModels.Download download(long vehicleId, String number, long fileId) {
var row = required(vehicleId, number, false);
if (attached(row).stream().noneMatch(item -> item.file().fileId().equals(Long.toString(fileId)))) throw missing();
var metadata = files.metadata(row.getId(), fileId);
return new VehicleCareModels.Download(metadata, files.download(row.getId(), fileId));
}
public PageResult<VehicleCareModels.History> history(long vehicleId, String number, int page, int size) {
var row = required(vehicleId, number, false);
var result = histories.selectPage(new Page<>(page, size), new LambdaQueryWrapper<VehicleCareHistory>()
.eq(VehicleCareHistory::getRecordId, row.getId()).orderByDesc(VehicleCareHistory::getRecordVersion));
return new PageResult<>(result.getRecords().stream().map(entry -> new VehicleCareModels.History(entry.getRecordVersion(),
entry.getAction(), entry.getReason(), entry.getOperatorId(), entry.getOccurredAt().toInstant(ZoneOffset.UTC),
read(entry.getSnapshotJson(), VehicleCareModels.Response.class))).toList(), result.getCurrent(), result.getSize(), result.getTotal(), result.getPages());
}
private void persist(VehicleCareEntity row, long expected, String action, String reason, String operator) {
row.setRecordVersion(expected + 1); row.setUpdatedBy(operator); row.setUpdatedAt(utc(Instant.now()));
if (records.update(row, new LambdaUpdateWrapper<VehicleCareEntity>().eq(VehicleCareEntity::getId, row.getId())
.eq(VehicleCareEntity::getRecordVersion, expected)) != 1) throw conflict("记录已变化,请刷新后重试");
record(row, action, reason, operator);
}
private void record(VehicleCareEntity row, String action, String reason, String operator) {
var history = new VehicleCareHistory(); history.setId(IdWorker.getId()); history.setRecordId(row.getId());
history.setRecordVersion(row.getRecordVersion()); history.setAction(action); history.setReason(reason);
history.setOperatorId(operator); history.setOccurredAt(row.getUpdatedAt()); history.setSnapshotJson(write(response(row)));
if (histories.insert(history) != 1) throw conflict("记录历史保存失败");
}
private VehicleCareModels.Response response(VehicleCareEntity row) {
return new VehicleCareModels.Response(row.getRecordNo(), row.getVehicleId().toString(), row.getVehiclePlate(),
read(row.getDetailsJson(), VehicleCareModels.Draft.class), attached(row).stream().map(VehicleCareModels.Attached::file).toList(),
row.getRecordVersion(), row.getUpdatedBy(), row.getUpdatedAt().toInstant(ZoneOffset.UTC),
Set.of("REPAIR", "RESCUE").contains(row.getRecordType()) ? "UNLINKED" : null);
}
private VehicleCareEntity required(long vehicleId, String number, boolean lock) {
var row = lock ? records.lock(vehicleId, number) : records.find(vehicleId, number);
if (row == null) throw missing(); return row;
}
private static void version(VehicleCareEntity row, long expected) { if (row.getRecordVersion() != expected) throw conflict("记录已变化,请刷新后重试"); }
static void validate(VehicleCareModels.Draft value) {
if (value.occurredAt() == null || value.occurredAt().isAfter(Instant.now())) throw bad("记录时间不能晚于当前时间");
if (value.occurredAt().atOffset(ZoneOffset.UTC).getYear() < 1900) throw bad("记录时间须为 1900 年及以后");
if (Set.of("REPAIR", "BREAKDOWN", "RESCUE", "EXCEPTION").contains(Objects.toString(value.recordType(), ""))) {
validateIncident(value); return;
}
if (value.incident() != null) throw bad("保养加油不能混入维修、故障、救援或异常字段");
if (value.odometer() == null || value.odometer().signum() < 0 || !Set.of("KM", "MI").contains(Objects.toString(value.distanceUnit(), ""))) throw bad("请填写有效里程及单位");
if (!Set.of("PENDING", "VERIFIED").contains(Objects.toString(value.verificationStatus(), ""))) throw bad("核验状态无效");
if ("MAINTENANCE".equals(value.recordType())) {
if (value.lastServiceOdometer() == null || value.nextServiceOdometer() == null || value.lastServiceOdometer().signum() < 0
|| value.lastServiceOdometer().compareTo(value.odometer()) > 0 || value.nextServiceOdometer().compareTo(value.lastServiceOdometer()) <= 0)
throw bad("上次保养里程须不大于记录时里程,下次保养里程须大于上次保养里程");
if (value.fuelQuantity() != null || value.fuelUnit() != null) throw bad("保养记录不能包含加油字段");
} else if ("FUEL".equals(value.recordType())) {
if (value.fuelQuantity() == null || value.fuelQuantity().signum() <= 0 || value.fuelUnit() == null
|| !Set.of("L", "US_GAL", "IMP_GAL").contains(value.fuelUnit())) throw bad("请填写正数加油量并明确升、美制加仑或英制加仑");
if (value.lastServiceOdometer() != null || value.nextServiceOdometer() != null) throw bad("加油记录不能包含保养里程字段");
} else throw bad("记录类型无效");
}
private static void validateIncident(VehicleCareModels.Draft value) {
if (value.distanceUnit() != null || value.odometer() != null || value.lastServiceOdometer() != null || value.nextServiceOdometer() != null
|| value.fuelQuantity() != null || value.fuelUnit() != null || value.verificationStatus() != null) throw bad("处理记录不能混入保养、加油或核验字段");
var incident = value.incident();
if (incident == null || blank(incident.description())) throw bad("请填写事件描述");
if (!Set.of("PENDING", "IN_PROGRESS", "COMPLETED").contains(Objects.toString(incident.processingStatus(), ""))) throw bad("处理状态无效");
if (!"PENDING".equals(incident.processingStatus()) && blank(incident.handler())) throw bad("处理中或已完成记录须填写处理人");
boolean costRecord = Set.of("REPAIR", "RESCUE").contains(value.recordType());
if (costRecord && (blank(incident.item()) || blank(incident.place()))) throw bad("请填写维修或救援项目及地点");
if (!costRecord && (incident.item() != null || incident.place() != null || incident.reportedCost() != null || incident.currency() != null))
throw bad("故障和异常记录不接受维修救援费用字段");
if ("EXCEPTION".equals(value.recordType())) {
if (!Set.of("ROUTE", "TIMEOUT", "DELIVERY", "VEHICLE_BREAKDOWN").contains(Objects.toString(incident.exceptionType(), ""))) throw bad("请选择异常类型");
} else if (incident.exceptionType() != null) throw bad("非异常记录不能设置异常类型");
if (incident.reportedCost() != null) {
if (incident.reportedCost().signum() < 0 || blank(incident.currency())) throw bad("费用须为非负数并填写币种");
try { Currency.getInstance(incident.currency()); } catch (IllegalArgumentException error) { throw bad("费用币种无效"); }
} else if (incident.currency() != null) throw bad("未登记费用时不能填写币种");
}
private static boolean blank(String value) { return value == null || value.isBlank(); }
private List<VehicleCareModels.Attached> attached(VehicleCareEntity row) {
try { return json.readValue(row.getFilesJson(), new TypeReference<>() { }); } catch (JsonProcessingException error) { throw new IllegalStateException(error); }
}
private String write(Object value) { try { return json.writeValueAsString(value); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } }
private <T> T read(String value, Class<T> type) { try { return json.readValue(value, type); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } }
private static String digest(byte[] value) { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } }
private static LocalDateTime utc(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); }
private static ResponseStatusException missing() { return new ResponseStatusException(HttpStatus.NOT_FOUND, "车辆或当前车辆的记录不存在"); }
private static ResponseStatusException bad(String reason) { return new ResponseStatusException(HttpStatus.BAD_REQUEST, reason); }
private static ResponseStatusException conflict(String reason) { return new ResponseStatusException(HttpStatus.CONFLICT, reason); }
}
@@ -0,0 +1,42 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data @TableName("ll_fleet_external_booking")
public class FleetBookingEntity {
@TableId(type=IdType.INPUT) private Long id;
private String bookingNo;
private Long tripId;
private String tripNo;
private String customerId;
private String customerCode;
private String customerName;
private String status;
private String cargoJson;
private String destinationKey;
private String destinationLabel;
@TableField(updateStrategy=FieldStrategy.ALWAYS) private BigDecimal agreedAmount;
private String idempotencyKey;
private String requestHash;
private String confirmKey;
private String confirmHash;
private String cancelKey;
private String cancelHash;
private String incomingNo;
@TableField(updateStrategy=FieldStrategy.ALWAYS) private String dispatchNo;
private String receiptJson;
private String incomingKey;
private String incomingHash;
private String receiptKey;
private String receiptHash;
private String bindingKey;
private String bindingHash;
private Long recordVersion;
private String createdBy;
private LocalDateTime createdAt;
private String updatedBy;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,90 @@
package com.baiyue.lastleg.fleet.trip;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
/** Confirmed commercial facts only; delivery owns fee publication in its transaction. */
@Component
public class FleetBookingFreight {
private final FleetBookingMapper bookings;
private final FleetTripDispatchMapper bindings;
private final FleetBookingReservations reservations;
private final ObjectMapper json;
public FleetBookingFreight(FleetBookingMapper bookings, FleetTripDispatchMapper bindings,
FleetBookingReservations reservations, ObjectMapper json) {
this.bookings = bookings; this.bindings = bindings; this.reservations = reservations; this.json = json;
}
public record Quote(String bookingNo, long recordVersion, String incomingNo, String inboundCode,
String customerName, String destinationKey, String currency, BigDecimal amount,
BigDecimal quantity, String quantityUnit, BigDecimal unitPrice) { }
public record Preview(String snapshotHash, boolean requiresDeliveryFee, List<Quote> quotes,
@com.fasterxml.jackson.annotation.JsonIgnore List<String> priorInboundCodes) { }
/** Caller serializes transfer with the dispatch lock. Never lock the parent trip here. */
public Preview preview(long dispatchId, String dispatchNo, String customerId,
List<FleetDispatchGateway.SourceCargo> sources) {
var quotes = new ArrayList<Quote>();
var priorInboundCodes = new TreeSet<String>();
var grouped = new TreeMap<String, List<FleetDispatchGateway.SourceCargo>>();
boolean requiresFee = false;
for (var source : sources) {
if (source.inboundCode() == null || source.inboundCode().isBlank()) requiresFee = true;
else grouped.computeIfAbsent(source.inboundCode(), key -> new ArrayList<>()).add(source);
}
for (var entry : grouped.entrySet()) {
var booking = bookings.incomingForFreight(entry.getKey());
if (booking == null) { requiresFee = true; continue; }
if (!customerId.equals(booking.getCustomerId())) throw conflict("来货来源与排车客户不一致");
var accepted = reservations.receipt(booking);
if (accepted != null && accepted.source().inboundCode() != null && !accepted.source().inboundCode().isBlank())
priorInboundCodes.add(accepted.source().inboundCode());
if ("CANCELLED".equals(booking.getStatus())) { requiresFee = true; continue; }
var binding = bindings.findByDispatchNo(dispatchNo);
if (!"BOUND".equals(booking.getStatus()) || !customerId.equals(booking.getCustomerId())
|| !dispatchNo.equals(booking.getDispatchNo()) || binding == null
|| !Objects.equals(binding.getDispatchId(), dispatchId)
|| !Objects.equals(binding.getTripId(), booking.getTripId()))
throw conflict("外接货须先在承诺车次中完成实收确认和排车关联");
if (accepted == null) throw conflict("外接货缺少实收与报价确认");
if (accepted.source().inboundCode() == null || accepted.source().inboundCode().isBlank())
throw conflict("外接实收缺少实际入仓码,请先核对来货来源");
var actual = new TreeMap<String, Integer>();
for (var source : entry.getValue()) {
if (source.warehousePalletId() == null || !Objects.equals(booking.getDestinationKey(), source.destinationKey()))
throw conflict("外接发运来源或目的地已变化,请重新核对");
actual.merge(source.warehousePalletId(), source.packages(), Math::addExact);
}
var confirmed = new TreeMap<String, Integer>();
for (var pallet : accepted.source().pallets()) confirmed.merge(pallet.warehousePalletId(), pallet.packages(), Math::addExact);
if (!actual.equals(confirmed)) throw conflict("外接发运数量与已确认实收不一致");
var cargo = reservations.cargo(booking);
BigDecimal quantity = "PALLET".equals(cargo.priceBasis()) ? BigDecimal.valueOf(cargo.palletSpaces()) : BigDecimal.ONE;
if (booking.getAgreedAmount() == null || booking.getAgreedAmount().signum() < 0 || cargo.unitPrice() == null
|| quantity.multiply(cargo.unitPrice()).compareTo(booking.getAgreedAmount()) != 0)
throw conflict("外接约定运费与实收计价依据不一致");
if (!Set.of("CNY", "USD").contains(cargo.currency())) throw conflict("外接运费入账仅支持CNY或USD,请先更正约定币种");
quotes.add(new Quote(booking.getBookingNo(), booking.getRecordVersion(), booking.getIncomingNo(),
accepted.source().inboundCode(), booking.getCustomerName(), booking.getDestinationKey(), cargo.currency(),
booking.getAgreedAmount(), quantity, "PALLET".equals(cargo.priceBasis()) ? "托位" : "单", cargo.unitPrice()));
}
if (sources.isEmpty()) requiresFee = true;
try {
String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(
json.writeValueAsString(List.of(dispatchNo, customerId, sources.stream().sorted(Comparator
.comparing(FleetDispatchGateway.SourceCargo::inboundCode, Comparator.nullsFirst(String::compareTo))
.thenComparing(FleetDispatchGateway.SourceCargo::warehousePalletId, Comparator.nullsFirst(String::compareTo))
.thenComparing(FleetDispatchGateway.SourceCargo::destinationKey, Comparator.nullsFirst(String::compareTo))
.thenComparingInt(FleetDispatchGateway.SourceCargo::packages)).toList(), quotes)).getBytes(StandardCharsets.UTF_8)));
return new Preview(hash, requiresFee, List.copyOf(quotes), List.copyOf(priorInboundCodes));
} catch (java.security.NoSuchAlgorithmException | com.fasterxml.jackson.core.JsonProcessingException error) {
throw new IllegalStateException(error);
}
}
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
}
@@ -0,0 +1,17 @@
package com.baiyue.lastleg.fleet.trip;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/** The transfer slice owns coming-goods documents and physical receiving facts. */
public interface FleetBookingIncomingGateway {
record Incoming(String customerId,String warehouseId,String warehouseName,String bookingNo,FleetBookingModels.Cargo cargo,
LocalDateTime estimatedArrivalAt,String deliveryInstructions,String privateAddress,String postalCode,String recipientName,String recipientPhone) { }
record Pallet(String warehousePalletId,String palletNo,int packages,BigDecimal weightKg,BigDecimal volumeCbm) { }
record Evidence(String incomingNo,String inboundCode,String warehouseId,String destinationKey,String status,
String receiptHash,List<Pallet> pallets,int receivedPackages) { }
Evidence create(String operator, Incoming incoming);
Evidence inspect(String customerId,String incomingNo,boolean lock);
Evidence confirm(String customerId,String incomingNo,String operator,String key);
}
@@ -0,0 +1,19 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface FleetBookingMapper extends BaseMapper<FleetBookingEntity> {
@Select("SELECT * FROM ll_fleet_external_booking WHERE incoming_no=#{incomingNo} AND status <> 'CANCELLED'")
FleetBookingEntity incoming(@Param("incomingNo") String incomingNo);
@Select("SELECT * FROM ll_fleet_external_booking WHERE incoming_no=#{incomingNo}")
FleetBookingEntity incomingForFreight(@Param("incomingNo") String incomingNo);
@Select("SELECT * FROM ll_fleet_external_booking WHERE trip_id=#{tripId} ORDER BY id")
List<FleetBookingEntity> list(@Param("tripId") long tripId);
@Select("SELECT * FROM ll_fleet_external_booking WHERE trip_id=#{tripId} AND created_by=#{operator} AND idempotency_key=#{key}")
FleetBookingEntity created(@Param("tripId") long tripId,@Param("operator") String operator,@Param("key") String key);
@Select("SELECT * FROM ll_fleet_external_booking WHERE trip_id=#{tripId} AND booking_no=#{number} FOR UPDATE")
FleetBookingEntity lock(@Param("tripId") long tripId,@Param("number") String number);
}
@@ -0,0 +1,38 @@
package com.baiyue.lastleg.fleet.trip;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
public final class FleetBookingModels {
private FleetBookingModels() { }
public record Cargo(@NotBlank @Size(max=160) String destinationKey, @Size(max=255) String cargoName,
@Min(1) int packageCount, @Min(1) Integer palletSpaces, @DecimalMin("0.001") @Digits(integer=9, fraction=3) BigDecimal weightKg,
@DecimalMin("0.001") @Digits(integer=9, fraction=3) BigDecimal volumeCbm,
@Pattern(regexp="PALLET|ORDER") String priceBasis, @DecimalMin("0.00") @Digits(integer=10, fraction=2) BigDecimal unitPrice,
@Size(max=3) String currency, @Size(max=128) String contactName, @Size(max=128) String contactPhone, @Size(max=1000) String remark) { }
public record Create(@NotNull @Min(0) Long tripRecordVersion, @NotNull @Positive Long customerId,
@NotNull @Valid Cargo cargo, @NotBlank @Size(min=8,max=128) String idempotencyKey) { }
public record Update(@NotNull @Min(0) Long tripRecordVersion, @NotNull @Min(0) Long recordVersion, @NotNull @Valid Cargo cargo) { }
public record Command(@NotNull @Min(0) Long tripRecordVersion, @NotNull @Min(0) Long recordVersion,
@NotBlank @Size(min=8,max=128) String idempotencyKey, @Size(max=1000) String reason) { }
public record StartIncoming(@NotNull @Min(0) Long tripRecordVersion,@NotNull @Min(0) Long recordVersion,
Instant estimatedArrivalAt,@Size(max=1000) String deliveryInstructions,@Size(max=1000) String privateAddress,
@Size(max=32) String postalCode,@Size(max=128) String recipientName,@Size(max=64) String recipientPhone,
@NotBlank @Size(min=8,max=128) String idempotencyKey) { }
public record PalletSpaces(@NotBlank String warehousePalletId,@Min(1) int palletSpaces) { }
public record AcceptReceipt(@NotNull @Min(0) Long tripRecordVersion,@NotNull @Min(0) Long recordVersion,
@NotBlank String receiptHash,@NotEmpty List<@Valid PalletSpaces> pallets,
@NotNull @DecimalMin("0.00") @Digits(integer=10,fraction=2) BigDecimal unitPrice,
@NotBlank @Size(min=8,max=128) String idempotencyKey) { }
public record BindDispatch(@NotNull @Min(0) Long tripRecordVersion,@NotNull @Min(0) Long recordVersion,
@NotBlank @Size(max=64) String dispatchNo,@NotBlank @Size(min=8,max=128) String idempotencyKey) { }
public record IncomingPreview(long tripRecordVersion,long recordVersion,FleetBookingIncomingGateway.Evidence incoming) { }
public record AcceptedReceipt(FleetBookingIncomingGateway.Evidence source,List<PalletSpaces> pallets,String operatorId,Instant confirmedAt) { }
public record Response(String bookingNo, String tripNo, String customerId, String customerCode, String customerName,
String status, Cargo cargo, String destinationLabel, BigDecimal agreedAmount, long recordVersion, Instant updatedAt, String incomingNo, String dispatchNo, AcceptedReceipt receipt) { }
public record Result(long tripRecordVersion, Response booking, boolean replayed) { }
public record ListResult(long tripRecordVersion, List<Response> records) { }
}
@@ -0,0 +1,87 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.lastleg.fleet.domain.TripCapacityPolicy;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import java.time.ZoneOffset;
import java.util.*;
/** Read under the parent trip lock whenever changing reservations or capacity. */
@Component
public class FleetBookingReservations {
private final FleetBookingMapper bookings;
private final ObjectMapper json;
public FleetBookingReservations(FleetBookingMapper bookings, ObjectMapper json) { this.bookings=bookings; this.json=json; }
public boolean hasConfirmed(long tripId) { return bookings.list(tripId).stream().anyMatch(row -> unbound(row)); }
public List<FleetBookingModels.Response> responses(long tripId) { return bookings.list(tripId).stream().map(this::response).toList(); }
public FleetBookingModels.Cargo cargo(FleetBookingEntity row) { return read(row.getCargoJson(), FleetBookingModels.Cargo.class); }
public FleetBookingModels.Response response(FleetBookingEntity row) {
return new FleetBookingModels.Response(row.getBookingNo(),row.getTripNo(),row.getCustomerId(),row.getCustomerCode(),row.getCustomerName(),
row.getStatus(),cargo(row),row.getDestinationLabel(),row.getAgreedAmount(),row.getRecordVersion(),row.getUpdatedAt().toInstant(ZoneOffset.UTC),row.getIncomingNo(),row.getDispatchNo(),receipt(row));
}
public List<TripCapacityPolicy.Segment> segments(FleetTripEntity trip, FleetExecutionModels.PlannedLoad own,
Long excludedId, FleetBookingEntity addition) {
var stops=stops(trip); var loads=new ArrayList<TripCapacityPolicy.Booking>();
for (var pallet:own.pallets()) loads.add(new TripCapacityPolicy.Booking("PALLET:"+pallet.warehousePalletId(),0,pallet.deliveryIndex(),
new TripCapacityPolicy.Load(pallet.palletSpaces(),pallet.weightKg(),pallet.volumeCbm())));
for(var row:bookings.list(trip.getId())) if(unbound(row) && !Objects.equals(row.getId(),excludedId)) add(loads,stops,row);
if(addition!=null) add(loads,stops,addition);
try { return TripCapacityPolicy.calculate(stops.size(),new TripCapacityPolicy.Load(trip.getMaxPalletSpaces(),trip.getMaxLoadKg(),trip.getMaxVolumeCbm()),loads); }
catch(IllegalArgumentException|ArithmeticException error){throw conflict(error.getMessage());}
}
public void requireReassignmentFits(FleetTripEntity trip, Integer spaces, java.math.BigDecimal weight, java.math.BigDecimal volume) {
if(!hasConfirmed(trip.getId())) return;
if(trip.getPlannedLoadJson()==null) throw conflict("已有外接承运,请先重新核对计划容量再改派");
var own=read(trip.getPlannedLoadJson(),FleetExecutionModels.PlannedLoad.class);
for(var segment:segments(trip,own,null,null)) if(segment.occupied().palletSpaces()>spaces
||segment.occupied().weightKg().compareTo(weight)>0||segment.occupied().volumeCbm().compareTo(volume)>0)
throw conflict("替换车辆无法容纳自有货及已确认外接预订");
}
public FleetBookingModels.AcceptedReceipt receipt(FleetBookingEntity row){return row.getReceiptJson()==null?null:read(row.getReceiptJson(),FleetBookingModels.AcceptedReceipt.class);}
private static boolean unbound(FleetBookingEntity row){return Set.of("CONFIRMED","RECEIVED").contains(row.getStatus());}
public void bindIncoming(FleetTripEntity trip,FleetDispatchGateway.Snapshot dispatch,List<FleetDispatchGateway.SourceCargo> sources,String operator){
var bySource=sources.stream().filter(row->row.inboundCode()!=null).collect(java.util.stream.Collectors.groupingBy(FleetDispatchGateway.SourceCargo::inboundCode));
for(var entry:bySource.entrySet()){
var row=bookings.incoming(entry.getKey());if(row==null)continue;
if(!Objects.equals(row.getTripId(),trip.getId()))throw conflict("此外接货已承诺给其他车次,请先调整原预订");
if(!Objects.equals(row.getCustomerId(),dispatch.customerId())||!"RECEIVED".equals(row.getStatus()))throw conflict("外接货须先确认实收货量及运费,再关联排车");
var accepted=receipt(row);if(accepted==null)throw conflict("外接货缺少实收确认");
var expected=new TreeMap<String,Integer>();
for(var pallet:accepted.source().pallets())expected.merge(pallet.warehousePalletId(),pallet.packages(),Math::addExact);
var selected=new TreeMap<String,Integer>();
for(var item:entry.getValue()){
if(item.warehousePalletId()==null||!Objects.equals(item.destinationKey(),row.getDestinationKey()))throw conflict("排车货物托盘或目的地与外接实收不一致");
selected.merge(item.warehousePalletId(),item.packages(),Math::addExact);
}
if(!selected.equals(expected))throw conflict("当前排车未完整包含此外接预订的实收货物");
row.setStatus("BOUND");row.setDispatchNo(dispatch.dispatchNo());touch(row,operator);
}
}
public void unbindIncoming(FleetTripEntity trip,String dispatchNo,String operator){
for(var row:bookings.list(trip.getId()))if("BOUND".equals(row.getStatus())&&Objects.equals(row.getDispatchNo(),dispatchNo)){
row.setStatus("RECEIVED");row.setDispatchNo(null);touch(row,operator);
}
}
private void touch(FleetBookingEntity row,String operator){row.setRecordVersion(row.getRecordVersion()+1);row.setUpdatedBy(operator);row.setUpdatedAt(java.time.LocalDateTime.now(ZoneOffset.UTC));if(bookings.updateById(row)!=1)throw conflict("外接关联已变化");}
public void requireRoute(FleetTripEntity trip,List<FleetTripModels.Stop> stops) {
for(var row:bookings.list(trip.getId())) if((unbound(row)||"BOUND".equals(row.getStatus())) && index(stops,row.getDestinationKey())<1)
throw conflict("路线仍须包含已确认外接预订的卸货站");
}
private void add(List<TripCapacityPolicy.Booking> loads,List<FleetTripModels.Stop> stops,FleetBookingEntity row){
var cargo=cargo(row); int index=index(stops,row.getDestinationKey());
if(index<1) throw conflict("外接预订卸货站不在当前路线");
if(cargo.palletSpaces()==null||cargo.weightKg()==null||cargo.volumeCbm()==null) throw conflict("确认承运前请补齐预计托位、重量和体积");
try {loads.add(new TripCapacityPolicy.Booking(row.getBookingNo(),0,index,new TripCapacityPolicy.Load(cargo.palletSpaces(),cargo.weightKg(),cargo.volumeCbm())));}
catch(IllegalArgumentException error){throw conflict(error.getMessage());}
}
public List<FleetTripModels.Stop> stops(FleetTripEntity trip){
try{return json.readValue(trip.getStopsJson(),new TypeReference<>(){});}catch(JsonProcessingException error){throw new IllegalStateException(error);}
}
public static int index(List<FleetTripModels.Stop> stops,String key){for(int i=1;i<stops.size();i++)if(Objects.equals(stops.get(i).destinationKey(),key))return i;return -1;}
private <T>T read(String value,Class<T> type){try{return json.readValue(value,type);}catch(JsonProcessingException error){throw new IllegalStateException(error);}}
private static ResponseStatusException conflict(String reason){return new ResponseStatusException(HttpStatus.CONFLICT,reason);}
}
@@ -0,0 +1,175 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baiyue.lastleg.fleet.customer.FleetCustomerDirectory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Currency;
import java.util.HexFormat;
import java.util.Objects;
@Service
public class FleetBookingService {
private final FleetTripMapper trips;
private final FleetBookingMapper bookings;
private final FleetBookingReservations reservations;
private final FleetTripService history;
private final FleetTripExecutionService execution;
private final FleetCustomerDirectory customers;
private final ObjectMapper json;
private final FleetBookingIncomingGateway incoming;
public FleetBookingService(FleetTripMapper trips,FleetBookingMapper bookings,FleetBookingReservations reservations,
FleetTripService history,FleetTripExecutionService execution,FleetCustomerDirectory customers,ObjectMapper json,FleetBookingIncomingGateway incoming){
this.trips=trips;this.bookings=bookings;this.reservations=reservations;this.history=history;this.execution=execution;this.customers=customers;this.json=json;this.incoming=incoming;
}
@Transactional(readOnly=true,isolation=org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public FleetBookingModels.ListResult list(String tripNo){var trip=trip(tripNo,false);return new FleetBookingModels.ListResult(trip.getRecordVersion(),reservations.responses(trip.getId()));}
@Transactional
public FleetBookingModels.Result create(String tripNo,String operator,FleetBookingModels.Create request){
var trip=trip(tripNo,true);String hash=hash(request);
var existing=bookings.created(trip.getId(),operator,request.idempotencyKey());
if(existing!=null){if(!hash.equals(existing.getRequestHash()))throw conflict("同一登记请求不能变更客户或货物内容");return result(trip,existing,true);}
requireTrip(trip,request.tripRecordVersion());var customer=customers.required(request.customerId());
var row=new FleetBookingEntity();row.setId(IdWorker.getId());row.setBookingNo("FB-"+row.getId());row.setTripId(trip.getId());row.setTripNo(tripNo);
row.setCustomerId(customer.id());row.setCustomerCode(customer.code());row.setCustomerName(customer.name());row.setStatus("DRAFT");
apply(trip,row,request.cargo());row.setIdempotencyKey(request.idempotencyKey());row.setRequestHash(hash);row.setRecordVersion(0L);
row.setCreatedBy(operator);row.setCreatedAt(now());row.setUpdatedBy(operator);row.setUpdatedAt(row.getCreatedAt());
bookings.insert(row);history.recordExecution(trip,request.tripRecordVersion(),"BOOKING_CREATE","登记外接询价",operator);
return result(trip,row,false);
}
@Transactional
public FleetBookingModels.Result update(String tripNo,String bookingNo,String operator,FleetBookingModels.Update request){
var trip=trip(tripNo,true);requireTrip(trip,request.tripRecordVersion());var row=booking(trip,bookingNo);requireVersion(row,request.recordVersion());
if(!"DRAFT".equals(row.getStatus()))throw conflict("已确认承运的货物请先取消预订后重新登记,原记录保留");
apply(trip,row,request.cargo());save(trip,row,operator,"BOOKING_EDIT","更新外接询价");return result(trip,row,false);
}
@Transactional
public FleetBookingModels.Result confirm(String tripNo,String bookingNo,String operator,FleetBookingModels.Command request){
var trip=trip(tripNo,true);var row=booking(trip,bookingNo);String hash=hash(request);
if(Objects.equals(row.getConfirmKey(),request.idempotencyKey())){if(!hash.equals(row.getConfirmHash()))throw conflict("承运确认请求内容不一致");return result(trip,row,true);}
requireTrip(trip,request.tripRecordVersion());requireVersion(row,request.recordVersion());
if(!"DRAFT".equals(row.getStatus()))throw conflict("仅询价中的外接货可以确认承运");
customers.required(Long.parseLong(row.getCustomerId()));var cargo=reservations.cargo(row);
if(row.getAgreedAmount()==null||cargo.currency()==null)throw conflict("确认承运前请填写约定单价和币种");
if(!java.util.Set.of("CNY","USD").contains(cargo.currency()))throw conflict("首版运费入账支持CNY或USD,请调整约定币种");
var plan=execution.capacityPlan(tripNo);
if(!plan.planValid()||plan.blockReason()!=null)throw conflict("请先核对本车自有货计划容量,再确认外接承运");
reservations.segments(trip,plan.capacityPlan(),null,row);
row.setStatus("CONFIRMED");row.setConfirmKey(request.idempotencyKey());row.setConfirmHash(hash);
save(trip,row,operator,"BOOKING_CONFIRM",reason(request.reason(),"确认外接承运并预留容量"));return result(trip,row,false);
}
@Transactional
public FleetBookingModels.Result cancel(String tripNo,String bookingNo,String operator,FleetBookingModels.Command request){
var trip=trip(tripNo,true);var row=booking(trip,bookingNo);String hash=hash(request);
if(Objects.equals(row.getCancelKey(),request.idempotencyKey())){if(!hash.equals(row.getCancelHash()))throw conflict("取消请求内容不一致");return result(trip,row,true);}
requireTrip(trip,request.tripRecordVersion());requireVersion(row,request.recordVersion());
if(!java.util.Set.of("DRAFT","CONFIRMED","RECEIVED").contains(row.getStatus()))throw conflict("请先解除尚未开工的排车关联,再取消预订;已拣货须走现场撤回流程");
row.setStatus("CANCELLED");row.setCancelKey(request.idempotencyKey());row.setCancelHash(hash);
save(trip,row,operator,"BOOKING_CANCEL",reason(request.reason(),"取消未执行外接预订并释放容量"));return result(trip,row,false);
}
@Transactional(readOnly=true,isolation=org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public FleetBookingModels.IncomingPreview incoming(String tripNo,String bookingNo){
var trip=trip(tripNo,false);var row=bookings.list(trip.getId()).stream().filter(value->value.getBookingNo().equals(bookingNo)).findFirst()
.orElseThrow(()->new ResponseStatusException(HttpStatus.NOT_FOUND,"外接预订不存在"));
return new FleetBookingModels.IncomingPreview(trip.getRecordVersion(),row.getRecordVersion(),row.getIncomingNo()==null?null:incoming.inspect(row.getCustomerId(),row.getIncomingNo(),false));
}
@Transactional
public FleetBookingModels.Result startIncoming(String tripNo,String bookingNo,String operator,FleetBookingModels.StartIncoming request){
var trip=trip(tripNo,true);var row=booking(trip,bookingNo);String hash=hash(request);
if(Objects.equals(row.getIncomingKey(),request.idempotencyKey())){if(!hash.equals(row.getIncomingHash()))throw conflict("来货登记请求内容不一致");return result(trip,row,true);}
requireTrip(trip,request.tripRecordVersion());requireVersion(row,request.recordVersion());
if(!"CONFIRMED".equals(row.getStatus())||row.getIncomingNo()!=null)throw conflict("仅已确认且尚未登记来货的预订允许此操作");
customers.required(Long.parseLong(row.getCustomerId()));
var arrival=request.estimatedArrivalAt()==null?trip.getPlannedDepartureAt().toInstant(ZoneOffset.UTC).minusSeconds(7200):request.estimatedArrivalAt();
var evidence=incoming.create(operator,new FleetBookingIncomingGateway.Incoming(row.getCustomerId(),trip.getWarehouseId().toString(),trip.getWarehouseName(),row.getBookingNo(),reservations.cargo(row),
LocalDateTime.ofInstant(arrival,java.time.ZoneId.systemDefault()),request.deliveryInstructions(),request.privateAddress(),request.postalCode(),request.recipientName(),request.recipientPhone()));
requireEvidence(trip,row,evidence);
row.setIncomingNo(evidence.incomingNo());row.setIncomingKey(request.idempotencyKey());row.setIncomingHash(hash);
save(trip,row,operator,"BOOKING_INCOMING","登记外接来货 "+evidence.incomingNo());return result(trip,row,false);
}
@Transactional
public FleetBookingModels.Result acceptReceipt(String tripNo,String bookingNo,String operator,FleetBookingModels.AcceptReceipt request){
var trip=trip(tripNo,true);var row=booking(trip,bookingNo);String hash=hash(request);
if(Objects.equals(row.getReceiptKey(),request.idempotencyKey())){if(!hash.equals(row.getReceiptHash()))throw conflict("实收确认请求内容不一致");return result(trip,row,true);}
requireTrip(trip,request.tripRecordVersion());requireVersion(row,request.recordVersion());
if(!"CONFIRMED".equals(row.getStatus())||row.getIncomingNo()==null)throw conflict("请先登记来货并完成仓库实际收货");
var evidence=incoming.inspect(row.getCustomerId(),row.getIncomingNo(),true);requireEvidence(trip,row,evidence);
if(!java.util.Set.of("WAIT_CUSTOMER_CONFIRMATION","READY_FOR_DISPATCH").contains(evidence.status())||evidence.pallets().isEmpty())throw conflict("仓库尚未完成实收及测量");
if(!Objects.equals(evidence.receiptHash(),request.receiptHash()))throw conflict("实收数据已变化,请刷新后重新核对");
var spaces=new java.util.HashMap<String,Integer>();
for(var entry:request.pallets())if(entry.palletSpaces()<1||spaces.put(entry.warehousePalletId(),entry.palletSpaces())!=null)throw conflict("请为每个实际托盘填写一次占用托位");
var physical=evidence.pallets().stream().map(FleetBookingIncomingGateway.Pallet::warehousePalletId).collect(java.util.stream.Collectors.toSet());
if(!spaces.keySet().equals(physical)||physical.contains(null))throw conflict("托位确认须与实际收货托盘一致");
BigDecimal weight=BigDecimal.ZERO,volume=BigDecimal.ZERO;int count=0;
for(var pallet:evidence.pallets()){
if(pallet.packages()<=0||pallet.weightKg()==null||pallet.volumeCbm()==null||pallet.weightKg().signum()<=0||pallet.volumeCbm().signum()<=0)throw conflict("实际托盘缺少有效箱数、重量或体积");
weight=weight.add(pallet.weightKg());volume=volume.add(pallet.volumeCbm());count=Math.addExact(count,pallet.packages());
}
int totalSpaces=spaces.values().stream().reduce(0,Math::addExact);var old=reservations.cargo(row);
apply(trip,row,new FleetBookingModels.Cargo(old.destinationKey(),old.cargoName(),count,totalSpaces,weight,volume,old.priceBasis(),request.unitPrice(),old.currency(),old.contactName(),old.contactPhone(),old.remark()));
var plan=execution.capacityPlan(tripNo);
if(!plan.planValid()||plan.blockReason()!=null)throw conflict("请先重新核对自有货容量计划,再确认外接实收");
reservations.segments(trip,plan.capacityPlan(),row.getId(),row);
var confirmed=incoming.confirm(row.getCustomerId(),row.getIncomingNo(),operator,"FLEET:"+bookingNo+":RECEIPT");
if(!"READY_FOR_DISPATCH".equals(confirmed.status())||!Objects.equals(confirmed.receiptHash(),evidence.receiptHash()))throw conflict("来货实收确认未完成或内容发生变化,请重新核对");
row.setReceiptJson(write(new FleetBookingModels.AcceptedReceipt(confirmed,java.util.List.copyOf(request.pallets()),operator,java.time.Instant.now())));
row.setStatus("RECEIVED");row.setReceiptKey(request.idempotencyKey());row.setReceiptHash(hash);
save(trip,row,operator,"BOOKING_RECEIPT","确认外接实收货量及约定运费 "+row.getBookingNo());return result(trip,row,false);
}
@Transactional
public FleetBookingModels.Result bindDispatch(String tripNo,String bookingNo,String operator,FleetBookingModels.BindDispatch request){
var trip=trip(tripNo,true);var row=booking(trip,bookingNo);String hash=hash(request);
if(Objects.equals(row.getBindingKey(),request.idempotencyKey())){if(!hash.equals(row.getBindingHash()))throw conflict("关联发运请求内容不一致");return result(trip,row,true);}
requireTrip(trip,request.tripRecordVersion());requireVersion(row,request.recordVersion());
if(!"RECEIVED".equals(row.getStatus()))throw conflict("请先确认外接实收货量和运费");
row.setBindingKey(request.idempotencyKey());row.setBindingHash(hash);bookings.updateById(row);
var linked=history.bindDispatch(tripNo,operator,new FleetTripModels.BindingCommand(request.tripRecordVersion(),request.dispatchNo(),"关联外接预订 "+bookingNo));
var result=booking(trip,bookingNo);
if(!"BOUND".equals(result.getStatus())||!Objects.equals(result.getDispatchNo(),request.dispatchNo().trim()))throw conflict("所选排车未包含此外接来货单的实际货物");
return new FleetBookingModels.Result(linked.trip().recordVersion(),reservations.response(result),false);
}
private static void requireEvidence(FleetTripEntity trip,FleetBookingEntity row,FleetBookingIncomingGateway.Evidence evidence){
if(evidence==null||evidence.incomingNo()==null||!Objects.equals(trip.getWarehouseId().toString(),evidence.warehouseId())||!Objects.equals(row.getDestinationKey(),evidence.destinationKey()))throw conflict("来货单仓库或目的地与外接承运约定不一致");
if(row.getIncomingNo()!=null&&!Objects.equals(row.getIncomingNo(),evidence.incomingNo()))throw conflict("来货单引用不一致");
}
private void apply(FleetTripEntity trip,FleetBookingEntity row,FleetBookingModels.Cargo input){
var stops=reservations.stops(trip);int index=FleetBookingReservations.index(stops,input.destinationKey());
if(index<1)throw conflict("请选择本车已有卸货站,外接货首版从本起运仓装车");
String basis=input.priceBasis()==null?"PALLET":input.priceBasis();String currency=trim(input.currency());
if(!basis.equals("PALLET")&&!basis.equals("ORDER"))throw bad("请选择按托或整单报价");
if(currency!=null){currency=currency.toUpperCase(java.util.Locale.ROOT);try{Currency.getInstance(currency);}catch(IllegalArgumentException error){throw bad("币种无效");}}
var cargo=new FleetBookingModels.Cargo(input.destinationKey(),trim(input.cargoName()),input.packageCount(),input.palletSpaces(),input.weightKg(),input.volumeCbm(),
basis,input.unitPrice(),currency,trim(input.contactName()),trim(input.contactPhone()),trim(input.remark()));
row.setCargoJson(write(cargo));row.setDestinationKey(cargo.destinationKey());row.setDestinationLabel(stops.get(index).name());
BigDecimal amount=null;
if(input.unitPrice()!=null && (basis.equals("ORDER")||input.palletSpaces()!=null)) amount=input.unitPrice().multiply(BigDecimal.valueOf(basis.equals("ORDER")?1:input.palletSpaces())).setScale(2);
if(amount!=null && amount.precision()>16)throw bad("约定金额超出支持范围");
row.setAgreedAmount(amount);
}
private void save(FleetTripEntity trip,FleetBookingEntity row,String operator,String action,String reason){
row.setRecordVersion(row.getRecordVersion()+1);row.setUpdatedBy(operator);row.setUpdatedAt(now());
if(bookings.updateById(row)!=1)throw conflict("外接预订已变化,请刷新");
history.recordExecution(trip,trip.getRecordVersion(),action,reason,operator);
}
private FleetBookingModels.Result result(FleetTripEntity trip,FleetBookingEntity row,boolean replayed){return new FleetBookingModels.Result(trip.getRecordVersion(),reservations.response(row),replayed);}
private FleetTripEntity trip(String number,boolean lock){var value=lock?trips.lockByNo(number):trips.findByNo(number);if(value==null)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"车次不存在");return value;}
private FleetBookingEntity booking(FleetTripEntity trip,String number){var row=bookings.lock(trip.getId(),number);if(row==null)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"当前车次无此外接预订");return row;}
private static void requireTrip(FleetTripEntity trip,long version){if(!"PLANNED".equals(trip.getStatus()))throw conflict("仅计划中的车次允许管理外接预订");if(trip.getRecordVersion()!=version)throw conflict("车次已被修改,请刷新");}
private static void requireVersion(FleetBookingEntity row,long version){if(row.getRecordVersion()!=version)throw conflict("外接预订已被修改,请刷新");}
private String write(Object value){try{return json.writeValueAsString(value);}catch(Exception error){throw new IllegalStateException(error);}}
private String hash(Object value){try{ObjectNode node=json.valueToTree(value);node.remove("idempotencyKey");node.remove("tripRecordVersion");return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(write(node).getBytes(StandardCharsets.UTF_8)));}catch(Exception error){throw new IllegalStateException(error);}}
private static LocalDateTime now(){return LocalDateTime.now(ZoneOffset.UTC);}
private static String trim(String value){return value==null||value.isBlank()?null:value.trim();}
private static String reason(String value,String fallback){return trim(value)==null?fallback:trim(value);}
private static ResponseStatusException conflict(String value){return new ResponseStatusException(HttpStatus.CONFLICT,value);}
private static ResponseStatusException bad(String value){return new ResponseStatusException(HttpStatus.BAD_REQUEST,value);}
}
@@ -0,0 +1,24 @@
package com.baiyue.lastleg.fleet.trip;
import jakarta.validation.constraints.*;
import java.time.Instant;
import java.util.List;
public final class FleetCompletionModels {
private FleetCompletionModels() { }
public record Outcome(String dispatchNo, String deliveryNo, String customerId, String destination,
String status, int packages, Instant terminalAt) { }
public record DispatchCompletion(String dispatchNo, String warehouseId, List<Outcome> outcomes, String blockReason) { }
public record Inspection(String tripNo, long recordVersion, boolean canComplete, String blockReason, List<Outcome> outcomes) { }
public record Complete(@NotNull @Min(0) Long recordVersion, @NotBlank @Size(min = 8, max = 128) String idempotencyKey,
@NotBlank @Size(max = 1000) String reason) { }
public record Completed(String idempotencyKey, String requestHash, Instant completedAt, Instant recordedAt,
String operatorId, List<Outcome> outcomes) { }
public record Release(@NotNull @Min(0) Long recordVersion, @NotBlank @Pattern(regexp = "VEHICLE|DRIVER") String resourceKind,
@NotNull @PastOrPresent Instant actualEndAt, @NotBlank @Size(max = 500) String endLocation,
@Pattern(regexp = "IN_SERVICE|MAINTENANCE|INACTIVE|RETURNED") String vehicleStatus,
@NotBlank @Size(min = 8, max = 128) String idempotencyKey, @NotBlank @Size(max = 1000) String reason) { }
public record Released(String idempotencyKey, String requestHash, Instant actualEndAt, String endLocation,
String vehicleStatus, String operatorId, Instant recordedAt) { }
public record ReleaseInfo(Instant actualEndAt, String endLocation, String vehicleStatus) { }
}
@@ -0,0 +1,50 @@
package com.baiyue.lastleg.fleet.trip;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
@Service
public class FleetDispatchBindingGuard {
private final FleetTripDispatchMapper bindings;
private final com.fasterxml.jackson.databind.ObjectMapper json;
public FleetDispatchBindingGuard(FleetTripDispatchMapper bindings, com.fasterxml.jackson.databind.ObjectMapper json) { this.bindings = bindings; this.json = json; }
/** Dispatch -> task -> binding locks; never acquire the parent trip lock from a PDA pick. */
@Transactional(propagation = Propagation.MANDATORY)
public void requirePickingApproved(long dispatchId) {
var binding = bindings.lockByDispatch(dispatchId);
if (binding == null) throw new ResponseStatusException(HttpStatus.CONFLICT, "请先关联车次并通过调度审核");
var review = FleetTripReview.read(json, binding.getReviewJson());
if (!"APPROVED".equals(review.status())) throw new ResponseStatusException(HttpStatus.CONFLICT,
"REJECTED".equals(review.status()) ? "调度审核已打回:" + review.reason() : "请先通过调度审核再拣货");
}
@Transactional(propagation = Propagation.MANDATORY)
public void requireMatchingAssignment(long dispatchId, FleetDispatchGateway.Assignment actual, FleetDispatchGateway.Assignment requested) {
var binding = bindings.lockByDispatch(dispatchId);
if (binding != null && (changed(requested.vehiclePlate(), actual.vehiclePlate()) || changed(requested.driverName(), actual.driverName())
|| changed(requested.driverPhone(), actual.driverPhone())))
throw new ResponseStatusException(HttpStatus.CONFLICT, "车辆和司机由车次 " + binding.getTripNo() + " 统一维护");
}
private static boolean changed(String requested, String actual) {
return requested != null && !requested.isBlank() && !requested.trim().equals(actual);
}
/** Must be called after locking the customer dispatch, which serializes binding and mutations. */
@Transactional(propagation = Propagation.MANDATORY)
public void requireUnbound(long dispatchId) {
var binding = bindings.lockByDispatch(dispatchId);
if (binding != null) throw new ResponseStatusException(HttpStatus.CONFLICT,
"排车单已关联车次 " + binding.getTripNo() + ",请先在车次中解除关联");
}
@Transactional(propagation = Propagation.MANDATORY)
public void requireCoordinatedDeparture(long dispatchId) {
var binding = bindings.lockByDispatch(dispatchId);
if (binding == null || !"DEPARTING".equals(bindings.tripStatus(dispatchId)))
throw new ResponseStatusException(HttpStatus.CONFLICT, "请通过车次统一发车");
}
}
@@ -0,0 +1,30 @@
package com.baiyue.lastleg.fleet.trip;
import java.time.Instant;
/** Customer dispatches remain owned by dispatch; fleet only orchestrates their physical trip. */
public interface FleetDispatchGateway {
record Snapshot(long dispatchId, String dispatchNo, String customerId, String warehouseId, int packageCount) { }
record SourceCargo(String inboundCode,String warehousePalletId,String palletNo,int packages,String destinationKey) { }
java.util.List<SourceCargo> sourceCargo(String dispatchNo);
record Assignment(String vehiclePlate, String driverName, String driverPhone) { }
static String destinationKey(String type,String code,String fba,String address,String postalCode) {
if(!"PRIVATE".equals(type)){String value=code==null||code.isBlank()?fba:code;return value==null||value.isBlank()?null:"FBA:"+value.trim().toUpperCase(java.util.Locale.ROOT);}
if(address==null||address.isBlank())return null;
String key=address.strip().replaceAll("\\s+"," ").toUpperCase(java.util.Locale.ROOT)+"|"+java.util.Objects.requireNonNullElse(postalCode,"").strip().toUpperCase(java.util.Locale.ROOT);
try{return "PRIVATE:"+java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(key.getBytes(java.nio.charset.StandardCharsets.UTF_8)));}
catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}
}
/** Locks the dispatch and rejects any picking or departure already performed. */
Snapshot lockForPlanning(String dispatchNo);
/** Allows pre-departure resource/time changes without changing cargo or recorded picking. */
Snapshot lockForAssignment(String dispatchNo);
/** Caller holds the dispatch lock for the entire transaction, including downstream snapshots. */
void assign(Snapshot dispatch, Assignment assignment);
FleetExecutionModels.Manifest manifest(String dispatchNo, boolean lock);
FleetCompletionModels.DispatchCompletion completion(String dispatchNo, boolean lock);
FleetExecutionModels.DepartedDispatch depart(String warehouseId, String dispatchNo, String operator,
String idempotencyKey, String remark, Instant departedAt);
}
@@ -0,0 +1,42 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.lastleg.fleet.domain.TripCapacityPolicy;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
public final class FleetExecutionModels {
private FleetExecutionModels() { }
public record Cargo(String dispatchNo, String customerId, String dispatchItemId, String warehousePalletId,
String palletNo, int packages, String destinationKey, String destinationLabel) { }
public record Manifest(String dispatchNo, String warehouseId, String vehiclePlate, String driverName, String driverPhone,
List<Cargo> cargo, String blockReason) { }
public record Measurement(@NotBlank String warehousePalletId, @Min(1) int palletSpaces,
@NotNull @DecimalMin("0.001") @Digits(integer = 9, fraction = 3) BigDecimal weightKg,
@NotNull @DecimalMin("0.001") @Digits(integer = 9, fraction = 3) BigDecimal volumeCbm,
@Min(1) int deliveryIndex) { }
public record Confirm(@NotNull @Min(0) Long recordVersion, @NotBlank @Pattern(regexp = "[0-9a-f]{64}") String manifestHash,
@NotEmpty @Size(max = 1000) List<@NotNull @Valid Measurement> pallets,
@NotBlank @Size(max = 1000) String reason) { }
public record ConfirmedLoad(String manifestHash, List<Cargo> cargo, List<Measurement> pallets,
List<TripCapacityPolicy.Segment> segments, String operatorId, Instant confirmedAt) { }
public record Loading(String tripNo, long recordVersion, List<Cargo> cargo, String manifestHash,
ConfirmedLoad confirmedLoad, String blockReason) { }
public record PlannedLoad(String manifestHash, List<Cargo> cargo, List<Measurement> pallets,
List<TripCapacityPolicy.Segment> segments, String operatorId, Instant confirmedAt) { }
public record Planning(String tripNo, long recordVersion, List<Cargo> cargo, String manifestHash,
PlannedLoad capacityPlan, boolean planValid, String blockReason, List<TripCapacityPolicy.Segment> availableSegments) { }
public record Depart(@NotNull @Min(0) Long recordVersion, @NotBlank @Size(min = 8, max = 128) String idempotencyKey,
@Size(max = 1000) String remark) { }
public record DepartedDispatch(String dispatchNo, long shippedPackages) { }
public record Departed(String tripNo, String status, Instant departedAt, long shippedPackages,
List<DepartedDispatch> dispatches, boolean replayed) {
public Departed withReplay() { return new Departed(tripNo, status, departedAt, shippedPackages, dispatches, true); }
}
public record Gate(String tripNo, Long recordVersion, int dispatchCount, boolean canDepart, String blockReason, String driverWarning,
boolean canPick, String pickBlockReason) {
public Gate withPicking(boolean allowed, String reason) { return new Gate(tripNo, recordVersion, dispatchCount, canDepart, blockReason, driverWarning, allowed, reason); }
}
}
@@ -0,0 +1,17 @@
package com.baiyue.lastleg.fleet.trip;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface FleetResourceMapper {
@Select("SELECT resource_kind,resource_id,trip_id,trip_no FROM ll_fleet_resource_assignment WHERE resource_kind=#{kind} AND resource_id=#{id}")
Assignment find(@Param("kind") String kind, @Param("id") long id);
@Select("SELECT resource_kind,resource_id,trip_id,trip_no FROM ll_fleet_resource_assignment WHERE trip_id=#{tripId} ORDER BY resource_kind,resource_id")
List<Assignment> byTrip(@Param("tripId") long tripId);
@Insert("INSERT INTO ll_fleet_resource_assignment(resource_kind,resource_id,trip_id,trip_no) VALUES(#{kind},#{id},#{tripId},#{tripNo})")
int reserve(@Param("kind") String kind, @Param("id") long id, @Param("tripId") long tripId, @Param("tripNo") String tripNo);
@Delete("DELETE FROM ll_fleet_resource_assignment WHERE resource_kind=#{kind} AND resource_id=#{id} AND trip_id=#{tripId}")
int release(@Param("kind") String kind, @Param("id") long id, @Param("tripId") long tripId);
record Assignment(String resourceKind, long resourceId, long tripId, String tripNo) { }
}
@@ -0,0 +1,144 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.lastleg.masterdata.vehicle.application.VehicleApplicationService;
import com.baiyue.lastleg.masterdata.vehicle.application.model.VehicleModels;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HexFormat;
import java.util.List;
import java.util.Set;
@Service
public class FleetTripCompletionService {
private final FleetTripMapper trips;
private final FleetTripDispatchMapper bindings;
private final FleetResourceMapper resources;
private final FleetDispatchGateway dispatches;
private final FleetTripService history;
private final VehicleRepository vehicles;
private final VehicleApplicationService vehicleService;
private final ObjectMapper json;
public FleetTripCompletionService(FleetTripMapper trips, FleetTripDispatchMapper bindings, FleetResourceMapper resources,
FleetDispatchGateway dispatches, FleetTripService history, VehicleRepository vehicles,
VehicleApplicationService vehicleService, ObjectMapper json) {
this.trips = trips; this.bindings = bindings; this.resources = resources; this.dispatches = dispatches;
this.history = history; this.vehicles = vehicles; this.vehicleService = vehicleService; this.json = json;
}
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public FleetCompletionModels.Inspection inspection(String tripNo) { return inspect(required(tripNo, false), false); }
@Transactional
public FleetTripModels.Detail complete(String tripNo, String operator, FleetCompletionModels.Complete request) {
var trip = required(tripNo, true);
String hash = hash(write(request));
if (trip.getCompletionJson() != null) {
var prior = read(trip.getCompletionJson(), FleetCompletionModels.Completed.class);
if (!prior.idempotencyKey().equals(request.idempotencyKey()) || !prior.requestHash().equals(hash))
throw conflict("车次已结案,请核对原结案请求");
return history.detail(tripNo);
}
requireVersion(trip, request.recordVersion());
var inspection = inspect(trip, true);
if (!inspection.canComplete()) throw conflict(inspection.blockReason());
Instant completedAt = inspection.outcomes().stream().map(FleetCompletionModels.Outcome::terminalAt).max(Instant::compareTo).orElseThrow();
trip.setStatus("COMPLETED"); trip.setCompletedAt(LocalDateTime.ofInstant(completedAt, ZoneOffset.UTC));
trip.setCompletionJson(write(new FleetCompletionModels.Completed(request.idempotencyKey(), hash, completedAt, Instant.now(), operator, inspection.outcomes())));
// Completion freezes cargo outcomes. It deliberately does not release a driver still returning.
history.recordExecution(trip, request.recordVersion(), "COMPLETE", request.reason(), operator);
return history.detail(tripNo);
}
@Transactional
public FleetTripModels.Detail release(String tripNo, String operator, FleetCompletionModels.Release request) {
var trip = required(tripNo, true);
if (!Set.of("VEHICLE", "DRIVER").contains(request.resourceKind())) throw bad("请选择车辆或司机任务");
boolean vehicle = "VEHICLE".equals(request.resourceKind());
String previous = vehicle ? trip.getVehicleReleaseJson() : trip.getDriverReleaseJson();
String hash = hash(write(request));
if (previous != null) {
var released = read(previous, FleetCompletionModels.Released.class);
if (!released.idempotencyKey().equals(request.idempotencyKey()) || !released.requestHash().equals(hash))
throw conflict("该资源任务已结束,请核对原结束请求");
return history.detail(tripNo);
}
requireVersion(trip, request.recordVersion());
if (!"COMPLETED".equals(trip.getStatus()) || trip.getCompletionJson() == null || trip.getCompletedAt() == null)
throw conflict("请先核对全部货物并完成车次结案");
Instant now = Instant.now();
if (request.actualEndAt() == null || request.actualEndAt().isAfter(now)
|| request.actualEndAt().isBefore(trip.getCompletedAt().toInstant(ZoneOffset.UTC))) throw bad("实际任务结束时间须不早于本车货物履约完成且不晚于当前时间");
if (request.endLocation() == null || request.endLocation().isBlank()) throw bad("请填写实际任务结束地点");
if (vehicle && (request.vehicleStatus() == null || !Set.of("IN_SERVICE", "MAINTENANCE", "INACTIVE", "RETURNED").contains(request.vehicleStatus())))
throw bad("请确认车辆结束任务后的实际状态");
if (!vehicle && request.vehicleStatus() != null) throw bad("结束司机任务不能修改车辆状态");
if (vehicle) {
var current = vehicles.lockById(trip.getVehicleId()).orElseThrow(() -> conflict("车辆档案不存在"));
requireRelease("VEHICLE", trip.getVehicleId(), trip.getId());
vehicleService.changeStatus(trip.getVehicleId(), operator, new VehicleModels.ChangeStatus(request.vehicleStatus(), current.recordVersion()));
} else {
// A now-expired or disabled driver may end their task; this never re-enables their qualification.
requireRelease("DRIVER", trip.getDriverId(), trip.getId());
}
var released = new FleetCompletionModels.Released(request.idempotencyKey(), hash, request.actualEndAt(),
request.endLocation().trim(), request.vehicleStatus(), operator, now);
if (vehicle) trip.setVehicleReleaseJson(write(released)); else trip.setDriverReleaseJson(write(released));
history.recordExecution(trip, request.recordVersion(), vehicle ? "RELEASE_VEHICLE" : "RELEASE_DRIVER", request.reason(), operator);
return history.detail(tripNo);
}
private FleetCompletionModels.Inspection inspect(FleetTripEntity trip, boolean lock) {
if (trip.getCompletionJson() != null) {
var prior = read(trip.getCompletionJson(), FleetCompletionModels.Completed.class);
return new FleetCompletionModels.Inspection(trip.getTripNo(), trip.getRecordVersion(), false, "车次货物已结案", prior.outcomes());
}
var completions = bindings.listByTrip(trip.getId()).stream().map(binding -> dispatches.completion(binding.getDispatchNo(), lock)).toList();
var outcomes = completions.stream().flatMap(completion -> completion.outcomes().stream()).toList();
String reason = null;
if (!"IN_TRANSIT".equals(trip.getStatus()) || trip.getDepartedAt() == null) reason = "仅已发车的车次可以结案";
else if (completions.isEmpty()) reason = "缺少客户执行单据,不能结案";
else {
for (var completion : completions) {
if (!trip.getWarehouseId().toString().equals(completion.warehouseId())) { reason = "客户执行单据起运仓与车次不一致"; break; }
if (completion.blockReason() != null) { reason = completion.dispatchNo() + ":" + completion.blockReason(); break; }
}
Instant departure = trip.getDepartedAt().toInstant(ZoneOffset.UTC), now = Instant.now();
if (reason == null && outcomes.stream().anyMatch(outcome -> outcome.terminalAt() == null
|| outcome.terminalAt().isBefore(departure) || outcome.terminalAt().isAfter(now))) reason = "签收或退回时间须在发车之后且不晚于当前时间,请核对原单";
}
return new FleetCompletionModels.Inspection(trip.getTripNo(), trip.getRecordVersion(), reason == null, reason, outcomes);
}
private void requireRelease(String kind, Long resourceId, long tripId) {
if (resourceId == null || resources.release(kind, resourceId, tripId) != 1) throw conflict("资源占用与车次不一致,结束任务未完成");
}
private FleetTripEntity required(String tripNo, boolean lock) {
var trip = lock ? trips.lockByNo(tripNo) : trips.findByNo(tripNo);
if (trip == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "车次不存在");
return trip;
}
private static void requireVersion(FleetTripEntity trip, long version) {
if (trip.getRecordVersion() != version) throw conflict("车次已被修改,请刷新后重试");
}
private String write(Object value) { try { return json.writeValueAsString(value); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } }
private <T> T read(String value, Class<T> type) { try { return json.readValue(value, type); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } }
private static String hash(String value) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); }
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
private static ResponseStatusException bad(String message) { return new ResponseStatusException(HttpStatus.BAD_REQUEST, message); }
}
@@ -0,0 +1,23 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("ll_fleet_trip_dispatch")
public class FleetTripDispatch {
@TableId(type = IdType.INPUT)
private Long dispatchId;
private String dispatchNo;
private String customerId;
private Long tripId;
private String tripNo;
private Integer packageCount;
private String boundBy;
private LocalDateTime boundAt;
@com.baomidou.mybatisplus.annotation.TableField(updateStrategy = com.baomidou.mybatisplus.annotation.FieldStrategy.ALWAYS)
private String reviewJson;
}
@@ -0,0 +1,22 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface FleetTripDispatchMapper extends BaseMapper<FleetTripDispatch> {
@Select("SELECT * FROM ll_fleet_trip_dispatch WHERE trip_id=#{tripId} ORDER BY dispatch_id")
List<FleetTripDispatch> listByTrip(@Param("tripId") long tripId);
@Select("SELECT * FROM ll_fleet_trip_dispatch WHERE dispatch_no=#{dispatchNo}")
FleetTripDispatch findByDispatchNo(@Param("dispatchNo") String dispatchNo);
@Select("<script>SELECT * FROM ll_fleet_trip_dispatch WHERE dispatch_no IN <foreach collection='numbers' item='number' open='(' separator=',' close=')'>#{number}</foreach></script>")
List<FleetTripDispatch> findByDispatchNos(@Param("numbers") List<String> numbers);
// Locking read sees a concurrent binding committed while the caller waited for the dispatch row.
@Select("SELECT * FROM ll_fleet_trip_dispatch WHERE dispatch_id=#{dispatchId} FOR UPDATE")
FleetTripDispatch lockByDispatch(@Param("dispatchId") long dispatchId);
@Select("SELECT t.status FROM ll_fleet_trip_dispatch b JOIN ll_fleet_trip t ON t.id=b.trip_id WHERE b.dispatch_id=#{dispatchId}")
String tripStatus(@Param("dispatchId") long dispatchId);
}
@@ -0,0 +1,53 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@TableName("ll_fleet_trip")
public class FleetTripEntity {
@TableId(type = IdType.INPUT) private Long id;
private String tripNo;
private String idempotencyKey;
private String requestHash;
private String status;
private Long warehouseId;
private String warehouseCode;
private String warehouseName;
private Long vehicleId;
private String vehiclePlate;
private Long driverId;
private String driverName;
private String driverPhone;
private Integer maxPalletSpaces;
private BigDecimal maxLoadKg;
private BigDecimal maxVolumeCbm;
private LocalDateTime plannedDepartureAt;
private LocalDateTime expectedDriverEndAt;
private LocalDateTime departedAt;
private LocalDateTime completedAt;
private String stopsJson;
@com.baomidou.mybatisplus.annotation.TableField(updateStrategy = com.baomidou.mybatisplus.annotation.FieldStrategy.ALWAYS)
private String plannedLoadJson;
@com.baomidou.mybatisplus.annotation.TableField(updateStrategy = com.baomidou.mybatisplus.annotation.FieldStrategy.ALWAYS)
private String loadJson;
@com.baomidou.mybatisplus.annotation.TableField(updateStrategy = com.baomidou.mybatisplus.annotation.FieldStrategy.ALWAYS)
private String loadingReviewJson;
private String departureKey;
private String departureHash;
private String departureResultJson;
private String completionJson;
private String vehicleReleaseJson;
private String driverReleaseJson;
@com.baomidou.mybatisplus.annotation.TableField(updateStrategy = com.baomidou.mybatisplus.annotation.FieldStrategy.ALWAYS)
private String remark;
private Long recordVersion;
private String createdBy;
private LocalDateTime createdAt;
private String updatedBy;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,318 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.lastleg.fleet.domain.TripCapacityPolicy;
import com.baiyue.lastleg.fleet.driver.DriverModels;
import com.baiyue.lastleg.fleet.driver.DriverService;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
@Service
public class FleetTripExecutionService {
private final FleetTripMapper trips;
private final FleetTripDispatchMapper bindings;
private final FleetResourceMapper resources;
private final FleetDispatchGateway dispatches;
private final FleetTripService history;
private final DriverService drivers;
private final VehicleRepository vehicles;
private final ObjectMapper json;
private final FleetBookingReservations bookingReservations;
public FleetTripExecutionService(FleetTripMapper trips, FleetTripDispatchMapper bindings, FleetResourceMapper resources,
FleetDispatchGateway dispatches, FleetTripService history, DriverService drivers,
VehicleRepository vehicles, ObjectMapper json, FleetBookingReservations bookingReservations) {
this.trips = trips; this.bindings = bindings; this.resources = resources; this.dispatches = dispatches;
this.history = history; this.drivers = drivers; this.vehicles = vehicles; this.json = json; this.bookingReservations = bookingReservations;
}
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public FleetExecutionModels.Planning capacityPlan(String tripNo) {
var trip = requireTrip(tripNo, false);
var cargo = cargo(manifests(trip, false));
return planning(trip, cargo);
}
@Transactional
public FleetExecutionModels.Planning confirmCapacityPlan(String tripNo, String operator, FleetExecutionModels.Confirm request) {
var trip = requireTrip(tripNo, true);
requireVersionAndPlan(trip, request.recordVersion());
var cargo = cargo(manifests(trip, true));
String reason = planningBlockReason(trip, cargo);
if (reason != null) throw conflict(reason);
String fingerprint = hash(write(cargo));
if (!fingerprint.equals(request.manifestHash())) throw conflict("货物明细已变化,请刷新后重新核对计划容量");
var pallets = request.pallets().stream().sorted(Comparator.comparing(FleetExecutionModels.Measurement::warehousePalletId)).toList();
var plan = new FleetExecutionModels.PlannedLoad(fingerprint, cargo, pallets, capacity(trip, cargo, pallets), operator, Instant.now());
bookingReservations.segments(trip, plan, null, null);
trip.setPlannedLoadJson(write(plan));
history.recordExecution(trip, request.recordVersion(), "PLAN_CAPACITY", request.reason(), operator);
return planning(trip, cargo);
}
private FleetExecutionModels.Planning planning(FleetTripEntity trip, List<FleetExecutionModels.Cargo> cargo) {
String fingerprint = hash(write(cargo));
var plan = trip.getPlannedLoadJson() == null ? null : read(trip.getPlannedLoadJson(), FleetExecutionModels.PlannedLoad.class);
boolean valid = plan != null && plan.manifestHash().equals(fingerprint);
return new FleetExecutionModels.Planning(trip.getTripNo(), trip.getRecordVersion(), cargo, fingerprint, plan, valid, planningBlockReason(trip, cargo), valid ? bookingReservations.segments(trip, plan, null, null) : List.of());
}
private String planningBlockReason(FleetTripEntity trip, List<FleetExecutionModels.Cargo> cargo) {
if (!"PLANNED".equals(trip.getStatus())) return "仅计划中的车次允许核对计划容量";
if (trip.getVehicleId() == null) return "请先分配车辆,明确可用托位、载重和容积";
if (cargo.isEmpty()) return "请先关联本车自有货排车单";
if (cargo.stream().anyMatch(row -> row.warehousePalletId() == null || row.destinationKey() == null))
return "请先明确每票货物的实物托盘和卸货目的地";
return null;
}
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public FleetExecutionModels.Loading loading(String tripNo) {
var trip = requireTrip(tripNo, false);
var manifest = manifests(trip, false);
var cargo = cargo(manifest);
return new FleetExecutionModels.Loading(tripNo, trip.getRecordVersion(), cargo, hash(write(cargo)), load(trip), blockReason(trip, manifest));
}
@Transactional
public FleetExecutionModels.Loading confirmLoad(String tripNo, String operator, FleetExecutionModels.Confirm request) {
var trip = requireTrip(tripNo, true);
requireVersionAndPlan(trip, request.recordVersion());
var manifest = manifests(trip, true);
String block = blockReason(trip, manifest);
if (block != null) throw conflict(block);
var cargo = cargo(manifest); String fingerprint = hash(write(cargo));
if (!fingerprint.equals(request.manifestHash())) throw conflict("货物明细已变化,请刷新后重新核对装载");
var pallets = request.pallets().stream().sorted(Comparator.comparing(FleetExecutionModels.Measurement::warehousePalletId)).toList();
var segments = capacity(trip, cargo, pallets);
var confirmed = new FleetExecutionModels.ConfirmedLoad(fingerprint, cargo, pallets, segments, operator, Instant.now());
trip.setLoadJson(write(confirmed));
history.recordExecution(trip, request.recordVersion(), "CONFIRM_LOAD", request.reason(), operator);
return new FleetExecutionModels.Loading(tripNo, trip.getRecordVersion(), cargo, fingerprint, confirmed, null);
}
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public FleetExecutionModels.Gate gate(String warehouseId, String dispatchNo) {
var binding = bindings.findByDispatchNo(dispatchNo);
if (binding == null) return missingGate();
return pickingGate(gateForTrip(warehouseId, binding.getTripNo()), binding);
}
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public Map<String, FleetExecutionModels.Gate> gates(String warehouseId, List<String> numbers) {
if (numbers.isEmpty()) return Map.of();
var result = new HashMap<String, FleetExecutionModels.Gate>();
numbers.forEach(number -> result.put(number, missingGate()));
var byTrip = new HashMap<String, FleetExecutionModels.Gate>();
for (var binding : bindings.findByDispatchNos(numbers)) result.put(binding.getDispatchNo(), pickingGate(
byTrip.computeIfAbsent(binding.getTripNo(), number -> gateForTrip(warehouseId, number)), binding));
return result;
}
private FleetExecutionModels.Gate gateForTrip(String warehouseId, String tripNo) {
var trip = requireTrip(tripNo, false);
requireWarehouse(trip, warehouseId);
var manifest = manifests(trip, false);
String reason = blockReason(trip, manifest);
String warning = null;
if (reason == null) reason = loadBlockReason(trip, cargo(manifest));
if (reason == null) reason = loadingReviewBlockReason(trip);
if (reason == null) {
var driver = drivers.detail(trip.getDriverId(), trip.getExpectedDriverEndAt().toInstant(ZoneOffset.UTC));
if (!driver.qualification().canDispatch()) reason = "司机资格不满足本次任务,请在平台核对";
else reason = driverBlockReason(trip, driver);
if (reason == null && driver.qualification().expiringSoon()) warning = "司机驾驶证将于 " + driver.qualification().licenseExpiresOn() + " 到期;有效期覆盖本次预计任务,请留意延期风险";
}
boolean canPick = "PLANNED".equals(trip.getStatus()) && trip.getVehicleId() != null && trip.getDriverId() != null;
return new FleetExecutionModels.Gate(trip.getTripNo(), trip.getRecordVersion(), manifest.size(), reason == null, reason, warning,
canPick, canPick ? null : "当前车次不允许继续拣货");
}
private static FleetExecutionModels.Gate missingGate() {
return new FleetExecutionModels.Gate(null, null, 0, false, "请先在平台将排车单关联车次", null, false, "请先关联车次并通过调度审核");
}
private FleetExecutionModels.Gate pickingGate(FleetExecutionModels.Gate gate, FleetTripDispatch binding) {
if (!gate.canPick()) return gate;
var review = FleetTripReview.read(json, binding.getReviewJson());
String reason = "APPROVED".equals(review.status()) ? null : "REJECTED".equals(review.status())
? "调度审核已打回:" + review.reason() : "请先通过调度审核再拣货";
return gate.withPicking(reason == null, reason);
}
private String loadingReviewBlockReason(FleetTripEntity trip) {
var review = FleetTripReview.read(json, trip.getLoadingReviewJson());
return "APPROVED".equals(review.status()) ? null : "REJECTED".equals(review.status()) ? "理货审核已打回:" + review.reason() : "请先通过理货审核再发车";
}
@Transactional
public FleetTripModels.Detail reviewLoading(String tripNo, String operator, FleetTripModels.Review request) {
var trip = requireTrip(tripNo, true);
requireVersionAndPlan(trip, request.recordVersion());
String reason = FleetTripReview.reason(request);
if ("APPROVED".equals(request.decision())) {
if (trip.getDriverId() == null) throw conflict("请先分配司机");
var driver = drivers.requireDispatchable(trip.getDriverId(), trip.getExpectedDriverEndAt().toInstant(ZoneOffset.UTC));
String driverBlock = driverBlockReason(trip, driver);
if (driverBlock != null) throw conflict(driverBlock);
var manifest = manifests(trip, true);
String block = blockReason(trip, manifest);
if (block == null) block = loadBlockReason(trip, cargo(manifest));
if (block != null) throw conflict(block);
}
trip.setLoadingReviewJson(write(new FleetTripModels.ReviewState(request.decision(), reason, operator, Instant.now(), request.recordVersion())));
history.recordExecution(trip, request.recordVersion(), "LOADING_REVIEW", reason, operator);
return history.detail(tripNo);
}
@Transactional
public FleetExecutionModels.Departed depart(String warehouseId, String dispatchNo, String operator, FleetExecutionModels.Depart request) {
var binding = bindings.findByDispatchNo(dispatchNo);
if (binding == null) throw conflict("请先在平台将排车单关联车次");
var trip = requireTrip(binding.getTripNo(), true);
requireWarehouse(trip, warehouseId);
// The binding may have changed while waiting for the trip lock. Never ship a stale parent.
var members = bindings.listByTrip(trip.getId());
if (members.stream().noneMatch(member -> member.getDispatchNo().equals(dispatchNo))) throw conflict("排车单所属车次已变化,请刷新");
String requestHash = hash(write(request));
if (trip.getDepartureKey() != null) {
if (!trip.getDepartureKey().equals(request.idempotencyKey()) || !trip.getDepartureHash().equals(requestHash))
throw conflict("车次已发车,发车请求标识或内容不一致");
return read(trip.getDepartureResultJson(), FleetExecutionModels.Departed.class).withReplay();
}
requireVersionAndPlan(trip, request.recordVersion());
// Resource lock order matches trip assignment: trip -> vehicle -> driver -> customer dispatches.
if (trip.getVehicleId() == null || trip.getDriverId() == null) throw conflict("请先分配车辆和司机");
var vehicle = vehicles.lockById(trip.getVehicleId()).orElseThrow(() -> conflict("车辆档案不存在"));
if (!"IN_SERVICE".equals(vehicle.status()) || !"OVERSEAS".equals(vehicle.region())
|| !Objects.equals(vehicle.plateNumber(), trip.getVehiclePlate()) || !Objects.equals(vehicle.maxPalletSpaces(), trip.getMaxPalletSpaces())
|| !equalNumber(vehicle.maxLoadKg(), trip.getMaxLoadKg()) || !equalNumber(vehicle.maxVolumeCbm(), trip.getMaxVolumeCbm()))
throw conflict("车辆状态或容量已变化,请重新确认车次");
requireResource("VEHICLE", trip.getVehicleId(), trip.getId()); requireResource("DRIVER", trip.getDriverId(), trip.getId());
var driver = drivers.requireDispatchable(trip.getDriverId(), trip.getExpectedDriverEndAt().toInstant(ZoneOffset.UTC));
String driverBlock = driverBlockReason(trip, driver);
if (driverBlock != null) throw conflict(driverBlock);
var manifest = manifests(trip, true);
String reason = blockReason(trip, manifest);
if (reason == null) reason = loadBlockReason(trip, cargo(manifest));
if (reason == null) reason = loadingReviewBlockReason(trip);
if (reason != null) throw conflict(reason);
Instant now = Instant.now();
trip.setStatus("DEPARTING");
if (trips.updateById(trip) != 1) throw conflict("车次状态已变化");
var results = new ArrayList<FleetExecutionModels.DepartedDispatch>();
for (var member : members) results.add(dispatches.depart(warehouseId, member.getDispatchNo(), operator,
trip.getTripNo() + ":" + member.getDispatchNo(), request.remark(), now));
trip.setStatus("IN_TRANSIT"); trip.setDepartedAt(LocalDateTime.ofInstant(now, ZoneOffset.UTC));
var result = new FleetExecutionModels.Departed(trip.getTripNo(), "IN_TRANSIT", now,
results.stream().mapToLong(FleetExecutionModels.DepartedDispatch::shippedPackages).sum(), List.copyOf(results), false);
trip.setDepartureKey(request.idempotencyKey()); trip.setDepartureHash(requestHash); trip.setDepartureResultJson(write(result));
history.recordExecution(trip, request.recordVersion(), "DEPART", request.remark(), operator);
return result;
}
private List<FleetExecutionModels.Manifest> manifests(FleetTripEntity trip, boolean lock) {
return bindings.listByTrip(trip.getId()).stream().map(binding -> dispatches.manifest(binding.getDispatchNo(), lock)).toList();
}
private static List<FleetExecutionModels.Cargo> cargo(List<FleetExecutionModels.Manifest> manifests) {
return manifests.stream().flatMap(manifest -> manifest.cargo().stream())
.sorted(Comparator.comparing(FleetExecutionModels.Cargo::dispatchNo).thenComparing(FleetExecutionModels.Cargo::dispatchItemId)).toList();
}
private String blockReason(FleetTripEntity trip, List<FleetExecutionModels.Manifest> manifests) {
if (!"PLANNED".equals(trip.getStatus())) return "当前车次不是待发车计划";
if (trip.getVehicleId() == null || trip.getDriverId() == null) return "请先分配车辆和司机";
if (manifests.isEmpty()) return "车次尚未关联排车单";
if (bookingReservations.hasConfirmed(trip.getId())) return "已确认外接预订尚未关联实际发运货物,请先完成来货与排车关联";
for (var binding : bindings.listByTrip(trip.getId())) {
if (!FleetTripReview.approved(json, binding.getReviewJson())) return "排车单 " + binding.getDispatchNo() + " 尚未通过调度审核";
}
for (var manifest : manifests) {
if (!trip.getWarehouseId().toString().equals(manifest.warehouseId())) return "排车单起运仓与车次不一致";
if (!Objects.equals(trip.getVehiclePlate(), manifest.vehiclePlate()) || !Objects.equals(trip.getDriverName(), manifest.driverName())
|| !Objects.equals(trip.getDriverPhone(), manifest.driverPhone())) return "排车单 " + manifest.dispatchNo() + " 的车辆司机与车次不一致";
if (manifest.blockReason() != null) return manifest.dispatchNo() + ":" + manifest.blockReason();
}
return null;
}
private String loadBlockReason(FleetTripEntity trip, List<FleetExecutionModels.Cargo> cargo) {
var load = load(trip);
if (load == null) return "请在平台确认本车实际装载";
if (!load.manifestHash().equals(hash(write(cargo)))) return "装载确认后货物发生变化,请重新确认";
try { capacity(trip, cargo, load.pallets()); return null; }
catch (ResponseStatusException error) { return error.getReason(); }
}
private List<TripCapacityPolicy.Segment> capacity(FleetTripEntity trip, List<FleetExecutionModels.Cargo> cargo,
List<FleetExecutionModels.Measurement> pallets) {
List<FleetTripModels.Stop> stops;
try { stops = json.readValue(trip.getStopsJson(), new TypeReference<>() { }); }
catch (JsonProcessingException error) { throw new IllegalStateException("车次路线读取失败", error); }
var destinations = new HashMap<String, String>(); var palletNumbers = new HashMap<String, String>();
if (cargo.isEmpty()) throw conflict("没有待发运货物");
for (var item : cargo) {
if (item.warehousePalletId() == null || item.palletNo() == null || item.palletNo().isBlank() || item.destinationKey() == null || item.packages() <= 0)
throw conflict("货物实物托盘、数量或目的地尚未确认");
String previous = destinations.putIfAbsent(item.warehousePalletId(), item.destinationKey());
if (previous != null && !previous.equals(item.destinationKey())) throw conflict("同一实物托盘包含不同卸货目的地,请先拆托");
String oldNumber = palletNumbers.putIfAbsent(item.warehousePalletId(), item.palletNo());
if (oldNumber != null && !oldNumber.equals(item.palletNo())) throw conflict("实物托盘编号不一致,请核对");
}
var measured = new HashSet<String>(); var bookings = new ArrayList<TripCapacityPolicy.Booking>();
try {
for (var pallet : pallets) {
if (!measured.add(pallet.warehousePalletId())) throw conflict("同一实物托盘不能重复计量");
if (!destinations.containsKey(pallet.warehousePalletId())) throw conflict("装载包含不属于本车的实物托盘");
if (pallet.deliveryIndex() < 1 || pallet.deliveryIndex() >= stops.size()
|| !destinations.get(pallet.warehousePalletId()).equals(stops.get(pallet.deliveryIndex()).destinationKey()))
throw conflict("托盘卸货站与货物目的地不一致");
bookings.add(new TripCapacityPolicy.Booking(pallet.warehousePalletId(), 0, pallet.deliveryIndex(),
new TripCapacityPolicy.Load(pallet.palletSpaces(), pallet.weightKg(), pallet.volumeCbm())));
}
if (!measured.equals(destinations.keySet())) throw conflict("请确认每个实物托盘的托位、实际重量及体积");
if (trip.getMaxPalletSpaces() == null || trip.getMaxLoadKg() == null || trip.getMaxVolumeCbm() == null)
throw conflict("车辆容量未确认");
return TripCapacityPolicy.calculate(stops.size(), new TripCapacityPolicy.Load(trip.getMaxPalletSpaces(), trip.getMaxLoadKg(), trip.getMaxVolumeCbm()), bookings);
} catch (IllegalArgumentException | ArithmeticException error) { throw conflict(error.getMessage()); }
}
private void requireResource(String kind, long id, long tripId) {
var claim = resources.find(kind, id);
if (claim == null || claim.tripId() != tripId) throw conflict("车次车辆或司机占用已变化");
}
private static String driverBlockReason(FleetTripEntity trip, DriverModels.Response driver) {
if (!"OVERSEAS".equals(driver.details().region())) return "本车次须使用海外司机,请核对当前司机档案";
if (!Objects.equals(driver.details().name(), trip.getDriverName())) return "司机档案已变化,请核对车次司机快照";
return null;
}
private FleetTripEntity requireTrip(String tripNo, boolean lock) {
var trip = lock ? trips.lockByNo(tripNo) : trips.findByNo(tripNo);
if (trip == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "车次不存在");
return trip;
}
private static void requireWarehouse(FleetTripEntity trip, String warehouseId) {
if (!trip.getWarehouseId().toString().equals(warehouseId)) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "当前绑定仓无此车次");
}
private static void requireVersionAndPlan(FleetTripEntity trip, long version) {
if (trip.getRecordVersion() != version) throw conflict("车次已被修改,请刷新后重新确认");
if (!"PLANNED".equals(trip.getStatus())) throw conflict("仅计划中的车次允许此操作");
}
private static boolean equalNumber(java.math.BigDecimal a, java.math.BigDecimal b) { return a != null && b != null && a.compareTo(b) == 0; }
private FleetExecutionModels.ConfirmedLoad load(FleetTripEntity trip) { return trip.getLoadJson() == null ? null : read(trip.getLoadJson(), FleetExecutionModels.ConfirmedLoad.class); }
private String write(Object value) { try { return json.writeValueAsString(value); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } }
private <T> T read(String value, Class<T> type) { try { return json.readValue(value, type); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } }
private static String hash(String value) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); }
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
}
@@ -0,0 +1,20 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("ll_fleet_trip_history")
public class FleetTripHistory {
@TableId(type = IdType.INPUT) private Long id;
private Long tripId;
private Long recordVersion;
private String action;
private String reason;
private String operatorId;
private LocalDateTime occurredAt;
private String snapshotJson;
}
@@ -0,0 +1,7 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface FleetTripHistoryMapper extends BaseMapper<FleetTripHistory> { }
@@ -0,0 +1,18 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface FleetTripMapper extends BaseMapper<FleetTripEntity> {
@Select("SELECT * FROM ll_fleet_trip WHERE trip_no=#{tripNo} FOR UPDATE")
FleetTripEntity lockByNo(@Param("tripNo") String tripNo);
@Select("SELECT * FROM ll_fleet_trip WHERE trip_no=#{tripNo}")
FleetTripEntity findByNo(@Param("tripNo") String tripNo);
@Select("SELECT * FROM ll_fleet_trip WHERE created_by=#{operator} AND idempotency_key=#{key}")
FleetTripEntity findCreated(@Param("operator") String operator, @Param("key") String key);
@Select("SELECT * FROM ll_fleet_trip WHERE created_by=#{operator} AND idempotency_key=#{key} FOR UPDATE")
FleetTripEntity lockCreated(@Param("operator") String operator, @Param("key") String key);
}
@@ -0,0 +1,46 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.lastleg.fleet.domain.DriverQualificationPolicy;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
public final class FleetTripModels {
private FleetTripModels() { }
public record Query(@Min(1) Integer page, @Min(1) @Max(200) Integer size, @Size(max = 128) String keyword,
String status, @Positive Long warehouseId) {
public Query { page = page == null ? 1 : page; size = size == null ? 20 : size; }
}
public record Stop(@NotBlank @Size(max = 128) String name, @Size(max = 500) String address,
@Size(max = 160) String destinationKey) { }
public record Create(@NotNull @Positive Long warehouseId, @NotNull Instant plannedDepartureAt,
@NotNull Instant expectedDriverEndAt, @NotNull @Size(min = 2, max = 200) List<@Valid Stop> stops,
@Size(max = 1000) String remark, @NotBlank @Size(min = 8, max = 128) String idempotencyKey) { }
public record Assign(@NotNull @Min(0) Long recordVersion, @NotNull @Positive Long vehicleId,
@NotNull @Positive Long driverId, @NotBlank @Size(max = 1000) String reason) { }
public record Plan(@NotNull @Min(0) Long recordVersion, @NotNull Instant plannedDepartureAt,
@NotNull Instant expectedDriverEndAt, @NotNull @Size(min = 2, max = 200) List<@Valid Stop> stops,
@Size(max = 1000) String remark, @NotBlank @Size(max = 1000) String reason) { }
public record Cancel(@NotNull @Min(0) Long recordVersion, @NotBlank @Size(max = 1000) String reason) { }
public record BindingCommand(@NotNull @Min(0) Long recordVersion, @NotBlank @Size(max = 64) String dispatchNo,
@NotBlank @Size(max = 1000) String reason) { }
public record Review(@NotNull @Min(0) Long recordVersion, @NotBlank @Pattern(regexp = "APPROVED|REJECTED") String decision,
@Size(max = 1000) String reason) { }
public record ReviewState(String status, String reason, String reviewerId, Instant reviewedAt, Long recordVersion) {
public static ReviewState pending() { return new ReviewState("PENDING", null, null, null, null); }
}
public record DispatchBinding(String dispatchNo, String customerId, int packageCount, String boundBy, Instant boundAt, ReviewState review) { }
public record Response(String tripNo, String status, String warehouseId, String warehouseCode, String warehouseName,
String vehicleId, String vehiclePlate, String driverId, String driverName, String driverPhone,
Integer maxPalletSpaces, BigDecimal maxLoadKg, BigDecimal maxVolumeCbm,
Instant plannedDepartureAt, Instant expectedDriverEndAt, Instant departedAt, Instant completedAt,
List<Stop> stops, String remark, long recordVersion, Instant updatedAt,
FleetCompletionModels.ReleaseInfo vehicleRelease, FleetCompletionModels.ReleaseInfo driverRelease) { }
public record Detail(Response trip, DriverQualificationPolicy.Qualification driverQualification, List<DispatchBinding> dispatches, ReviewState loadingReview) { }
public record AuditSnapshot(Response trip, List<DispatchBinding> dispatches, FleetExecutionModels.ConfirmedLoad confirmedLoad,
FleetCompletionModels.Completed completion, ReviewState loadingReview,
FleetExecutionModels.PlannedLoad capacityPlan, List<FleetBookingModels.Response> externalBookings) { }
public record History(long recordVersion, String action, String reason, String operatorId, Instant occurredAt, AuditSnapshot snapshot) { }
}
@@ -0,0 +1,24 @@
package com.baiyue.lastleg.fleet.trip;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
final class FleetTripReview {
private FleetTripReview() { }
static FleetTripModels.ReviewState read(ObjectMapper json, String value) {
if (value == null) return FleetTripModels.ReviewState.pending();
try { return json.readValue(value, FleetTripModels.ReviewState.class); }
catch (JsonProcessingException error) { throw new IllegalStateException("审核记录读取失败", error); }
}
static String reason(FleetTripModels.Review request) {
if (!"APPROVED".equals(request.decision()) && !"REJECTED".equals(request.decision()))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请选择审核通过或打回");
String reason = request.reason() == null ? "" : request.reason().trim();
if ("REJECTED".equals(request.decision()) && reason.isEmpty())
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请填写打回原因");
return reason.isEmpty() ? "审核通过" : reason;
}
static boolean approved(ObjectMapper json, String value) { return "APPROVED".equals(read(json, value).status()); }
}
@@ -0,0 +1,336 @@
package com.baiyue.lastleg.fleet.trip;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baiyue.common.core.api.PageResult;
import com.baiyue.lastleg.fleet.driver.DriverService;
import com.baiyue.lastleg.fleet.driver.FleetWarehouseDirectory;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.*;
import java.util.*;
@Service
public class FleetTripService {
private final FleetTripMapper trips;
private final FleetResourceMapper resources;
private final FleetTripHistoryMapper histories;
private final FleetTripDispatchMapper bindings;
private final FleetDispatchGateway dispatches;
private final VehicleRepository vehicles;
private final DriverService drivers;
private final FleetWarehouseDirectory warehouses;
private final ObjectMapper json;
private final Clock clock;
private final FleetBookingReservations bookingReservations;
@Autowired
public FleetTripService(FleetTripMapper trips, FleetResourceMapper resources, FleetTripHistoryMapper histories,
VehicleRepository vehicles, DriverService drivers, FleetWarehouseDirectory warehouses, ObjectMapper json,
FleetTripDispatchMapper bindings, FleetDispatchGateway dispatches, FleetBookingReservations bookingReservations) {
this(trips, resources, histories, vehicles, drivers, warehouses, json, bindings, dispatches, bookingReservations, Clock.systemUTC());
}
FleetTripService(FleetTripMapper trips, FleetResourceMapper resources, FleetTripHistoryMapper histories,
VehicleRepository vehicles, DriverService drivers, FleetWarehouseDirectory warehouses, ObjectMapper json,
FleetTripDispatchMapper bindings, FleetDispatchGateway dispatches, FleetBookingReservations bookingReservations, Clock clock) {
this.trips = trips; this.resources = resources; this.histories = histories; this.vehicles = vehicles;
this.drivers = drivers; this.warehouses = warehouses; this.json = json; this.clock = clock;
this.bindings = bindings; this.dispatches = dispatches; this.bookingReservations = bookingReservations;
}
public PageResult<FleetTripModels.Response> page(FleetTripModels.Query query) {
if (query.status() != null && !query.status().isBlank() && !Set.of("PLANNED", "IN_TRANSIT", "COMPLETED", "CANCELLED").contains(query.status()))
throw bad("车次状态无效");
var filter = new LambdaQueryWrapper<FleetTripEntity>()
.eq(query.status() != null && !query.status().isBlank(), FleetTripEntity::getStatus, query.status())
.eq(query.warehouseId() != null, FleetTripEntity::getWarehouseId, query.warehouseId());
if (query.keyword() != null && !query.keyword().isBlank()) filter.and(part -> part.like(FleetTripEntity::getTripNo, query.keyword().trim())
.or().like(FleetTripEntity::getVehiclePlate, query.keyword().trim()).or().like(FleetTripEntity::getDriverName, query.keyword().trim()));
filter.orderByDesc(FleetTripEntity::getUpdatedAt, FleetTripEntity::getId);
var page = trips.selectPage(new Page<>(query.page(), query.size()), filter);
return new PageResult<>(page.getRecords().stream().map(this::response).toList(), page.getCurrent(), page.getSize(), page.getTotal(), page.getPages());
}
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public FleetTripModels.Detail detail(String tripNo) {
FleetTripEntity trip = required(tripNo);
return detail(trip);
}
@Transactional
public FleetTripModels.Detail create(String operator, FleetTripModels.Create request) {
String hash = hash(write(request));
var existing = trips.findCreated(operator, request.idempotencyKey());
if (existing != null) return replay(existing, hash);
validatePlan(request.plannedDepartureAt(), request.expectedDriverEndAt(), request.stops());
var warehouse = warehouses.required(request.warehouseId(), "OVERSEAS");
var trip = new FleetTripEntity();
trip.setId(IdWorker.getId());
trip.setTripNo("TR-" + UUID.randomUUID().toString().replace("-", "").substring(0, 16).toUpperCase(Locale.ROOT));
trip.setIdempotencyKey(request.idempotencyKey()); trip.setRequestHash(hash);
trip.setStatus("PLANNED"); trip.setWarehouseId(Long.valueOf(warehouse.id()));
trip.setWarehouseCode(warehouse.code()); trip.setWarehouseName(warehouse.name());
trip.setPlannedDepartureAt(utc(request.plannedDepartureAt())); trip.setExpectedDriverEndAt(utc(request.expectedDriverEndAt()));
trip.setStopsJson(write(request.stops())); trip.setRemark(trim(request.remark()));
trip.setRecordVersion(0L); trip.setCreatedBy(operator); trip.setUpdatedBy(operator);
trip.setCreatedAt(now()); trip.setUpdatedAt(trip.getCreatedAt());
try { if (trips.insert(trip) != 1) throw conflict("车次创建失败"); }
catch (DuplicateKeyException duplicate) {
var concurrent = trips.lockCreated(operator, request.idempotencyKey());
if (concurrent == null) throw conflict("车次编号冲突,请重试");
return replay(concurrent, hash);
}
record(trip, "CREATE", null, operator);
return detail(trip);
}
@Transactional
public FleetTripModels.Detail assign(String tripNo, String operator, FleetTripModels.Assign request) {
FleetTripEntity trip = planned(tripNo, request.recordVersion());
requireReason(request.reason());
// All assigners serialize first on the vehicle, then on the driver. Resource uniqueness is the final safeguard.
var vehicle = vehicles.lockById(request.vehicleId()).orElseThrow(() -> bad("车辆档案不存在"));
if (!"OVERSEAS".equals(vehicle.region()) || !"IN_SERVICE".equals(vehicle.status())) throw bad("请选择在役海外车辆");
if (vehicle.maxPalletSpaces() == null || vehicle.maxLoadKg() == null || vehicle.maxVolumeCbm() == null
|| vehicle.maxPalletSpaces() <= 0 || vehicle.maxLoadKg().signum() <= 0 || vehicle.maxVolumeCbm().signum() <= 0)
throw bad("请先确认车辆的托位、载重和容积");
if (trip.getLoadJson() != null) {
var load = read(trip.getLoadJson(), FleetExecutionModels.ConfirmedLoad.class);
if (load.segments().stream().anyMatch(segment -> segment.occupied().palletSpaces() > vehicle.maxPalletSpaces()
|| segment.occupied().weightKg().compareTo(vehicle.maxLoadKg()) > 0
|| segment.occupied().volumeCbm().compareTo(vehicle.maxVolumeCbm()) > 0))
throw bad("已确认装载超过替换车辆的托位、载重或容积,请先调整装载安排");
}
if (!Objects.equals(trip.getVehicleId(), vehicle.id()))
bookingReservations.requireReassignmentFits(trip, vehicle.maxPalletSpaces(), vehicle.maxLoadKg(), vehicle.maxVolumeCbm());
var driver = drivers.requireDispatchable(request.driverId(), instant(trip.getExpectedDriverEndAt()));
if (!"OVERSEAS".equals(driver.details().region())) throw bad("请选择海外司机");
reserve("VEHICLE", request.vehicleId(), trip);
reserve("DRIVER", request.driverId(), trip);
if (trip.getVehicleId() != null && !trip.getVehicleId().equals(request.vehicleId())) release("VEHICLE", trip.getVehicleId(), trip.getId());
if (trip.getDriverId() != null && !trip.getDriverId().equals(request.driverId())) release("DRIVER", trip.getDriverId(), trip.getId());
trip.setVehicleId(vehicle.id()); trip.setVehiclePlate(vehicle.plateNumber());
trip.setMaxPalletSpaces(vehicle.maxPalletSpaces()); trip.setMaxLoadKg(vehicle.maxLoadKg()); trip.setMaxVolumeCbm(vehicle.maxVolumeCbm());
trip.setDriverId(Long.valueOf(driver.id())); trip.setDriverName(driver.details().name()); trip.setDriverPhone(driver.details().phone());
for (var binding : bindings.listByTrip(trip.getId())) {
var dispatch = dispatches.lockForAssignment(binding.getDispatchNo());
if (!trip.getWarehouseId().toString().equals(dispatch.warehouseId())) throw conflict("排车单与车次起运仓不一致");
dispatches.assign(dispatch, assignment(trip));
}
persist(trip, request.recordVersion(), "ASSIGN", request.reason(), operator);
return new FleetTripModels.Detail(response(trip), driver.qualification(), bindingResponses(trip), FleetTripReview.read(json, trip.getLoadingReviewJson()));
}
@Transactional
public FleetTripModels.Detail updatePlan(String tripNo, String operator, FleetTripModels.Plan request) {
FleetTripEntity trip = planned(tripNo, request.recordVersion());
requireReason(request.reason());
validatePlan(request.plannedDepartureAt(), request.expectedDriverEndAt(), request.stops());
bookingReservations.requireRoute(trip, request.stops());
if (trip.getDriverId() != null) drivers.requireDispatchable(trip.getDriverId(), request.expectedDriverEndAt());
boolean unchangedRoute = response(trip).stops().equals(request.stops());
boolean unchangedPlan = unchangedRoute && trip.getPlannedDepartureAt().equals(utc(request.plannedDepartureAt()))
&& trip.getExpectedDriverEndAt().equals(utc(request.expectedDriverEndAt()));
for (var binding : bindings.listByTrip(trip.getId())) {
if (unchangedRoute) dispatches.lockForAssignment(binding.getDispatchNo());
else dispatches.lockForPlanning(binding.getDispatchNo());
}
trip.setPlannedDepartureAt(utc(request.plannedDepartureAt())); trip.setExpectedDriverEndAt(utc(request.expectedDriverEndAt()));
trip.setStopsJson(write(request.stops())); trip.setRemark(trim(request.remark()));
persist(trip, request.recordVersion(), unchangedPlan ? "REMARK" : "PLAN", request.reason(), operator);
return detail(trip);
}
@Transactional
public FleetTripModels.Detail reviewDispatch(String tripNo, String dispatchNo, String operator, FleetTripModels.Review request) {
var trip = planned(tripNo, request.recordVersion());
String reason = FleetTripReview.reason(request);
if (trip.getVehicleId() == null || trip.getDriverId() == null) throw conflict("请先分配车辆和司机");
if ("APPROVED".equals(request.decision())) {
var vehicle = vehicles.lockById(trip.getVehicleId()).orElseThrow(() -> bad("车辆档案不存在"));
if (!"IN_SERVICE".equals(vehicle.status()) || !"OVERSEAS".equals(vehicle.region())) throw conflict("车辆当前不可派车");
var driver = drivers.requireDispatchable(trip.getDriverId(), instant(trip.getExpectedDriverEndAt()));
if (!"OVERSEAS".equals(driver.details().region())) throw conflict("请选择海外司机");
}
var dispatch = dispatches.lockForAssignment(dispatchNo);
var binding = bindings.lockByDispatch(dispatch.dispatchId());
if (binding == null || !Objects.equals(binding.getTripId(), trip.getId())) throw conflict("排车单未关联当前车次");
binding.setReviewJson(write(new FleetTripModels.ReviewState(request.decision(), reason, operator, clock.instant(), request.recordVersion())));
if (bindings.updateById(binding) != 1) throw conflict("排车单审核保存失败");
trip.setLoadingReviewJson(null);
persist(trip, request.recordVersion(), "DISPATCH_REVIEW", reason, operator);
return detail(trip);
}
@Transactional
public FleetTripModels.Detail cancel(String tripNo, String operator, FleetTripModels.Cancel request) {
FleetTripEntity trip = planned(tripNo, request.recordVersion());
requireReason(request.reason());
if (!bindings.listByTrip(trip.getId()).isEmpty()) throw conflict("请先解除客户排车单关联,再取消车次");
if (bookingReservations.hasConfirmed(trip.getId())) throw conflict("请先取消已确认的外接预订,再取消车次");
if (trip.getVehicleId() != null) release("VEHICLE", trip.getVehicleId(), trip.getId());
if (trip.getDriverId() != null) release("DRIVER", trip.getDriverId(), trip.getId());
trip.setStatus("CANCELLED");
persist(trip, request.recordVersion(), "CANCEL", request.reason(), operator);
return detail(trip);
}
@Transactional
public FleetTripModels.Detail bindDispatch(String tripNo, String operator, FleetTripModels.BindingCommand request) {
var trip = planned(tripNo, request.recordVersion());
requireReason(request.reason());
if (trip.getVehicleId() == null || trip.getDriverId() == null) throw conflict("请先分配车辆和司机");
var dispatch = dispatches.lockForPlanning(request.dispatchNo().trim());
if (!trip.getWarehouseId().toString().equals(dispatch.warehouseId())) throw bad("排车单与车次必须使用同一起运仓");
var bound = bindings.lockByDispatch(dispatch.dispatchId());
if (bound != null) throw conflict("排车单已关联车次 " + bound.getTripNo());
var binding = new FleetTripDispatch();
binding.setDispatchId(dispatch.dispatchId()); binding.setDispatchNo(dispatch.dispatchNo()); binding.setCustomerId(dispatch.customerId());
binding.setTripId(trip.getId()); binding.setTripNo(tripNo); binding.setPackageCount(dispatch.packageCount());
binding.setBoundBy(operator); binding.setBoundAt(now());
try { if (bindings.insert(binding) != 1) throw conflict("排车单关联失败"); }
catch (DuplicateKeyException duplicate) { throw conflict("排车单已关联其他车次,请刷新后重试"); }
bookingReservations.bindIncoming(trip, dispatch, dispatches.sourceCargo(dispatch.dispatchNo()), operator);
dispatches.assign(dispatch, assignment(trip));
persist(trip, request.recordVersion(), "BIND_DISPATCH", request.reason(), operator);
return detail(trip);
}
@Transactional
public FleetTripModels.Detail unbindDispatch(String tripNo, String operator, FleetTripModels.BindingCommand request) {
var trip = planned(tripNo, request.recordVersion());
requireReason(request.reason());
var dispatch = dispatches.lockForPlanning(request.dispatchNo().trim());
var binding = bindings.lockByDispatch(dispatch.dispatchId());
if (binding == null || !Objects.equals(binding.getTripId(), trip.getId())) throw conflict("排车单未关联当前车次");
dispatches.assign(dispatch, new FleetDispatchGateway.Assignment(null, null, null));
if (bindings.deleteById(binding.getDispatchId()) != 1) throw conflict("排车单关联已变化,请刷新后重试");
bookingReservations.unbindIncoming(trip, dispatch.dispatchNo(), operator);
persist(trip, request.recordVersion(), "UNBIND_DISPATCH", request.reason(), operator);
return detail(trip);
}
public PageResult<FleetTripModels.History> history(String tripNo, int page, int size) {
var trip = required(tripNo);
var result = histories.selectPage(new Page<>(page, size), new LambdaQueryWrapper<FleetTripHistory>()
.eq(FleetTripHistory::getTripId, trip.getId()).orderByDesc(FleetTripHistory::getRecordVersion));
return new PageResult<>(result.getRecords().stream().map(event -> new FleetTripModels.History(event.getRecordVersion(), event.getAction(),
event.getReason(), event.getOperatorId(), instant(event.getOccurredAt()), read(event.getSnapshotJson(), FleetTripModels.AuditSnapshot.class))).toList(),
result.getCurrent(), result.getSize(), result.getTotal(), result.getPages());
}
private void reserve(String kind, long resourceId, FleetTripEntity trip) {
var current = resources.find(kind, resourceId);
if (current != null) {
if (current.tripId() == trip.getId()) return;
throw conflict(("VEHICLE".equals(kind) ? "车辆" : "司机") + "已被车次 " + current.tripNo() + " 占用");
}
try { if (resources.reserve(kind, resourceId, trip.getId(), trip.getTripNo()) != 1) throw conflict("车次资源预留失败"); }
catch (DuplicateKeyException duplicate) { throw conflict("车辆或司机已被其他车次占用,请刷新后重试"); }
}
private void release(String kind, long resourceId, long tripId) {
if (resources.release(kind, resourceId, tripId) != 1) throw conflict("车次资源占用不一致,操作未完成");
}
private FleetTripEntity required(String number) {
var trip = trips.findByNo(number);
if (trip == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "车次不存在");
return trip;
}
private FleetTripEntity planned(String number, long version) {
var trip = trips.lockByNo(number);
if (trip == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "车次不存在");
if (trip.getRecordVersion() != version) throw conflict("车次已被修改,请刷新后重试");
if (!"PLANNED".equals(trip.getStatus())) throw conflict("仅计划中的车次允许此操作");
return trip;
}
private FleetTripModels.Detail replay(FleetTripEntity trip, String hash) {
if (!Objects.equals(trip.getRequestHash(), hash)) throw conflict("创建请求标识已用于不同车次内容");
return detail(trip);
}
private FleetTripModels.Detail detail(FleetTripEntity trip) {
return new FleetTripModels.Detail(response(trip), trip.getDriverId() == null ? null
: drivers.detail(trip.getDriverId(), instant(trip.getExpectedDriverEndAt())).qualification(), bindingResponses(trip), FleetTripReview.read(json, trip.getLoadingReviewJson()));
}
private List<FleetTripModels.DispatchBinding> bindingResponses(FleetTripEntity trip) {
return bindings.listByTrip(trip.getId()).stream().map(binding -> new FleetTripModels.DispatchBinding(binding.getDispatchNo(),
binding.getCustomerId(), binding.getPackageCount(), binding.getBoundBy(), instant(binding.getBoundAt()), FleetTripReview.read(json, binding.getReviewJson()))).toList();
}
private static FleetDispatchGateway.Assignment assignment(FleetTripEntity trip) {
return new FleetDispatchGateway.Assignment(trip.getVehiclePlate(), trip.getDriverName(), trip.getDriverPhone());
}
private FleetTripModels.Response response(FleetTripEntity trip) {
List<FleetTripModels.Stop> stops;
try { stops = json.readValue(trip.getStopsJson(), new TypeReference<>() { }); }
catch (JsonProcessingException error) { throw new IllegalStateException("车次路线读取失败", error); }
return new FleetTripModels.Response(trip.getTripNo(), trip.getStatus(), trip.getWarehouseId().toString(), trip.getWarehouseCode(), trip.getWarehouseName(),
text(trip.getVehicleId()), trip.getVehiclePlate(), text(trip.getDriverId()), trip.getDriverName(), trip.getDriverPhone(),
trip.getMaxPalletSpaces(), trip.getMaxLoadKg(), trip.getMaxVolumeCbm(), instant(trip.getPlannedDepartureAt()), instant(trip.getExpectedDriverEndAt()),
instant(trip.getDepartedAt()), instant(trip.getCompletedAt()), List.copyOf(stops), trip.getRemark(), trip.getRecordVersion(), instant(trip.getUpdatedAt()),
releaseInfo(trip.getVehicleReleaseJson()), releaseInfo(trip.getDriverReleaseJson()));
}
private void validatePlan(Instant departure, Instant end, List<FleetTripModels.Stop> stops) {
if (departure == null || end == null || !end.isAfter(departure) || !end.isAfter(clock.instant())) throw bad("司机预计任务结束时间须晚于计划发车及当前时间");
try {
if (utc(departure).getYear() < 1900 || utc(end).getYear() > 9998) throw bad("车次时间超出允许范围");
} catch (DateTimeException invalid) { throw bad("车次时间超出允许范围"); }
if (stops == null || stops.size() < 2 || stops.size() > 200 || stops.stream().anyMatch(stop -> stop == null || trim(stop.name()) == null))
throw bad("车次须包含起点和目的地,最多200个站点");
}
private void persist(FleetTripEntity trip, long version, String action, String reason, String operator) {
if (Set.of("ASSIGN", "PLAN", "BIND_DISPATCH", "UNBIND_DISPATCH", "CANCEL").contains(action)) trip.setPlannedLoadJson(null);
if (Set.of("ASSIGN", "PLAN", "BIND_DISPATCH", "UNBIND_DISPATCH", "CANCEL").contains(action)) trip.setLoadJson(null);
if (Set.of("ASSIGN", "PLAN", "BIND_DISPATCH", "UNBIND_DISPATCH", "CANCEL", "CONFIRM_LOAD").contains(action)) trip.setLoadingReviewJson(null);
if (Set.of("ASSIGN", "PLAN").contains(action)) bindings.update(null, new LambdaUpdateWrapper<FleetTripDispatch>()
.eq(FleetTripDispatch::getTripId, trip.getId()).set(FleetTripDispatch::getReviewJson, null));
trip.setRecordVersion(version + 1); trip.setUpdatedAt(now()); trip.setUpdatedBy(operator);
if (trips.update(trip, new LambdaUpdateWrapper<FleetTripEntity>().eq(FleetTripEntity::getId, trip.getId()).eq(FleetTripEntity::getRecordVersion, version)) != 1)
throw conflict("车次已被修改,请刷新后重试");
record(trip, action, reason, operator);
}
private void record(FleetTripEntity trip, String action, String reason, String operator) {
var event = new FleetTripHistory(); event.setId(IdWorker.getId()); event.setTripId(trip.getId()); event.setRecordVersion(trip.getRecordVersion());
event.setAction(action); event.setReason(trim(reason)); event.setOperatorId(operator); event.setOccurredAt(trip.getUpdatedAt());
event.setSnapshotJson(write(new FleetTripModels.AuditSnapshot(response(trip), bindingResponses(trip), trip.getLoadJson() == null ? null
: read(trip.getLoadJson(), FleetExecutionModels.ConfirmedLoad.class), trip.getCompletionJson() == null ? null
: read(trip.getCompletionJson(), FleetCompletionModels.Completed.class), FleetTripReview.read(json, trip.getLoadingReviewJson()),
trip.getPlannedLoadJson() == null ? null : read(trip.getPlannedLoadJson(), FleetExecutionModels.PlannedLoad.class), bookingReservations.responses(trip.getId()))));
if (histories.insert(event) != 1) throw conflict("车次历史保存失败");
}
private String write(Object value) { try { return json.writeValueAsString(value); } catch (JsonProcessingException e) { throw new IllegalStateException("车次序列化失败", e); } }
private FleetCompletionModels.ReleaseInfo releaseInfo(String value) {
if (value == null) return null;
var released = read(value, FleetCompletionModels.Released.class);
return new FleetCompletionModels.ReleaseInfo(released.actualEndAt(), released.endLocation(), released.vehicleStatus());
}
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY)
public void recordExecution(FleetTripEntity trip, long version, String action, String reason, String operator) {
persist(trip, version, action, reason, operator);
}
private <T> T read(String value, Class<T> type) { try { return json.readValue(value, type); } catch (JsonProcessingException e) { throw new IllegalStateException("车次历史读取失败", e); } }
private static String hash(String value) { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } }
private LocalDateTime now() { return utc(clock.instant()); }
private static LocalDateTime utc(Instant value) { return LocalDateTime.ofInstant(value, ZoneOffset.UTC); }
private static Instant instant(LocalDateTime value) { return value == null ? null : value.toInstant(ZoneOffset.UTC); }
private static String text(Long value) { return value == null ? null : value.toString(); }
private static String trim(String value) { return value == null || value.isBlank() ? null : value.trim(); }
private static void requireReason(String reason) { if (trim(reason) == null) throw bad("请填写操作原因"); }
private static ResponseStatusException bad(String message) { return new ResponseStatusException(HttpStatus.BAD_REQUEST, message); }
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
}
@@ -0,0 +1,16 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.lastleg.masterdata.vehicle.application.VehicleApplicationService;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleAssignmentGuard;
import org.springframework.stereotype.Component;
@Component
public class FleetVehicleAssignmentGuard implements VehicleAssignmentGuard {
private final FleetResourceMapper resources;
public FleetVehicleAssignmentGuard(FleetResourceMapper resources) { this.resources = resources; }
@Override public void requireUnassigned(long vehicleId) {
var assignment = resources.find("VEHICLE", vehicleId);
if (assignment != null) throw new VehicleApplicationService.VehicleFailure(VehicleApplicationService.FailureKind.CONFLICT,
"车辆正在车次 " + assignment.tripNo() + " 中使用,请先在车次中改派或取消安排");
}
}
@@ -0,0 +1,40 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.fleet.customer.FleetCustomerDirectory;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@RestController @RequestMapping("/api/platform/v1/last-leg/fleet/trips")
public class PlatformFleetBookingController {
private final FleetBookingService service;
private final FleetCustomerDirectory customers;
public PlatformFleetBookingController(FleetBookingService service,FleetCustomerDirectory customers){this.service=service;this.customers=customers;}
@GetMapping("/customer-options") @PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<List<FleetCustomerDirectory.Customer>> customers(@RequestParam(required=false) String keyword){return ApiResponse.success(customers.options(keyword));}
@GetMapping("/{tripNo}/bookings") @PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<FleetBookingModels.ListResult> list(@PathVariable String tripNo){return ApiResponse.success(service.list(tripNo));}
@PostMapping("/{tripNo}/bookings") @PreAuthorize("hasAuthority('platform:fleet:trip:booking-create')")
public ApiResponse<FleetBookingModels.Result> create(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String tripNo,@Valid @RequestBody FleetBookingModels.Create request){return ApiResponse.success(service.create(tripNo,operator(user),request));}
@PutMapping("/{tripNo}/bookings/{bookingNo}") @PreAuthorize("hasAuthority('platform:fleet:trip:booking-edit')")
public ApiResponse<FleetBookingModels.Result> update(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String tripNo,@PathVariable String bookingNo,@Valid @RequestBody FleetBookingModels.Update request){return ApiResponse.success(service.update(tripNo,bookingNo,operator(user),request));}
@PostMapping("/{tripNo}/bookings/{bookingNo}/confirm") @PreAuthorize("hasAuthority('platform:fleet:trip:booking-confirm')")
public ApiResponse<FleetBookingModels.Result> confirm(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String tripNo,@PathVariable String bookingNo,@Valid @RequestBody FleetBookingModels.Command request){return ApiResponse.success(service.confirm(tripNo,bookingNo,operator(user),request));}
@PostMapping("/{tripNo}/bookings/{bookingNo}/cancel") @PreAuthorize("hasAuthority('platform:fleet:trip:booking-cancel')")
public ApiResponse<FleetBookingModels.Result> cancel(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String tripNo,@PathVariable String bookingNo,@Valid @RequestBody FleetBookingModels.Command request){return ApiResponse.success(service.cancel(tripNo,bookingNo,operator(user),request));}
@GetMapping("/{tripNo}/bookings/{bookingNo}/incoming") @PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<FleetBookingModels.IncomingPreview> incoming(@PathVariable String tripNo,@PathVariable String bookingNo){return ApiResponse.success(service.incoming(tripNo,bookingNo));}
@PostMapping("/{tripNo}/bookings/{bookingNo}/incoming") @PreAuthorize("hasAuthority('platform:fleet:trip:booking-edit')")
public ApiResponse<FleetBookingModels.Result> incoming(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String tripNo,@PathVariable String bookingNo,@Valid @RequestBody FleetBookingModels.StartIncoming request){return ApiResponse.success(service.startIncoming(tripNo,bookingNo,operator(user),request));}
@PostMapping("/{tripNo}/bookings/{bookingNo}/receipt-confirmation") @PreAuthorize("hasAuthority('platform:fleet:trip:booking-confirm')")
public ApiResponse<FleetBookingModels.Result> receipt(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String tripNo,@PathVariable String bookingNo,@Valid @RequestBody FleetBookingModels.AcceptReceipt request){return ApiResponse.success(service.acceptReceipt(tripNo,bookingNo,operator(user),request));}
@PostMapping("/{tripNo}/bookings/{bookingNo}/dispatch") @PreAuthorize("hasAuthority('platform:fleet:trip:booking-edit') and hasAuthority('platform:fleet:trip:edit')")
public ApiResponse<FleetBookingModels.Result> bind(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String tripNo,@PathVariable String bookingNo,@Valid @RequestBody FleetBookingModels.BindDispatch request){return ApiResponse.success(service.bindDispatch(tripNo,bookingNo,operator(user),request));}
private static String operator(AuthenticatedUser user){if(user==null||user.userId()==null)throw new ResponseStatusException(HttpStatus.UNAUTHORIZED,"请重新登录");return user.userId().toString();}
}
@@ -0,0 +1,120 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.core.api.PageResult;
import com.baiyue.common.security.AuthenticatedUser;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
@RestController
@Validated
@RequestMapping("/api/platform/v1/last-leg/fleet/trips")
public class PlatformFleetTripController {
private final FleetTripService service;
private final FleetTripExecutionService execution;
private final FleetTripCompletionService completion;
public PlatformFleetTripController(FleetTripService service, FleetTripExecutionService execution, FleetTripCompletionService completion) {
this.service = service; this.execution = execution; this.completion = completion;
}
@GetMapping
@PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<PageResult<FleetTripModels.Response>> page(@Valid FleetTripModels.Query query) { return ApiResponse.success(service.page(query)); }
@GetMapping("/{tripNo}")
@PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<FleetTripModels.Detail> detail(@PathVariable String tripNo) { return ApiResponse.success(service.detail(tripNo)); }
@PostMapping
@PreAuthorize("hasAuthority('platform:fleet:trip:create')")
public ApiResponse<FleetTripModels.Detail> create(@AuthenticationPrincipal AuthenticatedUser user, @Valid @RequestBody FleetTripModels.Create request) {
return ApiResponse.success(service.create(operator(user), request));
}
@PutMapping("/{tripNo}/plan")
@PreAuthorize("hasAuthority('platform:fleet:trip:edit')")
public ApiResponse<FleetTripModels.Detail> plan(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo, @Valid @RequestBody FleetTripModels.Plan request) {
return ApiResponse.success(service.updatePlan(tripNo, operator(user), request));
}
@PostMapping("/{tripNo}/assignment")
@PreAuthorize("hasAuthority('platform:fleet:trip:assign')")
public ApiResponse<FleetTripModels.Detail> assign(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo, @Valid @RequestBody FleetTripModels.Assign request) {
return ApiResponse.success(service.assign(tripNo, operator(user), request));
}
@PostMapping("/{tripNo}/cancel")
@PreAuthorize("hasAuthority('platform:fleet:trip:cancel')")
public ApiResponse<FleetTripModels.Detail> cancel(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo, @Valid @RequestBody FleetTripModels.Cancel request) {
return ApiResponse.success(service.cancel(tripNo, operator(user), request));
}
@PostMapping("/{tripNo}/dispatches/bind")
@PreAuthorize("hasAuthority('platform:fleet:trip:edit')")
public ApiResponse<FleetTripModels.Detail> bind(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@Valid @RequestBody FleetTripModels.BindingCommand request) {
return ApiResponse.success(service.bindDispatch(tripNo, operator(user), request));
}
@PostMapping("/{tripNo}/dispatches/unbind")
@PreAuthorize("hasAuthority('platform:fleet:trip:edit')")
public ApiResponse<FleetTripModels.Detail> unbind(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@Valid @RequestBody FleetTripModels.BindingCommand request) {
return ApiResponse.success(service.unbindDispatch(tripNo, operator(user), request));
}
@GetMapping("/{tripNo}/history")
@PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<PageResult<FleetTripModels.History>> history(@PathVariable String tripNo,
@RequestParam(defaultValue = "1") @Min(1) int page, @RequestParam(defaultValue = "20") @Min(1) @Max(200) int size) {
return ApiResponse.success(service.history(tripNo, page, size));
}
@PostMapping("/{tripNo}/dispatches/{dispatchNo}/review")
@PreAuthorize("hasAuthority('platform:fleet:trip:dispatch-review')")
public ApiResponse<FleetTripModels.Detail> reviewDispatch(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@PathVariable String dispatchNo, @Valid @RequestBody FleetTripModels.Review request) {
return ApiResponse.success(service.reviewDispatch(tripNo, dispatchNo, operator(user), request));
}
@PostMapping("/{tripNo}/loading-review")
@PreAuthorize("hasAuthority('platform:fleet:trip:loading-review')")
public ApiResponse<FleetTripModels.Detail> reviewLoading(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@Valid @RequestBody FleetTripModels.Review request) {
return ApiResponse.success(execution.reviewLoading(tripNo, operator(user), request));
}
@GetMapping("/{tripNo}/loading")
@PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<FleetExecutionModels.Loading> loading(@PathVariable String tripNo) { return ApiResponse.success(execution.loading(tripNo)); }
@GetMapping("/{tripNo}/capacity-plan")
@PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<FleetExecutionModels.Planning> capacityPlan(@PathVariable String tripNo) { return ApiResponse.success(execution.capacityPlan(tripNo)); }
@PostMapping("/{tripNo}/capacity-plan")
@PreAuthorize("hasAuthority('platform:fleet:trip:edit')")
public ApiResponse<FleetExecutionModels.Planning> confirmCapacityPlan(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@Valid @RequestBody FleetExecutionModels.Confirm request) {
return ApiResponse.success(execution.confirmCapacityPlan(tripNo, operator(user), request));
}
@PostMapping("/{tripNo}/loading")
@PreAuthorize("hasAuthority('platform:fleet:trip:edit')")
public ApiResponse<FleetExecutionModels.Loading> confirmLoading(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@Valid @RequestBody FleetExecutionModels.Confirm request) {
return ApiResponse.success(execution.confirmLoad(tripNo, operator(user), request));
}
private static String operator(AuthenticatedUser user) {
if (user == null || user.userId() == null) throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "请重新登录");
return user.userId().toString();
}
@GetMapping("/{tripNo}/completion")
@PreAuthorize("hasAuthority('platform:fleet:trip:list')")
public ApiResponse<FleetCompletionModels.Inspection> completion(@PathVariable String tripNo) { return ApiResponse.success(completion.inspection(tripNo)); }
@PostMapping("/{tripNo}/complete")
@PreAuthorize("hasAuthority('platform:fleet:trip:complete')")
public ApiResponse<FleetTripModels.Detail> complete(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@Valid @RequestBody FleetCompletionModels.Complete request) {
return ApiResponse.success(completion.complete(tripNo, operator(user), request));
}
@PostMapping("/{tripNo}/resources/release")
@PreAuthorize("hasAuthority('platform:fleet:trip:release')")
public ApiResponse<FleetTripModels.Detail> release(@AuthenticationPrincipal AuthenticatedUser user, @PathVariable String tripNo,
@Valid @RequestBody FleetCompletionModels.Release request) {
return ApiResponse.success(completion.release(tripNo, operator(user), request));
}
}
@@ -48,6 +48,9 @@ public class VehiclePersistenceAdapter implements VehicleRepository {
record.setId(IdWorker.getId());
record.setPlateNumber(vehicle.plateNumber());
record.setModel(vehicle.model());
record.setMaxPalletSpaces(vehicle.maxPalletSpaces());
record.setMaxLoadKg(vehicle.maxLoadKg());
record.setMaxVolumeCbm(vehicle.maxVolumeCbm());
record.setFuelConsumptionPer100Km(vehicle.fuelConsumptionPer100Km());
record.setMileageKm(vehicle.mileageKm());
record.setDriverOrDispatchCompany(vehicle.driverOrDispatchCompany());
@@ -76,6 +79,9 @@ public class VehiclePersistenceAdapter implements VehicleRepository {
.eq(VehicleRecord::getId, id).eq(VehicleRecord::getRecordVersion, expectedVersion)
.set(VehicleRecord::getPlateNumber, changes.plateNumber())
.set(VehicleRecord::getModel, changes.model())
.set(VehicleRecord::getMaxPalletSpaces, changes.maxPalletSpaces())
.set(VehicleRecord::getMaxLoadKg, changes.maxLoadKg())
.set(VehicleRecord::getMaxVolumeCbm, changes.maxVolumeCbm())
.set(VehicleRecord::getFuelConsumptionPer100Km, changes.fuelConsumptionPer100Km())
.set(VehicleRecord::getMileageKm, changes.mileageKm())
.set(VehicleRecord::getDriverOrDispatchCompany, changes.driverOrDispatchCompany())
@@ -112,7 +118,7 @@ public class VehiclePersistenceAdapter implements VehicleRepository {
return new VehicleSnapshot(value.getId(), value.getPlateNumber(), value.getModel(),
value.getFuelConsumptionPer100Km(), value.getMileageKm(), value.getDriverOrDispatchCompany(), value.getPhone(),
value.getRegion(), value.getOwnership(), value.getStatus(), value.getRemark(), version(value.getRecordVersion()),
value.getUpdatedBy(), value.getUpdatedAt());
value.getUpdatedBy(), value.getUpdatedAt(), value.getMaxPalletSpaces(), value.getMaxLoadKg(), value.getMaxVolumeCbm());
}
private static long version(Long value) {
@@ -14,6 +14,9 @@ public class VehicleRecord {
@TableId(type = IdType.INPUT) private Long id;
private String plateNumber;
private String model;
private Integer maxPalletSpaces;
private BigDecimal maxLoadKg;
private BigDecimal maxVolumeCbm;
private BigDecimal fuelConsumptionPer100Km;
private Long mileageKm;
private String driverOrDispatchCompany;
@@ -3,6 +3,7 @@ package com.baiyue.lastleg.masterdata.vehicle.application;
import com.baiyue.common.core.api.PageResult;
import com.baiyue.lastleg.masterdata.vehicle.application.model.VehicleModels;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleAssignmentGuard;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository.DuplicatePlateException;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository.NewVehicle;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository.SearchCriteria;
@@ -24,9 +25,11 @@ public class VehicleApplicationService {
private static final Set<String> STATUSES = Set.of("IN_SERVICE", "DISPATCHED", "MAINTENANCE", "INACTIVE", "RETURNED");
private final VehicleRepository vehicles;
private final VehicleAssignmentGuard assignments;
public VehicleApplicationService(VehicleRepository vehicles) {
public VehicleApplicationService(VehicleRepository vehicles, VehicleAssignmentGuard assignments) {
this.vehicles = vehicles;
this.assignments = assignments;
}
public PageResult<VehicleModels.Response> page(VehicleModels.Query query) {
@@ -41,6 +44,7 @@ public class VehicleApplicationService {
@Transactional
public VehicleModels.Response create(String operator, VehicleModels.Create request) {
validateCapacity(request.maxPalletSpaces(), request.maxLoadKg(), request.maxVolumeCbm());
LocalDateTime now = LocalDateTime.now();
long id;
try {
@@ -48,7 +52,8 @@ public class VehicleApplicationService {
requiredText(request.plateNumber(), "车牌号").toUpperCase(Locale.ROOT),
requiredText(request.model(), "车型"), request.fuelConsumptionPer100Km(), request.mileageKm(),
trim(request.driverOrDispatchCompany()), trim(request.phone()), region(request.region()),
ownership(request.ownership()), status(request.status()), trim(request.remark()), operator, now));
ownership(request.ownership()), status(request.status()), trim(request.remark()), operator, now,
request.maxPalletSpaces(), request.maxLoadKg(), request.maxVolumeCbm()));
} catch (DuplicatePlateException exception) {
throw conflict("车牌号已存在");
}
@@ -57,16 +62,25 @@ public class VehicleApplicationService {
@Transactional
public VehicleModels.Response update(long id, String operator, VehicleModels.Update request) {
validateCapacity(request.maxPalletSpaces(), request.maxLoadKg(), request.maxVolumeCbm());
VehicleSnapshot current = locked(id);
requireVersion(current, request.recordVersion());
if (request.mileageKm() < current.mileageKm()) throw badRequest("当前公里码不能小于已有公里码");
if (!current.plateNumber().equals(requiredText(request.plateNumber(), "车牌号").toUpperCase(Locale.ROOT))
|| !current.model().equals(requiredText(request.model(), "车型")) || !current.region().equals(region(request.region()))
|| !current.ownership().equals(ownership(request.ownership()))
|| !java.util.Objects.equals(current.maxPalletSpaces(), request.maxPalletSpaces())
|| !sameDecimal(current.maxLoadKg(), request.maxLoadKg()) || !sameDecimal(current.maxVolumeCbm(), request.maxVolumeCbm())) {
assignments.requireUnassigned(id);
}
boolean updated;
try {
updated = vehicles.update(id, request.recordVersion(), new VehicleChanges(
requiredText(request.plateNumber(), "车牌号").toUpperCase(Locale.ROOT),
requiredText(request.model(), "车型"), request.fuelConsumptionPer100Km(), request.mileageKm(),
trim(request.driverOrDispatchCompany()), trim(request.phone()), region(request.region()),
ownership(request.ownership()), trim(request.remark()), operator, LocalDateTime.now()));
ownership(request.ownership()), trim(request.remark()), operator, LocalDateTime.now(),
request.maxPalletSpaces(), request.maxLoadKg(), request.maxVolumeCbm()));
} catch (DuplicatePlateException exception) {
throw conflict("车牌号已存在");
}
@@ -80,6 +94,7 @@ public class VehicleApplicationService {
requireVersion(current, request.recordVersion());
String status = status(request.status());
if (status.equals(current.status())) return response(current);
assignments.requireUnassigned(id);
boolean updated = vehicles.updateStatus(id, request.recordVersion(), status, operator, LocalDateTime.now());
if (!updated) throw conflict("车辆档案已被其他操作修改,请刷新后重试");
return detail(id);
@@ -87,11 +102,12 @@ public class VehicleApplicationService {
public byte[] exportCsv(VehicleModels.Query query) {
var rows = vehicles.list(criteria(query)).stream().map(this::response).toList();
StringBuilder csv = new StringBuilder("\uFEFF车辆ID,车牌号,车型,油耗(L/100km),当前公里码(km),司机或外派单位,联系电话,区域,车辆归属,状态,更新时间\r\n");
for (var row : rows) csv.append(row.id()).append(',').append(cell(row.plateNumber())).append(',')
StringBuilder csv = new StringBuilder("\uFEFF车牌号,车型,油耗(L/100km),当前公里码(km),司机或外派单位,联系电话,区域,车辆归属,状态,最大托位,最大载重(kg),可用容积(m³),更新时间\r\n");
for (var row : rows) csv.append(cell(row.plateNumber())).append(',')
.append(cell(row.model())).append(',').append(row.fuelConsumptionPer100Km()).append(',').append(row.mileageKm()).append(',')
.append(cell(row.driverOrDispatchCompany())).append(',').append(cell(row.phone())).append(',')
.append(row.region()).append(',').append(row.ownership()).append(',').append(row.status()).append(',')
.append(cell(row.maxPalletSpaces())).append(',').append(cell(row.maxLoadKg())).append(',').append(cell(row.maxVolumeCbm())).append(',')
.append(row.updatedAt()).append("\r\n");
return csv.toString().getBytes(StandardCharsets.UTF_8);
}
@@ -115,7 +131,17 @@ public class VehicleApplicationService {
return new VehicleModels.Response(String.valueOf(value.id()), value.plateNumber(), value.model(),
value.fuelConsumptionPer100Km(), value.mileageKm(), value.driverOrDispatchCompany(), value.phone(),
value.region(), value.ownership(), value.status(), value.remark(), value.recordVersion(),
value.updatedBy(), value.updatedAt());
value.updatedBy(), value.updatedAt(), value.maxPalletSpaces(), value.maxLoadKg(), value.maxVolumeCbm());
}
private static void validateCapacity(Integer pallets, java.math.BigDecimal weight, java.math.BigDecimal volume) {
if (pallets == null && weight == null && volume == null) return;
if (pallets == null || weight == null || volume == null || pallets < 1 || pallets > 10000
|| weight.signum() <= 0 || volume.signum() <= 0) throw badRequest("车辆托位、载重和容积须同时填写且大于零,或全部留空待确认");
}
private static boolean sameDecimal(java.math.BigDecimal first, java.math.BigDecimal second) {
return first == null ? second == null : second != null && first.compareTo(second) == 0;
}
private void requireVersion(VehicleSnapshot value, long expected) {
@@ -26,7 +26,10 @@ public final class VehicleModels {
@Size(max = 128) String driverOrDispatchCompany,
@Size(max = 64) String phone,
@NotBlank String region, @NotBlank String ownership,
@NotBlank String status, @Size(max = 1000) String remark) { }
@NotBlank String status, @Size(max = 1000) String remark,
@Min(1) @Max(10000) Integer maxPalletSpaces,
@DecimalMin(value = "0", inclusive = false) @Digits(integer = 9, fraction = 3) BigDecimal maxLoadKg,
@DecimalMin(value = "0", inclusive = false) @Digits(integer = 9, fraction = 3) BigDecimal maxVolumeCbm) { }
public record Update(@NotNull @Min(0) Long recordVersion,
@NotBlank @Size(max = 64) String plateNumber,
@@ -36,12 +39,16 @@ public final class VehicleModels {
@Size(max = 128) String driverOrDispatchCompany,
@Size(max = 64) String phone,
@NotBlank String region, @NotBlank String ownership,
@Size(max = 1000) String remark) { }
@Size(max = 1000) String remark,
@Min(1) @Max(10000) Integer maxPalletSpaces,
@DecimalMin(value = "0", inclusive = false) @Digits(integer = 9, fraction = 3) BigDecimal maxLoadKg,
@DecimalMin(value = "0", inclusive = false) @Digits(integer = 9, fraction = 3) BigDecimal maxVolumeCbm) { }
public record ChangeStatus(@NotBlank String status, @NotNull @Min(0) Long recordVersion) { }
public record Response(String id, String plateNumber, String model, BigDecimal fuelConsumptionPer100Km,
long mileageKm, String driverOrDispatchCompany, String phone, String region,
String ownership, String status, String remark, long recordVersion,
String updatedBy, LocalDateTime updatedAt) { }
String updatedBy, LocalDateTime updatedAt,
Integer maxPalletSpaces, BigDecimal maxLoadKg, BigDecimal maxVolumeCbm) { }
}
@@ -0,0 +1,6 @@
package com.baiyue.lastleg.masterdata.vehicle.application.port.out;
/** Called while the vehicle row is locked; fleet owns the active assignment. */
public interface VehicleAssignmentGuard {
void requireUnassigned(long vehicleId);
}
@@ -26,16 +26,19 @@ public interface VehicleRepository {
record NewVehicle(String plateNumber, String model, BigDecimal fuelConsumptionPer100Km, long mileageKm,
String driverOrDispatchCompany, String phone, String region, String ownership, String status,
String remark, String operator, LocalDateTime createdAt) { }
String remark, String operator, LocalDateTime createdAt,
Integer maxPalletSpaces, BigDecimal maxLoadKg, BigDecimal maxVolumeCbm) { }
record VehicleChanges(String plateNumber, String model, BigDecimal fuelConsumptionPer100Km, long mileageKm,
String driverOrDispatchCompany, String phone, String region, String ownership, String remark,
String operator, LocalDateTime updatedAt) { }
String operator, LocalDateTime updatedAt,
Integer maxPalletSpaces, BigDecimal maxLoadKg, BigDecimal maxVolumeCbm) { }
record VehicleSnapshot(long id, String plateNumber, String model, BigDecimal fuelConsumptionPer100Km,
long mileageKm, String driverOrDispatchCompany, String phone, String region,
String ownership, String status, String remark, long recordVersion,
String updatedBy, LocalDateTime updatedAt) { }
String updatedBy, LocalDateTime updatedAt,
Integer maxPalletSpaces, BigDecimal maxLoadKg, BigDecimal maxVolumeCbm) { }
final class DuplicatePlateException extends RuntimeException {
public DuplicatePlateException(Throwable cause) {
@@ -94,6 +94,15 @@ public final class OverseasPermissions {
public static final String VEHICLE_EDIT = "platform:overseas-master-data:vehicle:edit";
public static final String VEHICLE_STATUS = "platform:overseas-master-data:vehicle:status";
public static final String VEHICLE_EXPORT = "platform:overseas-master-data:vehicle:export";
public static final String VEHICLE_RECORD_CREATE = "platform:overseas-master-data:vehicle:record-create";
public static final String VEHICLE_RECORD_EDIT = "platform:overseas-master-data:vehicle:record-edit";
public static final String VEHICLE_RECORD_UPLOAD = "platform:overseas-master-data:vehicle:record-upload";
public static final String DRIVER_LIST = "platform:overseas-master-data:driver:list";
public static final String DRIVER_CREATE = "platform:overseas-master-data:driver:create";
public static final String DRIVER_EDIT = "platform:overseas-master-data:driver:edit";
public static final String DRIVER_STATUS = "platform:overseas-master-data:driver:status";
public static final String DRIVER_REVIEW = "platform:overseas-master-data:driver:review";
public static final String DRIVER_UPLOAD = "platform:overseas-master-data:driver:upload";
private OverseasPermissions() { }
}
@@ -0,0 +1,66 @@
package com.baiyue.lastleg.transfer.fleet;
import com.baiyue.lastleg.fleet.trip.FleetBookingIncomingGateway;
import com.baiyue.lastleg.fleet.trip.FleetDispatchGateway;
import com.baiyue.lastleg.transfer.service.WarehouseTransferService;
import com.baiyue.lastleg.transfer.dto.WarehouseTransferRequests;
import com.baiyue.lastleg.transfer.dto.WarehouseTransferResponses;
import com.baiyue.lastleg.transfer.mapper.WarehouseTransferOrderMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
@Component
public class FleetIncomingAdapter implements FleetBookingIncomingGateway {
private final WarehouseTransferService service;
private final WarehouseTransferOrderMapper orders;
private final ObjectMapper json;
public FleetIncomingAdapter(WarehouseTransferService service,WarehouseTransferOrderMapper orders,ObjectMapper json){this.service=service;this.orders=orders;this.json=json;}
@Override @Transactional(propagation=Propagation.MANDATORY)
public Evidence create(String operator,Incoming input){
boolean fba=input.cargo().destinationKey().startsWith("FBA:");
String code=fba?input.cargo().destinationKey().substring(4):null;
String key=FleetDispatchGateway.destinationKey(fba?"FBA":"PRIVATE",code,code,input.privateAddress(),input.postalCode());
if(!Objects.equals(key,input.cargo().destinationKey()))throw conflict("收货目的地与已确认外接卸货站不一致");
var request=new WarehouseTransferRequests.Create(null,List.of(),input.warehouseId(),code,
fba?"FBA":"PRIVATE",null,code,code,input.privateAddress(),input.postalCode(),input.recipientName(),input.recipientPhone(),
input.deliveryInstructions()==null||input.deliveryInstructions().isBlank()?"客户自送至"+input.warehouseName():input.deliveryInstructions(),
input.cargo().contactName(),input.cargo().contactPhone(),input.cargo().packageCount(),input.cargo().volumeCbm(),"CUSTOMER_DELIVERY",input.estimatedArrivalAt(),null,
null,null,null,"外接预订 "+input.bookingNo(),false,null,null,null,null,null,"FLEET:"+input.bookingNo()+":INCOMING",
List.of(new WarehouseTransferRequests.Item(null,input.cargo().cargoName(),input.cargo().packageCount(),null)),null);
var created=service.createAndSubmit(input.customerId(),operator,request);
var approved=service.review(input.customerId(),created.transferNo(),operator,new WarehouseTransferRequests.Review("APPROVE","外接承运已确认,按实际来货收货"));
return evidence(approved);
}
@Override @Transactional(propagation=Propagation.MANDATORY)
public Evidence inspect(String customerId,String incomingNo,boolean lock){
var row=lock?orders.lockNo(customerId,incomingNo):orders.findNo(customerId,incomingNo);
if(row==null)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"当前客户无此外接来货单");
return evidence(service.detail(customerId,incomingNo));
}
@Override @Transactional(propagation=Propagation.MANDATORY)
public Evidence confirm(String customerId,String incomingNo,String operator,String key){
var row=orders.lockNo(customerId,incomingNo);
if(row==null)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"外接来货单不存在");
if("READY_FOR_DISPATCH".equals(row.getStatus()))return evidence(service.detail(customerId,incomingNo));
return evidence(service.confirmMeasurement(customerId,incomingNo,operator,new WarehouseTransferRequests.CustomerConfirm(key,"运营代委托方确认外接实测货量")));
}
private Evidence evidence(WarehouseTransferResponses.Detail value){
var pallets=value.pallets().stream().filter(row->"COMPLETED".equals(row.status())).map(row->new Pallet(
row.warehousePalletId()==null?null:row.warehousePalletId().toString(),row.palletNo(),row.cartonCount(),row.grossWeightKg(),row.volumeCbm()))
.sorted(Comparator.comparing(row->Objects.requireNonNullElse(row.warehousePalletId(),""))).toList();
String destination=FleetDispatchGateway.destinationKey(value.destinationType(),value.destinationWarehouseCode(),value.fbaWarehouseCode(),value.privateDestinationAddress(),value.privateDestinationPostalCode());
int packages=pallets.stream().mapToInt(Pallet::packages).sum();
try{
String hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsString(Arrays.asList(value.transferNo(),value.inboundCode(),value.operatingWarehouseId(),destination,pallets)).getBytes(StandardCharsets.UTF_8)));
return new Evidence(value.transferNo(),value.inboundCode(),value.operatingWarehouseId(),destination,value.status(),hash,pallets,packages);
}catch(Exception error){throw new IllegalStateException(error);}
}
private static ResponseStatusException conflict(String reason){return new ResponseStatusException(HttpStatus.CONFLICT,reason);}
}
@@ -953,7 +953,7 @@ public class WarehouseTransferService {
String operationKey = "WAREHOUSE_TRANSFER_STOCK_IN:" + transfer.getTransferNo() + ":"
+ pallet.getSequenceNo() + ":" + item.getId();
InventoryCommandResponse result = inventory.stockIn(customerId, operatorId,
new InventoryCommandRequests.StockIn(customerId, "客户-" + customerId,
new InventoryCommandRequests.StockIn(customerId, "—",
transfer.getOperatingWarehouseId(), warehouse.warehouseCode(), warehouse.warehouseName(),
null, trim(transfer.getFbaWarehouseCode()), trim(transfer.getFbaWarehouseCode()),
transfer.getInboundOrderId(), transfer.getTransferNo(), transfer.getTransferNo(),
@@ -299,7 +299,7 @@ CREATE TABLE IF NOT EXISTS ll_delivery_order (
seller_name VARCHAR(128) NULL COMMENT '卖家姓名',
package_count INT NOT NULL DEFAULT 0 COMMENT '派送箱数',
pallet_count INT NOT NULL DEFAULT 0 COMMENT '派送托盘数',
total_weight_kg DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '总重量(千克)',
total_weight_kg DECIMAL(18,4) NULL COMMENT '总重量(千克),任一来源未确认时为空',
total_volume_cbm DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '总体积(立方米)',
planned_delivery_at DATETIME(3) NULL COMMENT '预计派送时间',
dispatched_at DATETIME(3) NULL COMMENT '实际派送时间',
@@ -968,7 +968,65 @@ CREATE TABLE IF NOT EXISTS ll_monthly_exchange_rate_history (
KEY idx_ll_exchange_rate_history (exchange_rate_id,created_at)
) ENGINE=InnoDB COMMENT='月度汇率变更历史';
CREATE TABLE ll_fleet_driver (
id BIGINT NOT NULL COMMENT '内部主键',
driver_no VARCHAR(32) NOT NULL COMMENT '司机业务编号',
warehouse_id BIGINT NULL COMMENT '所属公共仓库引用',
warehouse_code VARCHAR(64) NULL COMMENT '所属仓库编码快照',
warehouse_name VARCHAR(256) NULL COMMENT '所属仓库名称快照',
vehicle_models VARCHAR(128) NULL COMMENT '可驾驶车型描述',
languages_and_area VARCHAR(256) NULL COMMENT '语言及服务区域',
medical_expires_on DATE NULL COMMENT '体检到期日,当前不作为必需资质',
training_expires_on DATE NULL COMMENT '培训安全到期日,当前不作为必需资质',
insurance_expires_on DATE NULL COMMENT '保险到期日,当前不作为必需资质',
name VARCHAR(128) NOT NULL COMMENT '姓名',
phone VARCHAR(64) NOT NULL COMMENT '联系电话',
ownership VARCHAR(16) NOT NULL COMMENT '归属 OWNED自有 DISPATCHED外派',
region VARCHAR(16) NOT NULL COMMENT '区域 DOMESTIC国内 OVERSEAS海外',
active TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
review_status VARCHAR(16) NOT NULL DEFAULT 'PENDING' COMMENT '证照审核 PENDING待审 APPROVED通过 REJECTED打回',
license_number VARCHAR(128) NULL COMMENT '驾驶证编号',
license_type VARCHAR(64) NULL COMMENT '驾驶证类型',
license_issued_on DATE NULL COMMENT '驾驶证签发日期',
license_expires_on DATE NULL COMMENT '驾驶证有效截止日',
license_zone VARCHAR(64) NOT NULL COMMENT '证照有效日期的IANA时区',
license_file_id BIGINT NULL COMMENT '平台驾驶证文件引用',
remark VARCHAR(1000) NULL COMMENT '备注',
record_version BIGINT NOT NULL DEFAULT 0 COMMENT '并发版本',
created_by VARCHAR(64) NOT NULL COMMENT '创建人',
created_at DATETIME(3) NOT NULL COMMENT '创建时间UTC',
updated_by VARCHAR(64) NOT NULL COMMENT '修改人',
updated_at DATETIME(3) NOT NULL COMMENT '修改时间UTC',
PRIMARY KEY (id),
UNIQUE KEY uk_fleet_driver_no (driver_no),
KEY idx_fleet_driver_page (active,review_status,updated_at,id),
KEY idx_fleet_driver_expiry (license_expires_on),
CONSTRAINT chk_fleet_driver_ownership CHECK (ownership IN ('OWNED','DISPATCHED')),
CONSTRAINT chk_fleet_driver_region CHECK (region IN ('DOMESTIC','OVERSEAS')),
CONSTRAINT chk_fleet_driver_review CHECK (review_status IN ('PENDING','APPROVED','REJECTED')),
CONSTRAINT chk_fleet_driver_dates CHECK (license_issued_on IS NULL OR license_expires_on IS NULL OR license_issued_on <= license_expires_on)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台司机档案';
CREATE TABLE ll_fleet_driver_history (
id BIGINT NOT NULL COMMENT '内部主键',
driver_id BIGINT NOT NULL COMMENT '司机内部引用',
record_version BIGINT NOT NULL COMMENT '操作后的档案版本',
action VARCHAR(32) NOT NULL COMMENT '创建编辑启停证照上传及审核动作',
reason VARCHAR(1000) NULL COMMENT '操作原因或审核意见',
license_file_id BIGINT NULL COMMENT '当时驾驶证文件引用',
snapshot_json JSON NOT NULL COMMENT '操作后不可变档案快照',
operator_id VARCHAR(64) NOT NULL COMMENT '操作人',
occurred_at DATETIME(3) NOT NULL COMMENT '操作时间UTC',
PRIMARY KEY (id),
UNIQUE KEY uk_fleet_driver_history_version (driver_id,record_version),
KEY idx_fleet_driver_history_file (driver_id,license_file_id),
CONSTRAINT fk_fleet_driver_history_driver FOREIGN KEY (driver_id) REFERENCES ll_fleet_driver(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='司机档案及审核历史';
CREATE TABLE IF NOT EXISTS ll_vehicle (
max_pallet_spaces INT NULL COMMENT '最大标准托位,未知时为空',
max_load_kg DECIMAL(12,3) NULL COMMENT '最大载重,千克',
max_volume_cbm DECIMAL(12,3) NULL COMMENT '可用容积,立方米',
id BIGINT NOT NULL COMMENT '车辆档案ID', plate_number VARCHAR(64) NOT NULL COMMENT '车牌号',
model VARCHAR(128) NOT NULL COMMENT '车型', fuel_consumption_per100_km DECIMAL(10,2) NOT NULL COMMENT '百公里油耗,单位升',
mileage_km BIGINT NOT NULL COMMENT '当前公里码,单位公里', driver_or_dispatch_company VARCHAR(128) NULL COMMENT '司机姓名或外派单位',
@@ -979,9 +1037,181 @@ CREATE TABLE IF NOT EXISTS ll_vehicle (
created_by VARCHAR(128) NOT NULL COMMENT '创建人', updated_by VARCHAR(128) NOT NULL COMMENT '更新人',
created_at DATETIME(3) NOT NULL COMMENT '创建时间', updated_at DATETIME(3) NOT NULL COMMENT '更新时间',
PRIMARY KEY (id), UNIQUE KEY uk_ll_vehicle_plate (plate_number),
KEY idx_ll_vehicle_page (ownership,region,status,updated_at,id)
KEY idx_ll_vehicle_page (ownership,region,status,updated_at,id),
CONSTRAINT chk_ll_vehicle_capacity CHECK ((max_pallet_spaces IS NULL AND max_load_kg IS NULL AND max_volume_cbm IS NULL)
OR (max_pallet_spaces IS NOT NULL AND max_load_kg IS NOT NULL AND max_volume_cbm IS NOT NULL
AND max_pallet_spaces BETWEEN 1 AND 10000 AND max_load_kg > 0 AND max_volume_cbm > 0))
) ENGINE=InnoDB COMMENT='平台车辆主数据';
CREATE TABLE ll_fleet_vehicle_record (
id BIGINT NOT NULL COMMENT '记录内部主键',
record_no VARCHAR(32) NOT NULL COMMENT '车辆运维业务编号',
vehicle_id BIGINT NOT NULL COMMENT '所属车辆主键',
vehicle_plate VARCHAR(64) NOT NULL COMMENT '建档时车牌快照',
record_type VARCHAR(32) NOT NULL COMMENT '运维类型:保养、加油、维修、故障、救援、异常',
occurred_at DATETIME(3) NOT NULL COMMENT '记录发生时间(UTC)',
details_json JSON NOT NULL COMMENT '带明确单位的业务字段快照',
files_json JSON NOT NULL COMMENT '所属记录照片与上传幂等摘要',
idempotency_key VARCHAR(128) NOT NULL COMMENT '创建请求幂等键',
request_hash CHAR(64) NOT NULL COMMENT '原创建业务内容摘要',
record_version BIGINT NOT NULL DEFAULT 0 COMMENT '乐观锁版本',
created_by VARCHAR(64) NOT NULL COMMENT '创建操作人',
updated_by VARCHAR(64) NOT NULL COMMENT '最后操作人',
created_at DATETIME(3) NOT NULL COMMENT '创建时间(UTC)',
updated_at DATETIME(3) NOT NULL COMMENT '更新时间(UTC)',
PRIMARY KEY (id),
UNIQUE KEY uk_vehicle_record_no (record_no),
UNIQUE KEY uk_vehicle_record_creation (vehicle_id, created_by, idempotency_key),
KEY idx_vehicle_record_page (vehicle_id, record_type, occurred_at, id),
CONSTRAINT fk_vehicle_record_vehicle FOREIGN KEY (vehicle_id) REFERENCES ll_vehicle(id),
CONSTRAINT ck_vehicle_record_type CHECK (record_type IN ('MAINTENANCE','FUEL','REPAIR','BREAKDOWN','RESCUE','EXCEPTION'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='车辆运维记录';
CREATE TABLE ll_fleet_vehicle_record_history (
id BIGINT NOT NULL COMMENT '历史内部主键',
record_id BIGINT NOT NULL COMMENT '运维记录主键',
record_version BIGINT NOT NULL COMMENT '对应业务版本',
action VARCHAR(32) NOT NULL COMMENT '操作类型',
reason VARCHAR(1000) DEFAULT NULL COMMENT '更正原因或附件名称',
operator_id VARCHAR(64) NOT NULL COMMENT '操作人',
occurred_at DATETIME(3) NOT NULL COMMENT '操作时间(UTC)',
snapshot_json JSON NOT NULL COMMENT '当时完整业务快照',
PRIMARY KEY (id),
UNIQUE KEY uk_vehicle_record_revision (record_id, record_version),
CONSTRAINT fk_vehicle_record_history FOREIGN KEY (record_id) REFERENCES ll_fleet_vehicle_record(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='车辆运维记录不可变历史';
CREATE TABLE ll_fleet_trip (
id BIGINT NOT NULL COMMENT '内部主键',
trip_no VARCHAR(32) NOT NULL COMMENT '车次业务编号',
idempotency_key VARCHAR(128) NOT NULL COMMENT '创建请求幂等键',
request_hash VARCHAR(64) NOT NULL COMMENT '创建请求SHA256',
status VARCHAR(16) NOT NULL COMMENT '车次状态',
warehouse_id BIGINT NOT NULL COMMENT '起运公共仓库引用',
warehouse_code VARCHAR(64) NOT NULL COMMENT '起运仓编码快照',
warehouse_name VARCHAR(256) NOT NULL COMMENT '起运仓名称快照',
vehicle_id BIGINT NULL COMMENT '车辆档案引用',
vehicle_plate VARCHAR(64) NULL COMMENT '分配时车牌快照',
driver_id BIGINT NULL COMMENT '司机档案引用',
driver_name VARCHAR(128) NULL COMMENT '分配时司机姓名',
driver_phone VARCHAR(64) NULL COMMENT '分配时司机电话',
max_pallet_spaces INT NULL COMMENT '分配时托位容量快照',
max_load_kg DECIMAL(12,3) NULL COMMENT '分配时载重千克',
max_volume_cbm DECIMAL(12,3) NULL COMMENT '分配时可用容积立方米',
planned_departure_at DATETIME(3) NOT NULL COMMENT '计划发车UTC',
expected_driver_end_at DATETIME(3) NOT NULL COMMENT '司机预计任务结束UTC,含承担的返程转场',
departed_at DATETIME(3) NULL COMMENT '实际发车UTC',
completed_at DATETIME(3) NULL COMMENT '实际运输完成UTC',
stops_json JSON NOT NULL COMMENT '按顺序保存的路线站点',
planned_load_json JSON NULL COMMENT '拣货前自有货计划载荷与逐段剩余容量',
load_json JSON NULL COMMENT '已确认实物装载及客户货物来源快照',
loading_review_json LONGTEXT NULL COMMENT '整车理货审核快照,空值为待审核',
departure_key VARCHAR(128) NULL COMMENT '整车发车幂等标识',
departure_hash CHAR(64) NULL COMMENT '整车发车请求摘要',
departure_result_json JSON NULL COMMENT '整车发车结果及各客户出库结果',
completion_json JSON NULL COMMENT '货物结案来源及幂等结果快照',
vehicle_release_json JSON NULL COMMENT '车辆任务结束地点状态与幂等记录',
driver_release_json JSON NULL COMMENT '司机任务结束地点与幂等记录',
remark VARCHAR(1000) NULL COMMENT '备注',
record_version BIGINT NOT NULL DEFAULT 0 COMMENT '并发版本',
created_by VARCHAR(64) NOT NULL COMMENT '创建人',
created_at DATETIME(3) NOT NULL COMMENT '创建UTC时间',
updated_by VARCHAR(64) NOT NULL COMMENT '更新人',
updated_at DATETIME(3) NOT NULL COMMENT '更新UTC时间',
PRIMARY KEY (id),
UNIQUE KEY uk_fleet_trip_no (trip_no),
UNIQUE KEY uk_fleet_trip_create (created_by,idempotency_key),
KEY idx_fleet_trip_page (warehouse_id,status,updated_at,id),
CONSTRAINT fk_fleet_trip_vehicle FOREIGN KEY (vehicle_id) REFERENCES ll_vehicle(id),
CONSTRAINT fk_fleet_trip_driver FOREIGN KEY (driver_id) REFERENCES ll_fleet_driver(id),
CONSTRAINT chk_fleet_trip_status CHECK (status IN ('PLANNED','DEPARTING','IN_TRANSIT','COMPLETED','CANCELLED')),
CONSTRAINT chk_fleet_trip_time CHECK (expected_driver_end_at > planned_departure_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台运输车次';
CREATE TABLE ll_fleet_external_booking (
id BIGINT NOT NULL COMMENT '内部主键',
booking_no VARCHAR(32) NOT NULL COMMENT '外接预订业务编号',
trip_id BIGINT NOT NULL COMMENT '所属车次',
trip_no VARCHAR(32) NOT NULL COMMENT '车次业务编号',
customer_id VARCHAR(128) NOT NULL COMMENT '委托客户及付款归属',
customer_code VARCHAR(64) NOT NULL COMMENT '客户编号快照',
customer_name VARCHAR(255) NOT NULL COMMENT '客户名称快照',
status VARCHAR(16) NOT NULL COMMENT 'DRAFT询价/CONFIRMED占位/RECEIVED确认实收/BOUND关联发运/CANCELLED取消',
cargo_json JSON NOT NULL COMMENT '货物、计划载荷、联系人及约定报价快照',
destination_key VARCHAR(160) NOT NULL COMMENT '已有路线卸货站匹配键',
destination_label VARCHAR(255) NOT NULL COMMENT '约定卸货站名称',
agreed_amount DECIMAL(16,2) NULL COMMENT '约定金额,非已入账应收或实收',
idempotency_key VARCHAR(128) NOT NULL COMMENT '登记请求键',
request_hash CHAR(64) NOT NULL COMMENT '登记内容摘要',
confirm_key VARCHAR(128) NULL COMMENT '承运确认请求键',
confirm_hash CHAR(64) NULL COMMENT '承运确认摘要',
cancel_key VARCHAR(128) NULL COMMENT '取消请求键',
cancel_hash CHAR(64) NULL COMMENT '取消摘要',
incoming_no VARCHAR(64) NULL COMMENT '正式来货单业务编号',
dispatch_no VARCHAR(64) NULL COMMENT '已关联客户排车业务编号',
receipt_json JSON NULL COMMENT '实测来源及运营确认的托位和运费依据',
incoming_key VARCHAR(128) NULL COMMENT '来货登记请求键',
incoming_hash CHAR(64) NULL COMMENT '来货登记摘要',
receipt_key VARCHAR(128) NULL COMMENT '实收确认请求键',
receipt_hash CHAR(64) NULL COMMENT '实收确认摘要',
binding_key VARCHAR(128) NULL COMMENT '关联发运请求键',
binding_hash CHAR(64) NULL COMMENT '关联发运摘要',
record_version BIGINT NOT NULL DEFAULT 0 COMMENT '记录版本',
created_by VARCHAR(64) NOT NULL COMMENT '登记人',
created_at DATETIME(3) NOT NULL COMMENT '登记UTC时间',
updated_by VARCHAR(64) NOT NULL COMMENT '修改人',
updated_at DATETIME(3) NOT NULL COMMENT '修改UTC时间',
PRIMARY KEY(id),
UNIQUE KEY uk_fleet_booking_no(booking_no),
UNIQUE KEY uk_fleet_booking_create(trip_id,created_by,idempotency_key),
KEY idx_fleet_booking_trip(trip_id,status,id),
UNIQUE KEY uk_fleet_booking_incoming(incoming_no),
KEY idx_fleet_booking_dispatch(dispatch_no),
CONSTRAINT fk_fleet_booking_trip FOREIGN KEY(trip_id) REFERENCES ll_fleet_trip(id),
CONSTRAINT chk_fleet_booking_status CHECK(status IN ('DRAFT','CONFIRMED','RECEIVED','BOUND','CANCELLED'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='外接询价及确认承运占位;货物收发和费用入账分别引用正式事实';
CREATE TABLE ll_fleet_resource_assignment (
resource_kind VARCHAR(16) NOT NULL COMMENT '资源种类 VEHICLE或DRIVER',
resource_id BIGINT NOT NULL COMMENT '对应车辆或司机档案引用',
trip_id BIGINT NOT NULL COMMENT '占用车次',
trip_no VARCHAR(32) NOT NULL COMMENT '占用车次业务编号',
PRIMARY KEY (resource_kind,resource_id),
KEY idx_fleet_resource_trip (trip_id),
CONSTRAINT fk_fleet_resource_trip FOREIGN KEY (trip_id) REFERENCES ll_fleet_trip(id),
CONSTRAINT chk_fleet_resource_kind CHECK (resource_kind IN ('VEHICLE','DRIVER'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='车辆及司机当前车次占用,释放后删除锁行,历史保留在车次';
CREATE TABLE ll_fleet_trip_dispatch (
dispatch_id BIGINT NOT NULL COMMENT '客户排车单内部引用,唯一有效车次关联',
dispatch_no VARCHAR(64) NOT NULL COMMENT '客户排车业务单号',
customer_id VARCHAR(128) NOT NULL COMMENT '排车单自身客户归属',
trip_id BIGINT NOT NULL COMMENT '共享运输车次内部引用',
trip_no VARCHAR(32) NOT NULL COMMENT '共享运输车次业务编号',
package_count INT NOT NULL COMMENT '关联时待发运箱数快照',
bound_by VARCHAR(64) NOT NULL COMMENT '关联操作人',
bound_at DATETIME(3) NOT NULL COMMENT '关联UTC时间',
review_json LONGTEXT NULL COMMENT '客户排车调度审核快照,空值为待审核',
PRIMARY KEY (dispatch_id),
UNIQUE KEY uk_fleet_trip_dispatch_no (dispatch_no),
KEY idx_fleet_trip_dispatch_trip (trip_id,dispatch_id),
CONSTRAINT fk_fleet_trip_dispatch_trip FOREIGN KEY (trip_id) REFERENCES ll_fleet_trip(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='车次与各客户排车单的有效关联,解除前快照保留在车次历史';
CREATE TABLE ll_fleet_trip_history (
id BIGINT NOT NULL COMMENT '内部主键',
trip_id BIGINT NOT NULL COMMENT '车次内部引用',
record_version BIGINT NOT NULL COMMENT '操作后版本',
action VARCHAR(32) NOT NULL COMMENT '车次操作',
reason VARCHAR(1000) NULL COMMENT '操作原因',
operator_id VARCHAR(64) NOT NULL COMMENT '操作人',
occurred_at DATETIME(3) NOT NULL COMMENT '操作UTC时间',
snapshot_json JSON NOT NULL COMMENT '操作后不可变车次快照',
PRIMARY KEY (id),
UNIQUE KEY uk_fleet_trip_history_version (trip_id,record_version),
CONSTRAINT fk_fleet_trip_history FOREIGN KEY (trip_id) REFERENCES ll_fleet_trip(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='运输车次操作历史';
SET @ddl = (SELECT IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='ll_event_outbox' AND column_name='locked_at'), 'SELECT 1', 'ALTER TABLE ll_event_outbox ADD COLUMN locked_at DATETIME(3) NULL COMMENT ''投递租约获取时间'' AFTER published_at'));
PREPARE ll_outbox_lease_stmt FROM @ddl; EXECUTE ll_outbox_lease_stmt; DEALLOCATE PREPARE ll_outbox_lease_stmt;
SET @ddl = (SELECT IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='ll_event_outbox' AND column_name='locked_by'), 'SELECT 1', 'ALTER TABLE ll_event_outbox ADD COLUMN locked_by VARCHAR(128) NULL COMMENT ''投递租约持有者'' AFTER locked_at'));
@@ -1389,7 +1619,7 @@ CREATE TABLE IF NOT EXISTS ll_dispatch_item (
contact_name VARCHAR(128) NULL COMMENT '私人仓联系人快照',
contact_phone VARCHAR(64) NULL COMMENT '私人仓联系电话快照',
package_count INT NOT NULL DEFAULT 0 COMMENT '箱数',
gross_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '毛重(千克)',
gross_weight_kg DECIMAL(18,3) NULL COMMENT '毛重(千克),未知为NULL,不以材积重代替',
volume_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '材积重(千克)',
volume_cbm DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '体积(立方米)',
source_stage VARCHAR(32) NOT NULL COMMENT '数据来源阶段',
@@ -1510,13 +1740,14 @@ CREATE TABLE IF NOT EXISTS ll_outbound_order (
outbound_no VARCHAR(64) NOT NULL COMMENT '出库单号', dispatch_order_id BIGINT NULL COMMENT '派车单ID,一件代发为空', dispatch_no VARCHAR(64) NULL COMMENT '派车单号,一件代发为空',
overseas_warehouse_id VARCHAR(128) NULL COMMENT '海外仓ID', status VARCHAR(32) NOT NULL DEFAULT 'WAIT_OUTBOUND' COMMENT '业务状态',
package_count INT NOT NULL DEFAULT 0 COMMENT '箱数', pallet_count INT NOT NULL DEFAULT 0 COMMENT '托盘数',
gross_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '毛重(千克)', volume_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '材积重(千克)',
gross_weight_kg DECIMAL(18,3) NULL COMMENT '毛重(千克),来源未确认时为空', volume_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '材积重(千克)',
volume_cbm DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '体积(立方米)',
idempotency_key VARCHAR(255) NOT NULL COMMENT '业务幂等键', created_by VARCHAR(128) NULL COMMENT '创建人ID',
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间', updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新时间',
outbound_type VARCHAR(32) NOT NULL DEFAULT 'DISPATCH_DELIVERY' COMMENT '出库类型:派送转出库、一件代发', lx_codes VARCHAR(1000) NULL COMMENT '关联一件代发领星入库单代码汇总',
recipient_info VARCHAR(1000) NULL COMMENT '一件代发收件信息',
request_hash CHAR(64) NULL COMMENT '一件代发创建请求摘要,其他出库类型为空',
request_hash CHAR(64) NULL COMMENT '创建或转派送业务请求摘要,用于幂等内容校验',
fee_coverage_json JSON NULL COMMENT '本次发运引用的原费用版本、实际货物及明确服务覆盖确认快照',
PRIMARY KEY (id), UNIQUE KEY uk_ll_outbound_no (outbound_no),
UNIQUE KEY uk_ll_outbound_idempotency (customer_id,idempotency_key), UNIQUE KEY uk_ll_outbound_dispatch (customer_id,dispatch_order_id),
KEY idx_ll_outbound_list (customer_id,status,created_at)
@@ -1526,7 +1757,7 @@ CREATE TABLE IF NOT EXISTS ll_outbound_pallet_item (
id BIGINT NOT NULL COMMENT '主键ID', customer_id VARCHAR(128) NOT NULL COMMENT '客户租户ID', outbound_order_id BIGINT NOT NULL COMMENT '出库单ID',
warehouse_pallet_id BIGINT NULL COMMENT '仓库实物托盘ID', pallet_no VARCHAR(128) NULL COMMENT '托盘号',
destination_warehouse_id VARCHAR(128) NULL COMMENT '目的仓ID', destination_warehouse_code VARCHAR(128) NULL COMMENT '目的仓编码快照', destination_warehouse_name VARCHAR(255) NULL COMMENT '目的仓名称快照',
package_count INT NOT NULL DEFAULT 0 COMMENT '箱数', gross_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '毛重(千克)', volume_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '材积重(千克)', volume_cbm DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '体积(立方米)', picked_package_count INT NOT NULL DEFAULT 0 COMMENT '已拣箱数', status VARCHAR(32) NOT NULL DEFAULT 'WAIT_PICK' COMMENT '拣货状态', sku_code VARCHAR(128) NULL COMMENT '一件代发SKU', order_refs VARCHAR(2000) NULL COMMENT '关联订单信息', inbound_code VARCHAR(128) NULL COMMENT '入仓单号快照',
package_count INT NOT NULL DEFAULT 0 COMMENT '箱数', gross_weight_kg DECIMAL(18,3) NULL COMMENT '毛重(千克),来源未确认时为空', volume_weight_kg DECIMAL(18,3) NOT NULL DEFAULT 0 COMMENT '材积重(千克)', volume_cbm DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '体积(立方米)', picked_package_count INT NOT NULL DEFAULT 0 COMMENT '已拣箱数', status VARCHAR(32) NOT NULL DEFAULT 'WAIT_PICK' COMMENT '拣货状态', sku_code VARCHAR(128) NULL COMMENT '一件代发SKU', order_refs VARCHAR(2000) NULL COMMENT '关联订单信息', inbound_code VARCHAR(128) NULL COMMENT '入仓单号快照',
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间', PRIMARY KEY (id),
UNIQUE KEY uk_ll_outbound_pallet (customer_id,outbound_order_id,warehouse_pallet_id,inbound_code,sku_code),
KEY idx_ll_outbound_pallet_list (customer_id,outbound_order_id), KEY idx_ll_outbound_pallet_destination (customer_id,destination_warehouse_code)
@@ -5,7 +5,7 @@ info:
description: |
平台资料入口的customerId必须为真实派送所属客户;客户只读入口范围只取Token,只公开当前派送单已保存的RECEIPT签收文件,不提供上传、修改、历史版本、BOL或装车照片下载。
GET /delivery-orders 及 GET /delivery-orders/{deliveryNo} 的 order 行新增 bolNo 和 documentSummary,version/allowedActions 保持原契约。
RECEIPT 签收文件只有在 PUT 保存进入权威资料快照后才自动完成当前派送单;仅上传未保存不会完成。allowedActions 不再返回人工 COMPLETE_DELIVERY。
RECEIPT 签收文件只有在关联出库单已OUTBOUNDED、PUT保存进入权威资料快照后才自动完成当前派送单;仅上传未保存不会完成。发车前可保存BOL及装车资料,不能通过提前保存签收文件绕过实际出库。allowedActions 不再返回人工 COMPLETE_DELIVERY。
START_DELIVERY=DELIVERING(派送中);COMPLETE_DELIVERY=DELIVERED(完成并记录签收时间、生成待回访)。同状态重放不重复副作用。
资料不设必传门禁,不以三类齐全作为派送完成条件。业务失败使用统一 ApiResponse(A0422参数、A0409冲突),通常HTTP200。
security: [{ bearerAuth: [] }]
@@ -0,0 +1,310 @@
openapi: 3.0.3
info:
title: 平台车辆管理司机档案
version: 1.0.0
description: >-
平台司机主数据,列表权限包含详情、资格预览、历史和已关联证照读取。
写操作独立鉴权且要求当前recordVersion;创建版本0,后续每次成功写入递增。
证照或身份关键字段变化、替换附件后重新待审;电话和备注更正不撤销既有审核。
驾驶证是当前资格最低要求,其他资质不隐式必填。日期按licenseZone计算,
30天内到期但仍有效允许并提醒,任务结束达到有效截止日次日当地零点或更晚则禁止。
缺少预计结束时间时资格返回MISSING_TRIP_END;资格预览不预留司机,不代替发车事务复核。
新档案允许缺证照保存为PENDING,通过审核必须补齐编号、类型、有效期和真实附件。
所有业务错误遵循HTTP200加code,认证或基础设施错误可返回401/403/503。
security:
- bearerAuth: []
paths:
/api/platform/v1/last-leg/fleet/drivers:
get:
summary: 分页查询司机及资格
description: '权限:platform:overseas-master-data:driver:list;无逐行文件请求。'
parameters:
- {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}}
- {name: size, in: query, schema: {type: integer, minimum: 1, maximum: 200, default: 20}}
- {name: keyword, in: query, schema: {type: string, maxLength: 128}}
- {name: active, in: query, schema: {type: boolean}}
- {name: reviewStatus, in: query, schema: {type: string, enum: [PENDING, APPROVED, REJECTED]}}
- {name: ownership, in: query, schema: {type: string, enum: [OWNED, DISPATCHED]}}
- {name: region, in: query, schema: {type: string, enum: [DOMESTIC, OVERSEAS]}}
- {name: licenseState, in: query, schema: {type: string, enum: [MISSING, VALID, EXPIRING, EXPIRED]}, description: 仅驾驶证日期状态,与审核和附件状态分别展示}
- {name: expectedEnd, in: query, schema: {type: string, format: date-time}}
responses:
'200':
description: 业务响应,分页数据
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
records: {type: array, items: {$ref: '#/components/schemas/Driver'}}
page: {type: integer}
size: {type: integer}
total: {type: integer}
pages: {type: integer}
summary: {$ref: '#/components/schemas/Summary'}
post:
summary: 创建待审司机档案
description: '权限:platform:overseas-master-data:driver:create'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/Draft'}}}}
responses: {'200': {$ref: '#/components/responses/Driver'}}
/api/platform/v1/last-leg/fleet/drivers/warehouse-options:
get:
summary: 获取当前区域可关联的公共仓库
description: '权限:platform:overseas-master-data:driver:list;复用Warehouse内部有效目录,国内DOMESTIC,海外OVERSEAS/OVERSEAS_PARTNER,排除FBA目的仓;保存时再次校验。'
parameters:
- {name: region, in: query, required: true, schema: {type: string, enum: [DOMESTIC, OVERSEAS]}}
responses:
'200':
description: 业务响应,data为仓库候选
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data: {type: array, items: {$ref: '#/components/schemas/WarehouseOption'}}
/api/platform/v1/last-leg/fleet/drivers/{id}:
parameters: [{$ref: '#/components/parameters/Id'}]
get:
summary: 司机详情
description: '权限:platform:overseas-master-data:driver:list'
parameters:
- {name: expectedEnd, in: query, schema: {type: string, format: date-time}}
responses: {'200': {$ref: '#/components/responses/Driver'}}
put:
summary: 编辑档案,关键字段变化后重新待审
description: '权限:platform:overseas-master-data:driver:edit'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [recordVersion, details]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
details: {$ref: '#/components/schemas/Draft'}
responses: {'200': {$ref: '#/components/responses/Driver'}}
/api/platform/v1/last-leg/fleet/drivers/{id}/status:
parameters: [{$ref: '#/components/parameters/Id'}]
patch:
summary: 启停司机并记录原因
description: '权限:platform:overseas-master-data:driver:status;停用后不可派车,历史保留。'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [recordVersion, active, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
active: {type: boolean}
reason: {type: string, minLength: 1, maxLength: 1000}
responses: {'200': {$ref: '#/components/responses/Driver'}}
/api/platform/v1/last-leg/fleet/drivers/{id}/review:
parameters: [{$ref: '#/components/parameters/Id'}]
post:
summary: 通过或打回司机证照
description: '权限:platform:overseas-master-data:driver:review;仅PENDING允许审核;打回原因必填;通过前校验真实附件归属与证照有效性。'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [recordVersion, decision]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
decision: {type: string, enum: [APPROVED, REJECTED]}
reason: {type: string, maxLength: 1000}
responses: {'200': {$ref: '#/components/responses/Driver'}}
/api/platform/v1/last-leg/fleet/drivers/{id}/submit:
parameters: [{$ref: '#/components/parameters/Id'}]
post:
summary: 已打回档案重新提交
description: '权限:platform:overseas-master-data:driver:edit;仅REJECTED;先校验证照完整及文件归属。'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [recordVersion]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
responses: {'200': {$ref: '#/components/responses/Driver'}}
/api/platform/v1/last-leg/fleet/drivers/{id}/qualification:
parameters: [{$ref: '#/components/parameters/Id'}]
get:
summary: 按预计任务结束时间预览派车资格
description: '权限:platform:overseas-master-data:driver:list;预计结束应覆盖本司机承担的返程或转场。'
parameters:
- {name: expectedEnd, in: query, required: true, schema: {type: string, format: date-time}}
responses:
'200':
description: 资格结果,canDispatch与expiringSoon独立
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data: {$ref: '#/components/schemas/Qualification'}
/api/platform/v1/last-leg/fleet/drivers/{id}/history:
parameters: [{$ref: '#/components/parameters/Id'}]
get:
summary: 分页读取司机操作与审核历史
description: '权限:platform:overseas-master-data:driver:list;按版本降序,snapshot是历史当时的档案及资格,不能用作当前派车门禁。'
parameters:
- {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}}
- {name: size, in: query, schema: {type: integer, minimum: 1, maximum: 200, default: 20}}
responses:
'200':
description: 业务响应,data为含records/page/size/total/pages的分页
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
records: {type: array, items: {$ref: '#/components/schemas/History'}}
page: {type: integer}
size: {type: integer}
total: {type: integer}
pages: {type: integer}
/api/platform/v1/last-leg/fleet/drivers/{id}/license:
parameters: [{$ref: '#/components/parameters/Id'}]
post:
summary: 上传并绑定驾驶证,重置为待审
description: '权限:platform:overseas-master-data:driver:upload;复合归属固定平台0、FLEET_DRIVER_LICENSE、当前司机;非空PDF/JPG/PNG不超过10MiB,校验MIME和签名,旧版本附件保留在历史中。'
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [recordVersion, file]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
file: {type: string, format: binary}
responses: {'200': {$ref: '#/components/responses/Driver'}}
/api/platform/v1/last-leg/fleet/drivers/{id}/license/{fileId}:
parameters:
- {$ref: '#/components/parameters/Id'}
- {name: fileId, in: path, required: true, schema: {type: string, pattern: '^[1-9][0-9]*$'}}
get:
summary: 下载当前或历史已关联驾驶证
description: '权限:platform:overseas-master-data:driver:list;校验关联和File复合归属,attachment下载,Cache-Control no-store,拒绝未绑定文件。'
responses:
'200':
description: 文件内容;业务错误仍需识别JSON响应
content:
application/pdf: {schema: {type: string, format: binary}}
image/jpeg: {schema: {type: string, format: binary}}
image/png: {schema: {type: string, format: binary}}
components:
securitySchemes:
bearerAuth: {type: http, scheme: bearer, bearerFormat: JWT}
parameters:
Id: {name: id, in: path, required: true, schema: {type: string, pattern: '^[1-9][0-9]*$'}}
responses:
Driver:
description: 业务响应,data为司机详情
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data: {$ref: '#/components/schemas/Driver'}
schemas:
Envelope:
type: object
properties:
code: {type: string}
message: {type: string, nullable: true}
data: {type: object, nullable: true}
Draft:
type: object
required: [name, phone, ownership, region, licenseZone]
properties:
name: {type: string, minLength: 1, maxLength: 128}
phone: {type: string, minLength: 1, maxLength: 64}
ownership: {type: string, enum: [OWNED, DISPATCHED]}
region: {type: string, enum: [DOMESTIC, OVERSEAS]}
licenseNumber: {type: string, nullable: true, maxLength: 128}
licenseType: {type: string, nullable: true, maxLength: 64}
licenseIssuedOn: {type: string, format: date, nullable: true}
licenseExpiresOn: {type: string, format: date, nullable: true}
licenseZone: {type: string, maxLength: 64, description: IANA时区,如America/Los_Angeles}
remark: {type: string, nullable: true, maxLength: 1000}
profile: {$ref: '#/components/schemas/Profile'}
Profile:
type: object
nullable: true
description: 可选补充资料;当前其他资质日期不自动作为派车必需条件
properties:
warehouseId: {type: string, nullable: true, pattern: '^[1-9][0-9]*$'}
vehicleModels: {type: string, nullable: true, maxLength: 128}
languagesAndArea: {type: string, nullable: true, maxLength: 256}
medicalExpiresOn: {type: string, format: date, nullable: true}
trainingExpiresOn: {type: string, format: date, nullable: true}
insuranceExpiresOn: {type: string, format: date, nullable: true}
WarehouseOption:
type: object
properties:
id: {type: string}
code: {type: string}
name: {type: string}
region: {type: string, enum: [DOMESTIC, OVERSEAS]}
Summary:
type: object
description: 与列表共用筛选范围,按各证照时区计算30天(含)提醒,不以浏览器时区计算
properties:
total: {type: integer, format: int64}
owned: {type: integer, format: int64}
dispatched: {type: integer, format: int64}
expiringSoon: {type: integer, format: int64}
expired: {type: integer, format: int64}
Driver:
type: object
properties:
id: {type: string}
driverNo: {type: string, description: 独立生成的业务编号}
details: {$ref: '#/components/schemas/Draft'}
active: {type: boolean}
reviewStatus: {type: string, enum: [PENDING, APPROVED, REJECTED]}
licenseFileId: {type: string, nullable: true}
recordVersion: {type: integer, format: int64}
updatedBy: {type: string}
updatedAt: {type: string, description: UTC本地日期时间}
qualification: {$ref: '#/components/schemas/Qualification'}
licenseState: {type: string, enum: [MISSING, VALID, EXPIRING, EXPIRED]}
warehouseCode: {type: string, nullable: true}
warehouseName: {type: string, nullable: true}
Qualification:
type: object
properties:
canDispatch: {type: boolean}
expiringSoon: {type: boolean}
reason:
type: string
enum: [ELIGIBLE, INACTIVE, MISSING_LICENSE, MISSING_EXPIRY, PENDING_REVIEW, REJECTED, EXPIRED, MISSING_TRIP_END, INVALID_TRIP_END, EXPIRES_DURING_TRIP]
licenseExpiresOn: {type: string, format: date, nullable: true}
History:
type: object
properties:
recordVersion: {type: integer, format: int64}
action: {type: string, enum: [CREATE, UPDATE, ACTIVATE, DEACTIVATE, UPLOAD_LICENSE, APPROVED, REJECTED, RESUBMIT]}
reason: {type: string, nullable: true}
operatorId: {type: string}
occurredAt: {type: string, description: UTC本地日期时间}
snapshot: {$ref: '#/components/schemas/Driver'}
@@ -0,0 +1,649 @@
openapi: 3.0.3
info:
title: 平台运输车次与资源分配
version: 1.0.0
description: >-
车次是一次实际运输的稳定业务编号,客户排车、库存和派送单继续保留各自客户归属。
本文件定义计划、资源分配及客户排车单关联命令;分配或关联不会扣库存或标记发车。
创建可暂不指定车与司机,幂等键按创建人隔离;相同键相同内容返回同一车次,不同内容拒绝。
正式分配要求在役海外车辆及已确认的托位/载重/容积,以及海外司机;司机按预计任务结束时间重新核验且验证证照文件。
发车预览与实际发车重新核对司机当前海外区域和身份;分配后档案变更不能沿用原分配时的资格结果。
一个车辆或司机同时只能占用一个未释放车次;当前不提供多个未来时段的并行预约。
改派先取得新资源,成功后释放旧资源;整次写入与历史处于同一事务。
司机预计结束包含承担的返程/转场;修改预计结束须重新核验司机,所有写命令使用recordVersion。
普通计划接口不提供修改发车或签收状态的入口;PDA统一发车,结案检查所有客户派送终态及实发数量。
货物结案不释放车辆或司机;结束各资源任务独立提交实际结束时间、地点和原因,车辆另确认可用/维修/停用/已归还状态。
结案和结束任务命令携带版本及幂等键;结束司机任务不要求其证照仍有效,也不自动恢复其派车资格。
关联要求已分配车和司机,客户排车单同起运仓且未开始拣货;可跨客户关联但不改变客户数据归属。
同一排车单唯一关联一个车次;关联、改派、解除及尚未执行的派送单车/司机快照同步使用同一事务。
关联后子排车不能独立编辑、取消或单独发车;取消车次前须解除关联,已开工不允许直接解除或变更路线。
发车前允许在车次统一换车、换司机或调整时间,保留全部拣货事实与客户归属;已确认装载须能容纳于替换车辆。
改派或调整计划使原装载确认失效,发车前须重新确认;不支持用计划接口处理在途换车或撤销已执行货物。
关联只建立执行单据关系,不代表实际装载量、容量核验或审核已完成。
每张客户排车单调度审核通过后允许新拣货;整车确认实际装载并通过理货审核后允许发车。
审核仅通过或打回,通过意见选填、打回原因必填;无需额外提交或不同审核人。
换车换司机、修改路线或时间使调度与理货审核待审;仅修改备注保留审核及装载。
关联变更、重新确认装载或重新审核客户排车单使理货审核待审;保留全部拣货事实及历史审核快照。
security:
- bearerAuth: []
paths:
/api/platform/v1/last-leg/fleet/trips:
get:
summary: 分页查询车次
description: '权限:platform:fleet:trip:list'
parameters:
- {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}}
- {name: size, in: query, schema: {type: integer, minimum: 1, maximum: 200, default: 20}}
- {name: keyword, in: query, schema: {type: string, maxLength: 128}, description: 车次号/车牌/司机}
- {name: status, in: query, schema: {type: string, enum: [PLANNED, IN_TRANSIT, COMPLETED, CANCELLED]}}
- {name: warehouseId, in: query, schema: {type: string, pattern: '^[1-9][0-9]*$'}}
responses:
'200':
description: 统一业务响应,data包含records/page/size/total/pages;不逐行请求司机详情
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
records: {type: array, items: {$ref: '#/components/schemas/Trip'}}
page: {type: integer}
size: {type: integer}
total: {type: integer}
pages: {type: integer}
post:
summary: 幂等创建车次计划
description: '权限:platform:fleet:trip:create;起运仓使用公共有效海外仓目录;不推断GPS路线。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/Create'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/customer-options:
get:
summary: 查询有效委托客户候选
description: '权限:platform:fleet:trip:list;读取IAM当前客户主档;不使用采购历史或允许输入不存在的客户。'
parameters: [{name: keyword, in: query, schema: {type: string}}]
responses: {'200': {description: 统一响应data为客户id/code/name/contactName/contactPhone数组}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/bookings:
parameters: [{$ref: '#/components/parameters/TripNo'}]
get:
summary: 查询本车外接询价与承运预订
description: '权限:platform:fleet:trip:list;返回tripRecordVersion及records;约定金额不是应收或实收。'
responses: {'200': {description: 统一响应data为版本及Booking数组}}
post:
summary: 登记外接询价
description: '权限:platform:fleet:trip:booking-create;DRAFT不占位。客户由IAM校验,报价和预计载荷可待确认再补;起点固定本起运仓,卸货站为既有路线站点。相同创建键与内容重放原预订。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BookingCreate'}}}}
responses: {'200': {$ref: '#/components/responses/BookingResult'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/bookings/{bookingNo}:
parameters: [{$ref: '#/components/parameters/TripNo'}, {$ref: '#/components/parameters/BookingNo'}]
put:
summary: 编辑尚未确认的外接询价
description: '权限:platform:fleet:trip:booking-edit;仅DRAFT;客户与预订业务编号不变,更新前核对车次及预订版本。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BookingUpdate'}}}}
responses: {'200': {$ref: '#/components/responses/BookingResult'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/bookings/{bookingNo}/confirm:
parameters: [{$ref: '#/components/parameters/TripNo'}, {$ref: '#/components/parameters/BookingNo'}]
post:
summary: 确认外接承运并占用计划容量
description: '权限:platform:fleet:trip:booking-confirm;父车次锁内核对来源仍有效的自有货容量计划及全部已确认预订;报价/币种/预计托位重量体积完整。幂等重放返回当前预订事实,不重复占位;确认不代表已收货、已发运或已入财务。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BookingCommand'}}}}
responses: {'200': {$ref: '#/components/responses/BookingResult'}, '409': {description: 版本、资格或容量不满足}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/bookings/{bookingNo}/incoming:
parameters: [{$ref: '#/components/parameters/TripNo'}, {$ref: '#/components/parameters/BookingNo'}]
get:
summary: 查询外接来货及实际测量依据
description: '权限:platform:fleet:trip:list;固定预订客户范围,返回tripRecordVersion、recordVersion与incoming;尚未登记时incoming为null,不逐行预取。'
responses: {'200': {description: 统一响应data为版本及IncomingEvidence}}
post:
summary: 为已确认承运生成真实来货单
description: '权限:platform:fleet:trip:booking-edit;复用仓储转运创建/审核,在同一事务建立客户自送来货并关联预订;不写库存,不冒充实收;已有来货拒绝重复创建,同键同内容重放。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BookingIncoming'}}}}
responses: {'200': {$ref: '#/components/responses/BookingResult'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/bookings/{bookingNo}/receipt-confirmation:
parameters: [{$ref: '#/components/parameters/TripNo'}, {$ref: '#/components/parameters/BookingNo'}]
post:
summary: 运营确认委托方实收货量与运费
description: '权限:platform:fleet:trip:booking-confirm;实际来货已完成测量,receiptHash和实托集合一致,重新核算容量和约定金额,引用真实收货证据并确认原来货流程;不重复入库。差异必须显式确认,超容量回滚。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BookingAcceptReceipt'}}}}
responses: {'200': {$ref: '#/components/responses/BookingResult'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/bookings/{bookingNo}/dispatch:
parameters: [{$ref: '#/components/parameters/TripNo'}, {$ref: '#/components/parameters/BookingNo'}]
post:
summary: 将外接实收货物关联客户排车
description: '权限:同时要求platform:fleet:trip:booking-edit和platform:fleet:trip:edit;排车必须同客户同仓,完整包含预订来货的实收托盘与数量且目的地一致;原子绑定共享车次,防止绕过预订挂到其他车次。解除未开工关联后回到RECEIVED并重新预留容量,已拣货不允许直接解除。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BookingBindDispatch'}}}}
responses: {'200': {$ref: '#/components/responses/BookingResult'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/bookings/{bookingNo}/cancel:
parameters: [{$ref: '#/components/parameters/TripNo'}, {$ref: '#/components/parameters/BookingNo'}]
post:
summary: 取消未执行的外接预订并释放容量
description: '权限:platform:fleet:trip:booking-cancel;仅计划中车次的DRAFT/CONFIRMED/RECEIVED;只释放承运预留,不删除来货或库存;同键同内容重放不重复释放,历史保留报价及承运确认。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BookingCommand'}}}}
responses: {'200': {$ref: '#/components/responses/BookingResult'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}:
parameters: [{$ref: '#/components/parameters/TripNo'}]
get:
summary: 查询车次详情和当前司机资格
description: '权限:platform:fleet:trip:list;司机资格仅是详情预览,实际命令必须重新核验。'
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/dispatches/{dispatchNo}/review:
parameters:
- {$ref: '#/components/parameters/TripNo'}
- {name: dispatchNo, in: path, required: true, schema: {type: string}}
post:
summary: 通过或打回单张客户排车调度审核
description: '权限:platform:fleet:trip:dispatch-review;仅PLANNED;审核所属车次内的排车单,成功后理货审核待审;审批不扣库存。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/Review'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}, '409': {description: 版本、关联或资格冲突}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/loading-review:
parameters: [{$ref: '#/components/parameters/TripNo'}]
post:
summary: 通过或打回整车理货审核
description: '权限:platform:fleet:trip:loading-review;仅PLANNED;通过要求全部调度审核、拣货和实际装载确认已完成,当前司机资格有效。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/Review'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}, '409': {description: 版本、调度审核、装载或资格冲突}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/plan:
parameters: [{$ref: '#/components/parameters/TripNo'}]
put:
summary: 修改计划时间和路线
description: '权限:platform:fleet:trip:edit;仅PLANNED;司机预计结束变更重新核验;原因必填。已开始拣货时路线须完全一致,仅可调整时间和备注;调整时间使审核及装载确认失效,仅修改备注保留。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/Plan'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/assignment:
parameters: [{$ref: '#/components/parameters/TripNo'}]
post:
summary: 分配或更换车辆与司机
description: '权限:platform:fleet:trip:assign;仅PLANNED且全部关联单未发车、未出库;允许已拣货时统一改派并同步派送快照,保留拣货和到达时间。替换车辆须满足已确认装载容量,成功后清除原装载确认并重新核验;行锁和唯一占用键防重复派车,资格校验不得通过人工审核绕过。'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [recordVersion, vehicleId, driverId, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
vehicleId: {type: string, pattern: '^[1-9][0-9]*$'}
driverId: {type: string, pattern: '^[1-9][0-9]*$'}
reason: {type: string, minLength: 1, maxLength: 1000}
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/cancel:
parameters: [{$ref: '#/components/parameters/TripNo'}]
post:
summary: 取消计划并释放车和司机
description: '权限:platform:fleet:trip:cancel;仅PLANNED;保留车次快照和历史。已执行货物后续须按实际执行状态校验,不允许取消抹除作业事实。'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [recordVersion, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
reason: {type: string, minLength: 1, maxLength: 1000}
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/dispatches/bind:
parameters: [{$ref: '#/components/parameters/TripNo'}]
post:
summary: 将客户排车单关联到车次
description: '权限:platform:fleet:trip:edit;按业务单号解析客户归属,同仓且未开工;关联和车/司机快照同步原子提交。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BindingCommand'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/dispatches/unbind:
parameters: [{$ref: '#/components/parameters/TripNo'}]
post:
summary: 解除尚未执行的客户排车单关联
description: '权限:platform:fleet:trip:edit;清除排车及派送单当前车辆司机快照,历史保留;已拣货禁止直接解除。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/BindingCommand'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/history:
parameters: [{$ref: '#/components/parameters/TripNo'}]
get:
summary: 分页读取车次操作历史
description: '权限:platform:fleet:trip:list;版本倒序;不将历史快照当作当前资格。'
parameters:
- {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}}
- {name: size, in: query, schema: {type: integer, minimum: 1, maximum: 200, default: 20}}
responses:
'200':
description: 统一响应;data为PageResult,records项包含recordVersion/action/reason/operatorId/occurredAt/snapshot,snapshot包含trip、带review的dispatches、capacityPlan、confirmedLoad、completion及loadingReview、externalBookings不可变快照
/api/platform/v1/last-leg/fleet/trips/{tripNo}/capacity-plan:
parameters: [{$ref: '#/components/parameters/TripNo'}]
get:
summary: 读取拣货前计划载荷和逐段余位
description: '权限:platform:fleet:trip:list;按当前关联货物返回manifestHash;planValid为false表示尚未核对或来源已经变化,不能据旧计划承诺外接运力。'
responses:
'200': {description: 统一响应data为Planning, content: {application/json: {schema: {$ref: '#/components/schemas/PlanningEnvelope'}}}}
post:
summary: 核对本车货物计划载荷
description: '权限:platform:fleet:trip:edit;仅PLANNED;允许尚未拣货或审核,通过实托去重及逐段容量检查。保存计划不推进审核、库存或发车,不代替实际装载确认;调整计划/资源/关联使容量计划失效,纯备注保留。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/ConfirmLoad'}}}}
responses:
'200': {description: 已保存容量计划, content: {application/json: {schema: {$ref: '#/components/schemas/PlanningEnvelope'}}}}
'409': {description: 版本、来源变化或容量超限}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/loading:
parameters: [{$ref: '#/components/parameters/TripNo'}]
get:
summary: 读取整车实物装载核对依据
description: '权限:platform:fleet:trip:list;返回各客户货物组成、manifestHash和当前装载确认,实际重量不得使用计费材积重。'
responses:
'200': {description: 统一响应data为Loading, content: {application/json: {schema: {$ref: '#/components/schemas/LoadingEnvelope'}}}}
post:
summary: 确认整车实际装载及逐段容量
description: '权限:platform:fleet:trip:edit;全部客户拣货核平且转派送后确认;同一实物托盘只计量一次。货物hash或车次版本变化拒绝,托盘卸货站须匹配原货物目的地。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/ConfirmLoad'}}}}
responses:
'200': {description: 已确认装载快照,统一响应data为Loading, content: {application/json: {schema: {$ref: '#/components/schemas/LoadingEnvelope'}}}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/completion:
parameters: [{$ref: '#/components/parameters/TripNo'}]
get:
summary: 核对各客户货物是否全部结束履约
description: '权限:platform:fleet:trip:list;返回tripNo、recordVersion、canComplete、blockReason、outcomes。签收以signedAt为准,退回须有RETURN_COMPLETED操作事实,不以updatedAt代替实际终态时间。'
responses:
'200': {description: 统一响应data包含结案检查结果与逐张派送Outcome, content: {application/json: {schema: {$ref: '#/components/schemas/CompletionEnvelope'}}}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/complete:
parameters: [{$ref: '#/components/parameters/TripNo'}]
post:
summary: 核对全部货物并结案车次
description: '权限:platform:fleet:trip:complete;仅IN_TRANSIT,实发数量由全部已签收或已真实退回派送单覆盖;拒收、待退回、取消不算终态完成。不改写客户单、不新增收费、不释放资源;同键同内容重放,旧版本或不同内容拒绝。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/Complete'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}}
/api/platform/v1/last-leg/fleet/trips/{tripNo}/resources/release:
parameters: [{$ref: '#/components/parameters/TripNo'}]
post:
summary: 单独结束车辆或司机本次任务并释放占用
description: '权限:platform:fleet:trip:release;货物结案后才允许;实际结束时间不早于货物完成且不晚于当前时间,地点及原因必填。车辆状态与释放同事务更新;司机可继续返程而保持占用。原请求重放不释放后来另一个车次的占用。'
requestBody: {required: true, content: {application/json: {schema: {$ref: '#/components/schemas/Release'}}}}
responses: {'200': {$ref: '#/components/responses/Detail'}}
components:
securitySchemes:
bearerAuth: {type: http, scheme: bearer, bearerFormat: JWT}
parameters:
BookingNo:
name: bookingNo
in: path
required: true
schema: {type: string}
TripNo: {name: tripNo, in: path, required: true, schema: {type: string}}
responses:
BookingResult:
description: 统一响应data含tripRecordVersion、booking及replayed;客户端使用当前状态,重放不覆盖后续已发生的取消
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
tripRecordVersion: {type: integer, format: int64}
booking: {$ref: '#/components/schemas/Booking'}
replayed: {type: boolean}
Detail:
description: 统一响应,code为200代表成功,data为车次详情;业务冲突使用业务错误,不降级为成功
content:
application/json:
schema:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
trip: {$ref: '#/components/schemas/Trip'}
dispatches: {type: array, items: {$ref: '#/components/schemas/DispatchBinding'}}
loadingReview: {$ref: '#/components/schemas/ReviewState'}
driverQualification:
type: object
nullable: true
description: 未分配司机为null;字段与fleet-drivers-v1的Qualification一致
properties:
canDispatch: {type: boolean}
expiringSoon: {type: boolean}
reason: {type: string}
licenseExpiresOn: {type: string, format: date, nullable: true}
schemas:
BookingCargo:
type: object
required: [destinationKey, packageCount]
properties:
destinationKey: {type: string, maxLength: 160}
cargoName: {type: string, nullable: true, maxLength: 255}
packageCount: {type: integer, minimum: 1}
palletSpaces: {type: integer, nullable: true, minimum: 1}
weightKg: {type: number, nullable: true, minimum: 0.001}
volumeCbm: {type: number, nullable: true, minimum: 0.001}
priceBasis: {type: string, nullable: true, enum: [PALLET, ORDER], description: 为空时默认PALLET}
unitPrice: {type: number, nullable: true, minimum: 0, multipleOf: 0.01}
currency: {type: string, nullable: true, maxLength: 3}
contactName: {type: string, nullable: true, maxLength: 128}
contactPhone: {type: string, nullable: true, maxLength: 128}
remark: {type: string, nullable: true, maxLength: 1000}
IncomingEvidence:
type: object
properties:
incomingNo: {type: string}
inboundCode: {type: string}
warehouseId: {type: string}
destinationKey: {type: string}
status: {type: string}
receiptHash: {type: string, description: 实托、数量、实测值及来源匹配摘要,不包含可变作业状态}
receivedPackages: {type: integer}
pallets:
type: array
items:
type: object
properties:
warehousePalletId: {type: string}
palletNo: {type: string}
packages: {type: integer}
weightKg: {type: number, nullable: true}
volumeCbm: {type: number, nullable: true}
BookingIncoming:
allOf:
- {$ref: '#/components/schemas/BookingCommand'}
- properties:
estimatedArrivalAt: {type: string, format: date-time, nullable: true, description: 缺省为计划发车前2小时的预计值}
deliveryInstructions: {type: string, nullable: true, maxLength: 1000}
privateAddress: {type: string, nullable: true, maxLength: 1000}
postalCode: {type: string, nullable: true, maxLength: 32}
recipientName: {type: string, nullable: true, maxLength: 128}
recipientPhone: {type: string, nullable: true, maxLength: 64}
BookingPalletSpaces:
type: object
required: [warehousePalletId, palletSpaces]
properties:
warehousePalletId: {type: string}
palletSpaces: {type: integer, minimum: 1}
BookingAcceptReceipt:
allOf:
- {$ref: '#/components/schemas/BookingCommand'}
- required: [receiptHash, pallets, unitPrice]
properties:
receiptHash: {type: string}
pallets: {type: array, minItems: 1, items: {$ref: '#/components/schemas/BookingPalletSpaces'}}
unitPrice: {type: number, minimum: 0, multipleOf: 0.01}
BookingBindDispatch:
allOf:
- {$ref: '#/components/schemas/BookingCommand'}
- required: [dispatchNo]
properties:
dispatchNo: {type: string, maxLength: 64}
BookingCreate:
type: object
required: [tripRecordVersion, customerId, cargo, idempotencyKey]
properties:
tripRecordVersion: {type: integer, format: int64, minimum: 0}
customerId: {type: string, pattern: '^[1-9][0-9]*$'}
cargo: {$ref: '#/components/schemas/BookingCargo'}
idempotencyKey: {type: string, minLength: 8, maxLength: 128}
BookingUpdate:
type: object
required: [tripRecordVersion, recordVersion, cargo]
properties:
tripRecordVersion: {type: integer, format: int64, minimum: 0}
recordVersion: {type: integer, format: int64, minimum: 0}
cargo: {$ref: '#/components/schemas/BookingCargo'}
BookingCommand:
type: object
required: [tripRecordVersion, recordVersion, idempotencyKey]
properties:
tripRecordVersion: {type: integer, format: int64, minimum: 0}
recordVersion: {type: integer, format: int64, minimum: 0}
idempotencyKey: {type: string, minLength: 8, maxLength: 128}
reason: {type: string, nullable: true, maxLength: 1000}
Booking:
type: object
properties:
bookingNo: {type: string}
tripNo: {type: string}
customerId: {type: string}
customerCode: {type: string}
customerName: {type: string}
status: {type: string, enum: [DRAFT, CONFIRMED, RECEIVED, BOUND, CANCELLED]}
cargo: {$ref: '#/components/schemas/BookingCargo'}
destinationLabel: {type: string}
agreedAmount: {type: number, nullable: true, description: 约定运费,非财务应收或实收}
incomingNo: {type: string, nullable: true}
dispatchNo: {type: string, nullable: true}
receipt:
type: object
nullable: true
properties:
source: {$ref: '#/components/schemas/IncomingEvidence'}
pallets: {type: array, items: {$ref: '#/components/schemas/BookingPalletSpaces'}}
operatorId: {type: string}
confirmedAt: {type: string, format: date-time}
recordVersion: {type: integer, format: int64}
updatedAt: {type: string, format: date-time}
Outcome:
type: object
description: 本车原运输的结案依据;已签收后另发起退货仍保留本次运输DELIVERED及原signedAt,不修改后续退货单据状态。
properties:
dispatchNo: {type: string}
deliveryNo: {type: string}
customerId: {type: string}
destination: {type: string, nullable: true}
status: {type: string}
packages: {type: integer}
terminalAt: {type: string, format: date-time, nullable: true}
CompletionEnvelope:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
tripNo: {type: string}
recordVersion: {type: integer, format: int64}
canComplete: {type: boolean}
blockReason: {type: string, nullable: true}
outcomes: {type: array, items: {$ref: '#/components/schemas/Outcome'}}
Complete:
type: object
required: [recordVersion, idempotencyKey, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
idempotencyKey: {type: string, minLength: 8, maxLength: 128}
reason: {type: string, minLength: 1, maxLength: 1000}
Release:
type: object
required: [recordVersion, resourceKind, actualEndAt, endLocation, idempotencyKey, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
resourceKind: {type: string, enum: [VEHICLE, DRIVER]}
actualEndAt: {type: string, format: date-time}
endLocation: {type: string, minLength: 1, maxLength: 500}
vehicleStatus: {type: string, nullable: true, enum: [IN_SERVICE, MAINTENANCE, INACTIVE, RETURNED], description: 结束车辆任务必填,结束司机任务必须为空}
idempotencyKey: {type: string, minLength: 8, maxLength: 128}
reason: {type: string, minLength: 1, maxLength: 1000}
ReleaseInfo:
type: object
nullable: true
properties:
actualEndAt: {type: string, format: date-time}
endLocation: {type: string}
vehicleStatus: {type: string, nullable: true, description: 结束本次车辆任务时的状态快照,不代表车辆此后的实时可派状态}
LoadingEnvelope:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
tripNo: {type: string}
recordVersion: {type: integer, format: int64}
manifestHash: {type: string}
cargo: {type: array, items: {$ref: '#/components/schemas/Cargo'}}
blockReason: {type: string, nullable: true}
confirmedLoad:
type: object
nullable: true
properties:
manifestHash: {type: string}
cargo: {type: array, items: {$ref: '#/components/schemas/Cargo'}}
pallets: {type: array, items: {$ref: '#/components/schemas/Measurement'}}
segments: {type: array, items: {type: object}, description: 逐段fromIndex/toIndex及occupied/remaining托位、weightKg、volumeCbm}
operatorId: {type: string}
confirmedAt: {type: string, format: date-time}
Cargo:
type: object
properties:
dispatchNo: {type: string}
customerId: {type: string}
dispatchItemId: {type: string}
warehousePalletId: {type: string, nullable: true}
palletNo: {type: string, nullable: true}
packages: {type: integer}
destinationKey: {type: string, nullable: true, description: 原货物目的地稳定匹配键,选择路线站点时透传}
destinationLabel: {type: string, nullable: true}
Measurement:
type: object
required: [warehousePalletId, palletSpaces, weightKg, volumeCbm, deliveryIndex]
properties:
warehousePalletId: {type: string}
palletSpaces: {type: integer, minimum: 1}
weightKg: {type: number, minimum: 0.001, multipleOf: 0.001, maximum: 999999999.999}
volumeCbm: {type: number, minimum: 0.001, multipleOf: 0.001, maximum: 999999999.999}
deliveryIndex: {type: integer, minimum: 1, description: 卸货站索引,起运仓固定为0}
PlanningEnvelope:
allOf:
- {$ref: '#/components/schemas/Envelope'}
- properties:
data:
type: object
properties:
tripNo: {type: string}
recordVersion: {type: integer, format: int64}
cargo: {type: array, items: {$ref: '#/components/schemas/Cargo'}}
manifestHash: {type: string}
planValid: {type: boolean, description: 计划已经核对且来源hash仍一致}
availableSegments: {type: array, items: {$ref: '#/components/schemas/Segment'}, description: 当前自有货计划加已确认外接预订后的逐段占用与余位;计划失效返回空数组}
blockReason: {type: string, nullable: true}
capacityPlan:
type: object
nullable: true
description: 计划值,不能作为实际装载确认
properties:
manifestHash: {type: string}
cargo: {type: array, items: {$ref: '#/components/schemas/Cargo'}}
pallets: {type: array, items: {$ref: '#/components/schemas/Measurement'}}
segments: {type: array, items: {$ref: '#/components/schemas/Segment'}}
operatorId: {type: string}
confirmedAt: {type: string, format: date-time}
Segment:
type: object
properties:
fromIndex: {type: integer}
toIndex: {type: integer}
occupied: {$ref: '#/components/schemas/CapacityLoad'}
remaining: {$ref: '#/components/schemas/CapacityLoad'}
CapacityLoad:
type: object
properties:
palletSpaces: {type: integer}
weightKg: {type: number}
volumeCbm: {type: number}
ConfirmLoad:
type: object
required: [recordVersion, manifestHash, pallets, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
manifestHash: {type: string, pattern: '^[0-9a-f]{64}$'}
pallets: {type: array, minItems: 1, maxItems: 1000, items: {$ref: '#/components/schemas/Measurement'}}
reason: {type: string, minLength: 1, maxLength: 1000}
BindingCommand:
type: object
required: [recordVersion, dispatchNo, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
dispatchNo: {type: string, minLength: 1, maxLength: 64}
reason: {type: string, minLength: 1, maxLength: 1000}
Review:
type: object
required: [recordVersion, decision]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
decision: {type: string, enum: [APPROVED, REJECTED]}
reason: {type: string, nullable: true, maxLength: 1000, description: 通过选填;打回必填}
ReviewState:
type: object
required: [status]
properties:
status: {type: string, enum: [PENDING, APPROVED, REJECTED]}
reason: {type: string, nullable: true}
reviewerId: {type: string, nullable: true}
reviewedAt: {type: string, format: date-time, nullable: true}
recordVersion: {type: integer, format: int64, nullable: true, description: 本次审核所核对的车次版本}
DispatchBinding:
type: object
properties:
dispatchNo: {type: string}
customerId: {type: string, description: 排车单自身客户归属,由服务端解析}
packageCount: {type: integer, description: 关联时待发运箱数,不是实物托位数}
boundBy: {type: string}
boundAt: {type: string, format: date-time}
review: {$ref: '#/components/schemas/ReviewState'}
Envelope:
type: object
properties:
code: {type: string}
message: {type: string, nullable: true}
data: {type: object, nullable: true}
Stop:
type: object
required: [name]
properties:
name: {type: string, minLength: 1, maxLength: 128}
address: {type: string, nullable: true, maxLength: 500}
destinationKey: {type: string, nullable: true, maxLength: 160, description: 卸货站匹配Loading货物的destinationKey;未配置时可以保存计划但不能确认装载}
Create:
type: object
required: [warehouseId, plannedDepartureAt, expectedDriverEndAt, stops, idempotencyKey]
properties:
warehouseId: {type: string, pattern: '^[1-9][0-9]*$'}
plannedDepartureAt: {type: string, format: date-time}
expectedDriverEndAt: {type: string, format: date-time}
stops: {type: array, minItems: 2, maxItems: 200, items: {$ref: '#/components/schemas/Stop'}}
remark: {type: string, nullable: true, maxLength: 1000}
idempotencyKey: {type: string, minLength: 8, maxLength: 128}
Plan:
type: object
required: [recordVersion, plannedDepartureAt, expectedDriverEndAt, stops, reason]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
plannedDepartureAt: {type: string, format: date-time}
expectedDriverEndAt: {type: string, format: date-time}
stops: {type: array, minItems: 2, maxItems: 200, items: {$ref: '#/components/schemas/Stop'}}
remark: {type: string, nullable: true, maxLength: 1000}
reason: {type: string, minLength: 1, maxLength: 1000}
Trip:
type: object
properties:
tripNo: {type: string}
status: {type: string, enum: [PLANNED, IN_TRANSIT, COMPLETED, CANCELLED]}
warehouseId: {type: string}
warehouseCode: {type: string}
warehouseName: {type: string}
vehicleId: {type: string, nullable: true}
vehiclePlate: {type: string, nullable: true}
driverId: {type: string, nullable: true}
driverName: {type: string, nullable: true}
driverPhone: {type: string, nullable: true}
maxPalletSpaces: {type: integer, nullable: true}
maxLoadKg: {type: number, nullable: true}
maxVolumeCbm: {type: number, nullable: true}
plannedDepartureAt: {type: string, format: date-time}
expectedDriverEndAt: {type: string, format: date-time}
departedAt: {type: string, format: date-time, nullable: true}
completedAt: {type: string, format: date-time, nullable: true}
stops: {type: array, items: {$ref: '#/components/schemas/Stop'}}
remark: {type: string, nullable: true}
recordVersion: {type: integer, format: int64}
updatedAt: {type: string, format: date-time}
vehicleRelease: {$ref: '#/components/schemas/ReleaseInfo'}
driverRelease: {$ref: '#/components/schemas/ReleaseInfo'}
@@ -0,0 +1,175 @@
openapi: 3.0.3
info:
title: 车辆运维记录
version: 1.0.0
description: >-
平台车辆运维事实,支持保养、加油、维修、紧急故障、应急救援和异常。每条记录固定属于一辆车,使用VR业务编号;读取、修改、照片和历史均校验路径中的车辆归属。
原始里程必须明确KM或MI,加油量必须明确L、US_GAL或IMP_GAL;不自动推测或换算,不更新车辆主档公里数。
核验状态是人工记录的PENDING或VERIFIED,不代表财务审批或车辆可派,不自动产生账单、付款或变更车辆状态。
创建按车辆、操作者和幂等键去重;更正须版本及原因。照片上传按记录与幂等键去重并核对内容摘要,丢失响应可原样重试。
照片最多20张,每张非空JPG/PNG且最多10MiB;File按平台0、FLEET_VEHICLE_RECORD_PHOTO和记录内部主键复合归属,验证内容签名。
维修和救援项目、地点独立保存;处理中或已完成须有处理人,异常须有明确分类。
费用只是运维申报金额,填金额则必须填有效币种;未填金额和零金额有区别,不生成应付或付款。
维修/救援paymentStatus当前固定UNLINKED表示未关联财务,不得由processingStatus推定为已付款,其他类型为空。
不提供物理删除;编辑与上传历史同事务不可变保存。本接口不提供财务结算或车辆占用/状态自动变更。
security: [{bearerAuth: []}]
paths:
/api/platform/v1/last-leg/fleet/vehicles/{vehicleId}/records:
parameters: [{$ref: '#/components/parameters/Vehicle'}]
get:
summary: 分页查询当前车辆运维记录
description: '权限:platform:overseas-master-data:vehicle:list;按发生时间倒序,列表包含已关联照片元数据,不读取图片内容。'
parameters:
- {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}}
- {name: size, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 20}}
- {name: recordType, in: query, schema: {type: string, enum: [MAINTENANCE, FUEL, REPAIR, BREAKDOWN, RESCUE, EXCEPTION]}}
responses:
'200': {description: '统一响应data为records/page/size/total/pages,records元素为Record'}
post:
summary: 新增记录
description: '权限:platform:overseas-master-data:vehicle:record-create;同键同内容返回原记录,不同内容冲突。'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [idempotencyKey, details]
properties:
idempotencyKey: {type: string, minLength: 1, maxLength: 128}
details: {$ref: '#/components/schemas/Draft'}
responses:
'200': {$ref: '#/components/responses/Record'}
/api/platform/v1/last-leg/fleet/vehicles/{vehicleId}/records/{recordNo}:
parameters: [{$ref: '#/components/parameters/Vehicle'}, {$ref: '#/components/parameters/RecordNumber'}]
get:
summary: 读取记录详情
description: '权限:platform:overseas-master-data:vehicle:list;跨车辆记录返回404,不泄露其他车辆数据。'
responses:
'200': {$ref: '#/components/responses/Record'}
put:
summary: 更正记录
description: '权限:platform:overseas-master-data:vehicle:record-edit;类型及车辆不可更换,保留历史。'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [recordVersion, reason, details]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
reason: {type: string, minLength: 1, maxLength: 1000}
details: {$ref: '#/components/schemas/Draft'}
responses:
'200': {$ref: '#/components/responses/Record'}
/api/platform/v1/last-leg/fleet/vehicles/{vehicleId}/records/{recordNo}/files:
parameters: [{$ref: '#/components/parameters/Vehicle'}, {$ref: '#/components/parameters/RecordNumber'}]
post:
summary: 上传并关联运维图片
description: '权限:platform:overseas-master-data:vehicle:record-upload;记录保存成功后再上传,失败重试不得重复建记录。'
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [recordVersion, idempotencyKey, file]
properties:
recordVersion: {type: integer, format: int64, minimum: 0}
idempotencyKey: {type: string, minLength: 1, maxLength: 128}
file: {type: string, format: binary}
responses:
'200': {$ref: '#/components/responses/Record'}
/api/platform/v1/last-leg/fleet/vehicles/{vehicleId}/records/{recordNo}/files/{fileId}:
parameters:
- {$ref: '#/components/parameters/Vehicle'}
- {$ref: '#/components/parameters/RecordNumber'}
- {name: fileId, in: path, required: true, schema: {type: string, pattern: '^[1-9][0-9]*$'}}
get:
summary: 读取当前记录已关联图片
description: '权限:platform:overseas-master-data:vehicle:list;先校验记录关联,再校验File复合归属;no-store和nosniff,不返回存储路径。'
responses:
'200': {description: 图片字节, content: {image/png: {schema: {type: string, format: binary}}, image/jpeg: {schema: {type: string, format: binary}}}}
/api/platform/v1/last-leg/fleet/vehicles/{vehicleId}/records/{recordNo}/history:
parameters: [{$ref: '#/components/parameters/Vehicle'}, {$ref: '#/components/parameters/RecordNumber'}]
get:
summary: 分页读取不可变修改历史
description: '权限:platform:overseas-master-data:vehicle:list;版本倒序,仅按需读取。'
parameters:
- {name: page, in: query, schema: {type: integer, minimum: 1, default: 1}}
- {name: size, in: query, schema: {type: integer, minimum: 1, maximum: 100, default: 20}}
responses:
'200': {description: '统一响应data为分页对象;records包含recordVersion/action/reason/operatorId/occurredAt/snapshot,snapshot为Record'}
components:
securitySchemes:
bearerAuth: {type: http, scheme: bearer, bearerFormat: JWT}
parameters:
Vehicle: {name: vehicleId, in: path, required: true, schema: {type: string, pattern: '^[1-9][0-9]*$'}}
RecordNumber: {name: recordNo, in: path, required: true, schema: {type: string}}
responses:
Record:
description: 统一业务响应;失败保留code、message及诊断标识
content:
application/json:
schema:
type: object
properties:
code: {type: string}
data: {$ref: '#/components/schemas/Record'}
schemas:
Draft:
type: object
required: [recordType, occurredAt]
oneOf:
- properties: {recordType: {enum: [MAINTENANCE]}}
required: [distanceUnit, odometer, verificationStatus, lastServiceOdometer, nextServiceOdometer]
- properties: {recordType: {enum: [FUEL]}}
required: [distanceUnit, odometer, verificationStatus, fuelQuantity, fuelUnit]
- properties: {recordType: {enum: [REPAIR, BREAKDOWN, RESCUE, EXCEPTION]}}
required: [incident]
properties:
recordType: {type: string, enum: [MAINTENANCE, FUEL, REPAIR, BREAKDOWN, RESCUE, EXCEPTION]}
occurredAt: {type: string, format: date-time, description: 带偏移或Z的实际发生时间,不晚于当前时间,保存UTC}
distanceUnit: {type: string, nullable: true, enum: [KM, MI], description: 保养加油必填;其他类型必须为空}
odometer: {type: number, nullable: true, minimum: 0, multipleOf: 0.001, description: 保养加油必填;其他类型必须为空}
lastServiceOdometer: {type: number, nullable: true, minimum: 0, description: 保养必填,不大于记录时里程;加油必须为空}
nextServiceOdometer: {type: number, nullable: true, minimum: 0, description: 保养必填且大于上次保养里程,可低于当前里程表示已超保养里程;不默认一万迈}
fuelQuantity: {type: number, nullable: true, minimum: 0, exclusiveMinimum: true, description: 加油必填正数;保养必须为空}
fuelUnit: {type: string, nullable: true, enum: [L, US_GAL, IMP_GAL], description: 加油必填明确单位;保养必须为空}
verificationStatus: {type: string, nullable: true, enum: [PENDING, VERIFIED], description: 保养加油必填;其他类型必须为空,不能混作处理状态}
remark: {type: string, nullable: true, maxLength: 1000}
incident: {$ref: '#/components/schemas/Incident'}
Incident:
type: object
nullable: true
description: 维修/故障/救援/异常必填;保养加油必须为空,并禁止混入里程、加油或核验字段
required: [description, processingStatus]
properties:
description: {type: string, minLength: 1, maxLength: 2000}
item: {type: string, nullable: true, maxLength: 256, description: 维修或救援项目,此两类必填;其他类型为空}
place: {type: string, nullable: true, maxLength: 512, description: 维修或救援地点,此两类必填;其他类型为空}
handler: {type: string, nullable: true, maxLength: 128, description: 实际处理人;处理中或完成时必填,与系统操作人分别保留}
processingStatus: {type: string, enum: [PENDING, IN_PROGRESS, COMPLETED]}
exceptionType: {type: string, nullable: true, enum: [ROUTE, TIMEOUT, DELIVERY, VEHICLE_BREAKDOWN], description: 异常记录必填;其他类型为空}
reportedCost: {type: number, nullable: true, minimum: 0, multipleOf: 0.01, maximum: 999999999999.99, description: 仅维修/救援允许;空为未登记,零为已登记零费用,不表示付款}
currency: {type: string, nullable: true, pattern: '^[A-Z]{3}$', description: 金额非空时必填有效币种;未填金额时为空,不自动换算}
File:
type: object
properties:
fileId: {type: string}
fileName: {type: string}
contentType: {type: string, enum: [image/jpeg, image/png]}
sizeBytes: {type: integer, format: int64}
Record:
type: object
properties:
recordNo: {type: string}
vehicleId: {type: string}
vehiclePlate: {type: string, description: 建档时车牌快照}
details: {$ref: '#/components/schemas/Draft'}
files: {type: array, items: {$ref: '#/components/schemas/File'}}
recordVersion: {type: integer, format: int64, minimum: 0}
updatedBy: {type: string}
updatedAt: {type: string, format: date-time}
paymentStatus: {type: string, nullable: true, readOnly: true, enum: [UNLINKED], description: 维修/救援未关联财务时为UNLINKED,其余为空;不可用处理完成推定已付款}
@@ -600,14 +600,14 @@ paths:
'404': { description: 排车单不存在 }
put:
summary: 编辑待发车排车单
description: 权限 platform:overseas-warehouse:dispatch:edit;只按全局唯一 dispatchNo 锁定记录并从记录解析客户范围,不接收 customerId。仅允许 PENDING_DEPARTURE,且请求不包含 status/departAt,发车事实只能由 PDA 作业命令产生。
description: 权限 platform:overseas-warehouse:dispatch:edit;只按全局唯一 dispatchNo 锁定记录并从记录解析客户范围,不接收 customerId。仅允许 PENDING_DEPARTURE,且请求不包含 status/departAt,发车事实只能由 PDA 作业命令产生。已关联共享车次时拒绝独立编辑,须先按车次执行状态解除关联。
security: [{ bearerAuth: [] }]
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/DispatchUpdate' } } } }
responses: { '200': { description: 更新后的 DispatchResponse }, '404': { description: 排车单不存在 }, '409': { description: 排车单已执行或不可编辑 } }
delete:
summary: 取消待发车排车单
description: 权限 platform:overseas-warehouse:dispatch:cancel;只按全局唯一 dispatchNo 锁定记录并解析客户范围,不接收 customerId。仅 PENDING_DEPARTURE 可取消并释放正式托盘锁;重复取消幂等成功。
description: 权限 platform:overseas-warehouse:dispatch:cancel;只按全局唯一 dispatchNo 锁定记录并解析客户范围,不接收 customerId。仅 PENDING_DEPARTURE 可取消并释放正式托盘锁;重复取消幂等成功。已关联共享车次必须先解除关联,不能单独取消破坏整车计划。
security: [{ bearerAuth: [] }]
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
responses: { '200': { description: 取消成功或已取消 }, '404': { description: 排车单不存在 }, '409': { description: 排车已开始执行 } }
@@ -650,7 +650,7 @@ paths:
/api/platform/v1/last-leg/dispatches/{dispatchNo}/items/{itemId}:
delete:
summary: 移除已排车托盘
description: 权限 platform:overseas-warehouse:dispatch:edit;仅待发车、未拣货且尚未生成出库单时允许,成功后释放托盘锁并刷新排车汇总。
description: 权限 platform:overseas-warehouse:dispatch:edit;仅待发车、未拣货且尚未生成出库单时允许,成功后释放托盘锁并刷新排车汇总。已关联共享车次时须先解除关联。
security: [{ bearerAuth: [] }]
parameters:
- { name: dispatchNo, in: path, required: true, schema: { type: string } }
@@ -715,10 +715,82 @@ paths:
- { name: draftToken, in: path, required: true, schema: { type: string, maxLength: 64 } }
- { name: containerId, in: path, required: true, schema: { type: string } }
responses: { '200': { description: 空车厢删除成功 }, '409': { description: 车厢仍绑定托盘或草稿状态冲突 } }
/api/platform/v1/last-leg/dispatches/{dispatchNo}/fee-coverage:
get:
summary: 按实际发运来源查询原头程费用
description: 权限platform:overseas-warehouse:dispatch:list;只接收排车号,客户由服务端解析。按实物库存与本次已拣数量还原各票来源并核平排车箱数;合托不使用单一汇总入仓码代替全部来源。sourceComplete=false时不返回费用候选。Finance批量查询仅返回各票该客户原入仓单的已审核有效应收最新版本,存在来源不等于任何服务已包含,查询不会免收或新增费用。
security: [{ bearerAuth: [] }]
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
responses:
'200':
description: 来源核对结果与原费用候选
content:
application/json:
schema:
type: object
properties:
data:
type: object
properties:
dispatchNo: { type: string }
sourceComplete: { type: boolean }
blockReason: { type: string, nullable: true }
cargoHash: { type: string }
cargo:
type: array
items:
type: object
properties:
dispatchItemId: { type: string }
warehousePalletId: { type: string }
palletNo: { type: string, nullable: true }
orderId: { type: string }
sourceRegion: { type: string, nullable: true }
sourceInboundId: { type: string, nullable: true }
inboundCode: { type: string, nullable: true }
packages: { type: integer }
dispatchInboundCode: { type: string, nullable: true, description: 排车来源业务码;不能代替实物拆分后的各票inboundCode }
feeSources:
type: array
items:
type: object
properties:
financeFeeId: { type: string }
sourceFeeId: { type: string }
sourceType: { type: string }
sourceVersion: { type: integer }
customerId: { type: string }
sourceInboundId: { type: string }
inboundCode: { type: string, nullable: true }
feeItemCode: { type: string }
feeItemName: { type: string }
currency: { type: string }
amount: { type: number }
sourceHash: { type: string }
status: { type: string, enum: [AVAILABLE, SETTLED] }
'404': { description: 排车单不存在 }
'503': { description: Finance来源查询不可用或返回范围不一致 }
/api/platform/v1/last-leg/dispatches/{dispatchNo}/external-freight:
get:
summary: 读取本次排车的外接实收约定运费
description: 权限 platform:overseas-warehouse:dispatch:list;客户从排车单解析。逐票核对真实来货、车次关联、目的地及实收数量,返回不可变报价版本与货物摘要;查询不发布费用。
security: [{ bearerAuth: [] }]
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
responses:
'200':
description: 约定运费与是否仍需填写其余货物派送费用
content:
application/json:
schema:
type: object
properties:
data: { $ref: '#/components/schemas/ExternalFreightPreview' }
'404': { description: 排车单不存在 }
'409': { description: 外接实收或排车关联不一致 }
/api/platform/v1/last-leg/dispatches/{dispatchNo}/transfer-delivery:
post:
summary: 排车转出库与派送单
description: 权限 platform:overseas-warehouse:dispatch:transfer-delivery;只按全局唯一 dispatchNo 锁定记录并从记录解析客户范围,不接收 customerId;一个排车仍生成一张出库单,并按目的FBA仓分别生成派送单,返回 deliveries 数组;同一幂等键或已转换排车重复调用返回全部既有单据。派送费用只发布一次,避免按拆分派送单重复计费。
description: 权限 platform:overseas-warehouse:dispatch:transfer-delivery;只按全局唯一 dispatchNo 锁定记录并从记录解析客户范围,不接收 customerId;一个排车仍生成一张出库单,并按目的FBA仓分别生成派送单,返回 deliveries 数组;同一幂等键或已转换排车只有业务请求内容与首次保存一致才返回既有单据,费用、计划时间、装载或其他字段变化均拒绝,不因更换幂等键绕过。派送费用只发布一次,费用更正使用正式来源调整流程。已关联车次时新请求不得覆盖车次维护的车牌、司机和电话;原请求重放不改写后续已同步的车次快照。
security: [{ bearerAuth: [] }]
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/DeliveryTransfer' } } } }
@@ -766,7 +838,7 @@ paths:
/api/platform/v1/last-leg/outbound-orders/{outboundNo}/cancel:
post:
summary: 取消未执行出库单
description: 权限 platform:overseas-warehouse:outbound:cancel;只按全局唯一 outboundNo 锁定并解析客户范围,不接收 customerId。仅未开始拣货/出库的单据可取消,重复取消幂等成功。
description: 权限 platform:overseas-warehouse:outbound:cancel;操作人取认证身份,只按全局唯一outboundNo解析客户,不接收customerId。关联排车按dispatch→outbound顺序锁定,已拣货/发车拒绝,仍绑定车次时须先解除;取消出库不自动取消原排车占用,后续在排车列表取消。当前已审核有效的DELIVERY_FEE应收按原来源版本申请作废,装车/买约/应付等其他费用保留核对,物流取消不代表账务作废成功。取消原因完整保存在派送操作记录,重复取消幂等成功。
security: [{ bearerAuth: [] }]
parameters: [{ name: outboundNo, in: path, required: true, schema: { type: string } }]
requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/OutboundCancel' } } } }
@@ -783,7 +855,7 @@ paths:
description: 权限 platform:overseas-warehouse:delivery:list;列表权限包含详情只读;order.allowedActions 为当前可执行动作。
security: [{ bearerAuth: [] }]
parameters: [{ name: deliveryNo, in: path, required: true, schema: { type: string } }]
responses: { '200': { description: 派送单详情,SKU与BOL打印数据只包含当前派送单目的FBA仓 }, '404': { description: 派送单不存在 } }
responses: { '200': { description: '派送单详情,SKU与BOL打印数据只包含当前派送单目的FBA仓;fees附reviewStatus、sourceStatus、voidStatus(NOT_REQUESTED/PENDING_FINANCE/FINANCE_ATTENTION/CONFIRMED),不得把待财务确认或待处理显示为已作废。feeCoverage为可空的原费用服务覆盖确认快照,只包含当前派送所属货物、引用的原费用版本及服务、确认人和时间;不代表新增收费或原费用已付款。' }, '404': { description: 派送单不存在 } }
/api/platform/v1/last-leg/exception-orders:
get:
summary: 分页查询异常订单
@@ -983,7 +1055,7 @@ paths:
responses: { '200': { description: 当前客户派送单分页 }, '403': { description: 缺少客户派送查看权限 } }
post:
summary: 客户从自己的排车单创建派送单
description: 权限 merchant:warehouse:delivery:create;客户范围只取认证 Token,dispatchNo 必填,不接收 customerId;同一幂等键或已转换排车重复调用返回既有单据。
description: 权限 merchant:warehouse:delivery:create;客户范围只取认证 Token,dispatchNo 必填,不接收 customerId;同一幂等键或已转换排车重复调用返回既有单据。已关联车次时请求不得覆盖车次维护的车牌、司机和电话。
security: [{ bearerAuth: [] }]
parameters: [{ name: dispatchNo, in: query, required: true, schema: { type: string, minLength: 1 } }]
requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/DeliveryTransfer' } } } }
@@ -2311,7 +2383,7 @@ components:
planNo: { type: string, nullable: true }
orderType: { type: string, nullable: true }
volumeWeightKg: { type: number, nullable: true }
grossWeightKg: { type: number, nullable: true, description: 候选托盘实际毛重(千克);按入库计划分配比例汇总,缺失时回退体积重 }
grossWeightKg: { type: number, nullable: true, description: 候选托盘分摊毛重(千克);以实际毛重按入库计划分配比例汇总,缺失时为空,禁止使用体积重替代;正式配载须核验实际装载 }
containerNo: { type: string, nullable: true }
appointmentAt: { type: string, format: date-time, nullable: true }
expectedLoadingAt: { type: string, format: date-time, nullable: true }
@@ -2327,8 +2399,6 @@ components:
destinationWarehouseName: { type: string }
fbaWarehouseCode: { type: string }
packageCount: { type: integer }
grossWeightKg: { type: number, description: 排车托盘冻结毛重(千克) }
volumeWeightKg: { type: number, description: 排车托盘冻结材积重(千克) }
volumeCbm: { type: number }
sourceStage: { type: string, enum: [PLAN, RECEIVED] }
cartonMarks: { type: string, nullable: true, description: 该托盘箱号,逗号分隔 }
@@ -2396,6 +2466,7 @@ components:
estimatedArrivalAt: { type: string, format: date-time, nullable: true }
DeliveryTransfer:
type: object
description: 外接货必须带入当前externalFreightHash,服务端按实收报价发布对应目的地的派送应收。平台可通过feeCoverage逐票确认原Finance费用所含服务,并传feeCoverageCargoHash;重新核对真实货物、费用ID/版本/hash及客户范围后冻结确认快照。只有全部相关货物已覆盖的服务才能免填对应新增应收,并禁止重复登记该应收;仍可独立登记供应商应付。未覆盖部分收费,原费用不复制入账也不伪造零金额费用。客户接口禁止自行声明feeCoverage。已有成功命令重放保留原覆盖快照。
required: [idempotencyKey, plannedDeliveryAt, deliveryMethod, pickupMethod, loadingType, fees]
properties:
idempotencyKey: { type: string, minLength: 1, maxLength: 255 }
@@ -2413,7 +2484,40 @@ components:
appointmentAccount: { type: string, nullable: true, maxLength: 128 }
sellerName: { type: string, nullable: true, maxLength: 128 }
remark: { type: string, nullable: true, maxLength: 1000 }
fees: { type: array, minItems: 1, maxItems: 20, items: { $ref: '#/components/schemas/DeliveryFeeInput' } }
fees: { type: array, maxItems: 20, items: { $ref: '#/components/schemas/DeliveryFeeInput' } }
externalFreightHash: { type: string, nullable: true, maxLength: 64 }
feeCoverageCargoHash: { type: string, nullable: true, maxLength: 64 }
feeCoverage: { type: array, nullable: true, maxItems: 2000, items: { $ref: '#/components/schemas/FeeCoverageSelection' } }
FeeCoverageSelection:
type: object
required: [financeFeeId, sourceVersion, sourceHash, services]
properties:
financeFeeId: { type: string, pattern: '^[1-9][0-9]*$' }
sourceVersion: { type: integer, minimum: 1 }
sourceHash: { type: string }
services: { type: array, minItems: 1, maxItems: 3, items: { type: string, enum: [DELIVERY_FEE, LOADING_FEE, APPOINTMENT_FEE] } }
ExternalFreightPreview:
type: object
required: [snapshotHash, requiresDeliveryFee, quotes]
properties:
snapshotHash: { type: string }
requiresDeliveryFee: { type: boolean }
quotes:
type: array
items:
type: object
properties:
bookingNo: { type: string }
recordVersion: { type: integer, format: int64 }
incomingNo: { type: string }
inboundCode: { type: string, nullable: true }
customerName: { type: string }
destinationKey: { type: string }
currency: { type: string, enum: [CNY, USD] }
amount: { type: number }
quantity: { type: number }
quantityUnit: { type: string, enum: [托位, 单] }
unitPrice: { type: number }
DeliveryStatusChange:
type: object
required: [status, expectedVersion]
@@ -10,7 +10,7 @@ paths:
- { in: query, name: businessType, schema: { $ref: '#/components/schemas/BusinessType' } }
- { in: query, name: businessNo, schema: { type: string } }
- { in: query, name: containerBookingId, description: 精确查询真实来源柜下全部客户的费用;可再传customerId收窄到单个客户, schema: { type: string, pattern: '^[1-9][0-9]*$' } }
responses: { '200': { description: 当前版本列表 } }
responses: { '200': { description: '当前版本列表;voidStatus为NOT_REQUESTED、PENDING_FINANCE、FINANCE_ATTENTION或CONFIRMED,批量查询作废确认状态,不逐行读取。等待或拒绝时sourceStatus保留ACTIVE,只有Finance持久化确认后为VOIDED。' } }
post:
summary: 创建海外业务费用来源草稿
description: 客户和业务编号必填;入仓ID、入仓码均按业务事实选填,不得为补字段伪造。海外货柜费用必须以相同的businessId和containerBookingId引用真实来源柜,且businessNo与containerNo均为该柜真实集装箱号。
@@ -34,7 +34,7 @@ paths:
/api/platform/v1/last-leg/finance-fee-sources/{sourceFeeId}/{action}:
post:
summary: 提交、审核、调整或作废海外业务费用来源
description: 审核通过与作废均事务性写入Outbox,经Event Bridge可靠投递至独立Finance;action为submit、review、adjust、void。
description: 审核通过与作废均事务性写入Outbox;此处作废仅指申请,直接可靠投递至独立Finance;action为submit、review、adjust、void。作废申请不立即更改sourceStatus,voidStatus为PENDING_FINANCE;等待原发布成功后才投递作废,收到匹配APPLIED/DUPLICATE确认时在投递审计事务内更新VOIDED。失败/结果未知仍保留原来源,拒绝或投递耗尽显示FINANCE_ATTENTION,禁止未决作废期间调整版本。
security: [{ bearerAuth: [] }]
parameters:
- { in: path, name: sourceFeeId, required: true, schema: { type: string } }
@@ -264,10 +264,14 @@ components:
VehicleStatus: { type: string, enum: [IN_SERVICE, DISPATCHED, MAINTENANCE, INACTIVE, RETURNED] }
VehicleCreate:
type: object
description: 托位/载重/容积同时填写正数,或全部留空表示容量尚未确认;未知容量不可用于正式配载,不按车型名称推算。
required: [plateNumber, model, fuelConsumptionPer100Km, mileageKm, region, ownership, status]
properties:
plateNumber: { type: string, maxLength: 64 }
model: { type: string, maxLength: 128 }
maxPalletSpaces: { type: integer, minimum: 1, maximum: 10000, nullable: true }
maxLoadKg: { type: number, minimum: 0, exclusiveMinimum: true, nullable: true }
maxVolumeCbm: { type: number, minimum: 0, exclusiveMinimum: true, nullable: true }
fuelConsumptionPer100Km: { type: number, exclusiveMinimum: true, minimum: 0 }
mileageKm: { type: integer, format: int64, minimum: 0 }
driverOrDispatchCompany: { type: string, maxLength: 128, nullable: true }
@@ -278,11 +282,15 @@ components:
remark: { type: string, maxLength: 1000, nullable: true }
VehicleUpdate:
type: object
description: 托位/载重/容积同时填写正数,或全部留空;不能部分设置容量。
required: [recordVersion, plateNumber, model, fuelConsumptionPer100Km, mileageKm, region, ownership]
properties:
recordVersion: { type: integer, format: int64, minimum: 0 }
plateNumber: { type: string, maxLength: 64 }
model: { type: string, maxLength: 128 }
maxPalletSpaces: { type: integer, minimum: 1, maximum: 10000, nullable: true }
maxLoadKg: { type: number, minimum: 0, exclusiveMinimum: true, nullable: true }
maxVolumeCbm: { type: number, minimum: 0, exclusiveMinimum: true, nullable: true }
fuelConsumptionPer100Km: { type: number, exclusiveMinimum: true, minimum: 0 }
mileageKm: { type: integer, format: int64, minimum: 0, description: 不得小于已有公里码 }
driverOrDispatchCompany: { type: string, maxLength: 128, nullable: true }
@@ -15,12 +15,13 @@ paths:
/api/pda/v1/last-leg/dispatches/{dispatchNo}:
get:
summary: 查询绑定仓排车任务详情
description: 返回 canDepart 与 departBlockReason;PDA 必须以服务端门禁决定是否开放发车,不得仅按本地拣货数量推断。
description: 返回 tripNo、tripRecordVersion、tripDispatchCount、driverWarning、canDepart、departBlockReason、canPick 与 pickBlockReason;门禁反映整车所有客户单据、实际装载及当前司机资格,PDA 不得仅按当前子单拣货数量推断。canPick/pickBlockReason仅反映当前客户排车单调度审核,不以其他客户审核结果替代。未关联车次不可拣货或发车;列表按车次复用同次查询的门禁结果。证照30天内到期但覆盖任务时driverWarning提醒且仍允许,预计结束前过期则阻断。
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
responses: { '200': { description: 排车托盘、目的仓与库存位置详情 }, '404': { description: 当前绑定仓无此排车任务 } }
/api/pda/v1/last-leg/dispatches/{dispatchNo}/items/{itemId}/pick:
post:
summary: 扫码拣取排车托盘包裹
description: 新请求须当前排车调度审核通过;同键同内容重放已保存结果不重新扣库存。
parameters:
- { name: dispatchNo, in: path, required: true, schema: { type: string } }
- { name: itemId, in: path, required: true, schema: { type: string, pattern: '^[0-9]+$' } }
@@ -29,17 +30,17 @@ paths:
/api/pda/v1/last-leg/dispatches/{dispatchNo}/complete:
post:
summary: 完成排车拣货
description: 每个要求托盘及全部包裹必须精确完成;不允许部分完成。
description: 当前排车调度审核通过且每个要求托盘及全部包裹必须精确完成;不允许部分完成。
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/IdempotentAction' } } } }
responses: { '200': { description: READY_TO_DEPART结果 }, '409': { description: 未全部拣货或幂等冲突 } }
/api/pda/v1/last-leg/dispatches/{dispatchNo}/depart:
post:
summary: 排车发车并完成出库门禁
description: 仅完整拣货且存在待出库单时发车;同事务推进出库与排车状态、订单归属并释放托盘锁,不重复扣减扫码时已扣库存。
summary: 从排车任务确认所属车次整车发车
description: 按Token绑定仓锁定车次,校验期望车次版本、车辆占用、全部调度审核、实际装载、整车理货审核及全部客户拣货和待出库单,重新核验司机证照、当前海外区域和身份;区域或身份变化与预览门禁一致阻断。一个事务推进所有子单,任一失败全车回滚。扫码阶段已扣库存不重复扣减;同键同内容重放整车结果,不同内容冲突。DEPARTING仅是同事务内部状态,不对外提交。
parameters: [{ name: dispatchNo, in: path, required: true, schema: { type: string } }]
requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/DepartAction' } } } }
responses: { '200': { description: DEPARTED结果;同键同请求返回既有结果 }, '409': { description: 拣货、出库或幂等门禁未满足 } }
responses: { '200': { description: '统一响应data包含tripNo、status=IN_TRANSIT、departedAt、shippedPackages、dispatches数组(dispatchNo/shippedPackages)和replayed;每张子排车状态均为DEPARTED' }, '409': { description: 车次版本、装载、资格、拣货、出库或幂等门禁未满足 } }
/api/pda/v1/last-leg/outbound-tasks:
get:
summary: 查询Token绑定仓的一件代发出库任务
@@ -850,9 +851,10 @@ components:
properties: { idempotencyKey: { type: string, minLength: 1, maxLength: 255 } }
DepartAction:
type: object
required: [idempotencyKey]
required: [recordVersion, idempotencyKey]
properties:
idempotencyKey: { type: string, minLength: 1, maxLength: 255 }
recordVersion: { type: integer, format: int64, minimum: 0, description: 当前车次版本,来自tripRecordVersion}
idempotencyKey: { type: string, minLength: 8, maxLength: 128 }
remark: { type: string, maxLength: 1000, nullable: true }
DispatchPick:
type: object
@@ -0,0 +1,103 @@
package com.baiyue.lastleg.delivery;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.client.FinanceFeeCoverageClient;
import com.baiyue.lastleg.delivery.controller.PlatformDeliveryFeeCoverageController;
import com.baiyue.lastleg.delivery.dto.DeliveryFeeCoverageModels;
import com.baiyue.lastleg.delivery.dto.DeliveryRequests;
import com.baiyue.lastleg.delivery.mapper.DispatchFeeCargoMapper;
import com.baiyue.lastleg.delivery.service.DeliveryFeeCoverageService;
import com.baiyue.lastleg.dispatch.entity.DispatchItem;
import com.baiyue.lastleg.dispatch.entity.DispatchOrder;
import com.baiyue.lastleg.dispatch.mapper.DispatchItemMapper;
import com.baiyue.lastleg.dispatch.mapper.DispatchOrderMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
class DeliveryFeeCoverageServiceTest {
final DispatchOrderMapper dispatches = mock(DispatchOrderMapper.class);
final DispatchItemMapper items = mock(DispatchItemMapper.class);
final DispatchFeeCargoMapper cargo = mock(DispatchFeeCargoMapper.class);
final FinanceFeeCoverageClient finance = mock(FinanceFeeCoverageClient.class);
final DeliveryFeeCoverageService service = new DeliveryFeeCoverageService(dispatches, items, cargo, finance,
new ObjectMapper().findAndRegisterModules(), "coverage-test-token");
@BeforeEach void setup() {
var dispatch = new DispatchOrder(); dispatch.setId(1L); dispatch.setCustomerId("101"); dispatch.setDispatchNo("DP-1");
when(dispatches.findGlobalByDispatchNo("DP-1")).thenReturn(dispatch);
var selected = new DispatchItem(); selected.setId(201L); selected.setPackageCount(20);
when(items.findByDispatchOrder("101", 1L)).thenReturn(List.of(selected));
when(cargo.list("101", 1)).thenReturn(List.of(source("11", "IN-A", 10), source("12", "IN-B", 10)));
}
@Test void batchesBothActualInboundSourcesInsteadOfUsingOneDisplayCode() {
var query = new FinanceFeeCoverageClient.Query(101L, List.of(11L, 12L));
when(finance.sources("coverage-test-token", query)).thenReturn(ApiResponse.success(List.of(fee(101, 11))));
var result = service.preview("DP-1");
assertThat(result.sourceComplete()).isTrue(); assertThat(result.cargo()).hasSize(2); assertThat(result.feeSources()).hasSize(1);
assertThat(result.cargoHash()).hasSize(64);
verify(finance).sources("coverage-test-token", query); verifyNoMoreInteractions(finance);
}
@Test void incompletePhysicalSourcesNeverProduceAFalseCoverageOption() {
when(cargo.list("101", 1)).thenReturn(List.of(source("11", "IN-A", 10)));
var result = service.preview("DP-1");
assertThat(result.sourceComplete()).isFalse(); assertThat(result.blockReason()).contains("箱数不一致");
assertThat(result.feeSources()).isEmpty(); verifyNoInteractions(finance);
}
@Test void unavailableOrWrongScopeFinanceResultsFailClosed() {
when(finance.sources(anyString(), any())).thenReturn(ApiResponse.success(List.of(fee(202, 11))));
assertThatThrownBy(() -> service.preview("DP-1")).isInstanceOf(ResponseStatusException.class).hasMessageContaining("503");
when(finance.sources(anyString(), any())).thenReturn(ApiResponse.success(List.of(fee(101, 999))));
assertThatThrownBy(() -> service.preview("DP-1")).isInstanceOf(ResponseStatusException.class);
when(finance.sources(anyString(), any())).thenReturn(null);
assertThatThrownBy(() -> service.preview("DP-1")).isInstanceOf(ResponseStatusException.class);
}
@Test void platformReadonlyEndpointDoesNotAcceptMerchantIdentityOrAClientSuppliedCustomer() throws Exception {
var controller = new PlatformDeliveryFeeCoverageController(service);
var merchant = new AuthenticatedUser(7L, 101L, 101L, 8L, "merchant", "MERCHANT", "WEB", Set.of());
assertThatThrownBy(() -> controller.preview(merchant, "DP-1")).isInstanceOf(ResponseStatusException.class).hasMessageContaining("403");
assertThatThrownBy(() -> controller.preview(null, "DP-1")).isInstanceOf(ResponseStatusException.class).hasMessageContaining("401");
var method = PlatformDeliveryFeeCoverageController.class.getMethod("preview", AuthenticatedUser.class, String.class);
assertThat(method.getAnnotation(PreAuthorize.class).value()).contains("platform:overseas-warehouse:dispatch:list");
verifyNoInteractions(dispatches, items, cargo, finance);
}
@Test void onlyFullyCoveredServicesCanRemoveANewChargeAndTheSnapshotKeepsEveryActualSource() {
when(finance.sources(anyString(), any())).thenReturn(ApiResponse.success(List.of(fee(101,11), fee(101,12))));
var preview = service.preview("DP-1");
var a = new DeliveryFeeCoverageModels.Selection(711L, 1, fee(101,11).sourceHash(), List.of("DELIVERY_FEE", "LOADING_FEE"));
var partial = service.confirm("DP-1", coverageRequest(preview.cargoHash(), List.of(a)), "OP-1", Set.of());
assertThat(partial.includedServices()).isEmpty();
assertThat(partial.uncovered("DELIVERY_FEE")).extracting(DeliveryFeeCoverageModels.Cargo::sourceInboundId).containsExactly("12");
var b = new DeliveryFeeCoverageModels.Selection(712L, 1, fee(101,12).sourceHash(), List.of("DELIVERY_FEE", "LOADING_FEE"));
var complete = service.confirm("DP-1", coverageRequest(preview.cargoHash(), List.of(a,b)), "OP-1", Set.of());
assertThat(complete.includedServices()).containsExactlyInAnyOrder("DELIVERY_FEE", "LOADING_FEE");
assertThat(complete.evidence().cargo()).hasSize(2); assertThat(complete.evidence().references()).hasSize(2);
assertThat(complete.evidence().operatorId()).isEqualTo("OP-1");
}
@Test void staleCargoFeeVersionAndRepeatedCoverageAreRejected() {
when(finance.sources(anyString(), any())).thenReturn(ApiResponse.success(List.of(fee(101,11))));
var preview = service.preview("DP-1");
var selected = new DeliveryFeeCoverageModels.Selection(711L, 1, fee(101,11).sourceHash(), List.of("DELIVERY_FEE"));
assertThatThrownBy(() -> service.confirm("DP-1", coverageRequest("old-cargo", List.of(selected)), "OP-1", Set.of())).hasMessageContaining("货物已变化");
var old = new DeliveryFeeCoverageModels.Selection(711L, 2, selected.sourceHash(), selected.services());
assertThatThrownBy(() -> service.confirm("DP-1", coverageRequest(preview.cargoHash(), List.of(old)), "OP-1", Set.of())).hasMessageContaining("版本已变化");
assertThatThrownBy(() -> service.confirm("DP-1", coverageRequest(preview.cargoHash(), List.of(selected, selected)), "OP-1", Set.of())).hasMessageContaining("只能引用一项");
}
static DeliveryRequests.Transfer coverageRequest(String hash, List<DeliveryFeeCoverageModels.Selection> selections) {
return new ObjectMapper().findAndRegisterModules().convertValue(java.util.Map.of("feeCoverageCargoHash", hash, "feeCoverage", selections), DeliveryRequests.Transfer.class);
}
static DeliveryFeeCoverageModels.Cargo source(String id, String code, long packages) {
return new DeliveryFeeCoverageModels.Cargo(201L, 501L, "PLT-501", Long.valueOf(id), "FIRSTLEG", id, code, packages, "IN-A");
}
static FinanceFeeCoverageClient.Fee fee(long customer, long inbound) {
return new FinanceFeeCoverageClient.Fee(700L + inbound, 800L + inbound, "INBOUND_FEE", 1, customer, inbound,
"IN-A", "FREIGHT", "原运费", "CNY", BigDecimal.TEN, "sha256:" + "a".repeat(64), "AVAILABLE");
}
}
@@ -34,9 +34,9 @@ class DeliveryLongIdJsonContractTest {
deliveryRow(),
List.of(),
List.of(new DeliveryResponses.DeliveryFeeRow(
FEE_ID, "RECEIVABLE", "DELIVERY_FEE", "USD", null, null)),
FEE_ID, "RECEIVABLE", "DELIVERY_FEE", "USD", null, null, "APPROVED", "ACTIVE", "NOT_REQUESTED")),
List.of(new DeliveryResponses.DeliveryOperationRow(
OPERATION_ID, null, "CREATED", "tester", "success")));
OPERATION_ID, null, "CREATED", "tester", "success")), null);
JsonNode json = objectMapper.readTree(objectMapper.writeValueAsString(detail));
@@ -67,7 +67,7 @@ class DeliveryLongIdJsonContractTest {
null, null, "PS-1", null, null, null, null, "CREATED", null,
null, null, null, null, null, null, null, null, null, null, null,
0, 0, null, null, null, null, null, null, null, null, 0, java.util.List.of(), null,
com.baiyue.lastleg.delivery.model.DeliveryDocumentSnapshot.summary(null), null, null, null,
com.baiyue.lastleg.delivery.service.DeliveryDocumentSnapshot.summary(null), null, null, null,
null, null, null, null, null);
}
}
@@ -17,6 +17,18 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DeliverySchemaContractTest {
@Test
void shipmentSnapshotsKeepUnknownPhysicalWeightNullableAcrossBothBaselines() throws Exception {
for (Path path : java.util.List.of(Path.of("src/main/resources/db/lastleg.sql"), Path.of("../deploy/sql/海外区域统一增量-MySQL8.sql"))) {
String sql = Files.readString(path, StandardCharsets.UTF_8);
for (String table : java.util.List.of("ll_dispatch_item", "ll_outbound_order", "ll_outbound_pallet_item", "ll_delivery_order")) {
var matcher = java.util.regex.Pattern.compile("(?is)CREATE TABLE(?: IF NOT EXISTS)? " + table + " \\(.*?;").matcher(sql);
assertTrue(matcher.find(), table);
String column = "ll_delivery_order".equals(table) ? "total_weight_kg" : "gross_weight_kg";
assertTrue(java.util.regex.Pattern.compile("(?i)" + column + " DECIMAL\\(18,[34]\\) NULL COMMENT").matcher(matcher.group()).find(), table + " keeps unknown weight NULL");
}
}
}
@Test
void baselineDefinesOutboundPalletsAndDeliveryContracts() throws Exception {
String schema = Files.readString(Path.of("src/main/resources/db/lastleg.sql"), StandardCharsets.UTF_8)
@@ -0,0 +1,50 @@
package com.baiyue.lastleg.delivery;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.baiyue.lastleg.delivery.mapper.DispatchFeeCargoMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.util.UUID;
import static org.assertj.core.api.Assertions.*;
class DispatchFeeCargoMapperTest {
JdbcTemplate jdbc; DispatchFeeCargoMapper mapper;
@BeforeEach void setup() throws Exception {
var dataSource = new DriverManagerDataSource("jdbc:h2:mem:" + UUID.randomUUID() + ";MODE=MySQL;DB_CLOSE_DELAY=-1", "sa", "");
jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE ll_dispatch_item(id BIGINT,dispatch_order_id BIGINT,customer_id VARCHAR(64),warehouse_pallet_id BIGINT,pallet_no VARCHAR(64),overseas_warehouse_id VARCHAR(64),plan_pallet_id BIGINT,inbound_code VARCHAR(64))");
jdbc.execute("CREATE TABLE ll_inventory_position(id BIGINT,customer_id VARCHAR(64),pallet_id BIGINT,overseas_warehouse_id VARCHAR(64),balance_id BIGINT,available_packages BIGINT)");
jdbc.execute("CREATE TABLE ll_inventory_balance(id BIGINT,customer_id VARCHAR(64),inbound_order_id BIGINT,inbound_code VARCHAR(64))");
jdbc.execute("CREATE TABLE ll_order(id BIGINT,customer_id VARCHAR(64),source_region VARCHAR(32),source_inbound_id VARCHAR(64))");
jdbc.execute("CREATE TABLE ll_dispatch_pda_task(id BIGINT,customer_id VARCHAR(64),dispatch_order_id BIGINT)");
jdbc.execute("CREATE TABLE ll_dispatch_pda_pick(task_id BIGINT,customer_id VARCHAR(64),dispatch_item_id BIGINT,inventory_position_id BIGINT,packages BIGINT)");
jdbc.execute("CREATE TABLE ll_inbound_plan_pallet_allocation(pallet_id BIGINT,line_id BIGINT)");
jdbc.execute("CREATE TABLE ll_inbound_plan_line(id BIGINT,customer_id VARCHAR(64),order_id BIGINT)");
jdbc.update("INSERT INTO ll_dispatch_item VALUES(201,1,'101',501,'PLT-501','WH-1',NULL,'IN-A')");
jdbc.update("INSERT INTO ll_inventory_position VALUES(101,'101',501,'WH-1',301,8),(102,'101',501,'WH-1',302,6),(103,'202',501,'WH-1',303,50),(104,'101',501,'WH-2',301,50)");
jdbc.update("INSERT INTO ll_inventory_balance VALUES(301,'101',401,'IN-A'),(302,'101',402,'IN-B'),(303,'202',403,'IN-OTHER')");
jdbc.update("INSERT INTO ll_order VALUES(401,'101','FIRSTLEG','11'),(402,'101','FIRSTLEG','12'),(403,'202','FIRSTLEG','13')");
jdbc.update("INSERT INTO ll_dispatch_pda_task VALUES(601,'101',1),(602,'101',2)");
jdbc.update("INSERT INTO ll_dispatch_pda_pick VALUES(601,'101',201,101,2),(601,'101',201,102,4),(602,'101',201,101,50)");
var config = new MybatisConfiguration(); config.addMapper(DispatchFeeCargoMapper.class);
var factory = new MybatisSqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setConfiguration(config); factory.afterPropertiesSet();
mapper = new SqlSessionTemplate(factory.getObject()).getMapper(DispatchFeeCargoMapper.class);
}
@Test void preservesEveryInboundOnSharedPalletAndIncludesOnlyThisDispatchsPickedPackages() {
var rows = mapper.list("101", 1);
assertThat(rows).hasSize(2);
assertThat(rows).extracting(row -> row.sourceInboundId()).containsExactly("11", "12");
assertThat(rows).extracting(row -> row.packages()).containsExactly(10L, 10L);
assertThat(mapper.list("202", 1)).isEmpty();
}
@Test void aSelectedPlanPalletCannotBorrowOtherInboundStockOnTheSamePhysicalPallet() {
jdbc.update("UPDATE ll_dispatch_item SET plan_pallet_id=801");
jdbc.update("INSERT INTO ll_inbound_plan_pallet_allocation VALUES(801,901)");
jdbc.update("INSERT INTO ll_inbound_plan_line VALUES(901,'101',401)");
assertThat(mapper.list("101", 1)).extracting(row -> row.sourceInboundId()).containsExactly("11");
}
}
@@ -94,6 +94,8 @@ class PlatformDispatchOutboundContractTest {
Method cancel = DispatchController.class.getMethod("cancel", AuthenticatedUser.class, String.class);
Method transfer = DeliveryTransferController.class.getMethod("transfer", AuthenticatedUser.class,
String.class, DeliveryRequests.Transfer.class);
Method externalFreight = DeliveryTransferController.class.getMethod("externalFreight", AuthenticatedUser.class, String.class);
assertPermission(externalFreight, OverseasPermissions.DISPATCH_LIST);
Method outboundDetail = DeliveryTransferController.class.getMethod("outboundDetail",
AuthenticatedUser.class, String.class);
Method outboundCancel = DeliveryTransferController.class.getMethod("cancelOutbound",
@@ -105,7 +107,7 @@ class PlatformDispatchOutboundContractTest {
assertPermission(outboundDetail, OverseasPermissions.OUTBOUND_LIST);
assertEquals(2, outboundDetail.getParameterCount());
assertPermission(outboundCancel, OverseasPermissions.OUTBOUND_CANCEL);
for (Method method : Set.of(update, cancel, transfer, outboundDetail, outboundCancel)) {
for (Method method : Set.of(update, cancel, transfer, externalFreight, outboundDetail, outboundCancel)) {
assertTrue(Arrays.stream(method.getParameters())
.noneMatch(parameter -> parameter.isAnnotationPresent(RequestParam.class)));
}
@@ -125,7 +125,7 @@ class MerchantDeliveryControllerTest {
@Test
void invalidCreatePayloadIsRejectedByBeanValidationContract() {
DeliveryRequests.Transfer invalid = new DeliveryRequests.Transfer(" ", null, " ", null, null,
" ", " ", null, null, null, null, null, null, null, null, null);
" ", " ", null, null, null, null, null, null, null, null, null, null, null, null);
try (var factory = Validation.buildDefaultValidatorFactory()) {
assertTrue(factory.getValidator().validate(invalid).size() >= 6);
}
@@ -186,6 +186,6 @@ class MerchantDeliveryControllerTest {
"ONE_PICKUP_ONE_DROP", "PALLET", null, null, null, null, null, null, null, null,
List.of(new DeliveryRequests.FeeItem("DELIVERY_FEE", "派送费", "RECEIVABLE", "CNY",
new BigDecimal("10.00"), null, null, null, null, null, null, null, null,
null, null, null, null, null, null)));
null, null, null, null, null, null)), null, null, null);
}
}

Some files were not shown because too many files have changed in this diff Show More