feat(fleet): query vehicle delivery and reassignment history

This commit is contained in:
2026-10-03 10:10:55 +08:00
parent d93185e750
commit 30559fd4eb
8 changed files with 420 additions and 0 deletions
@@ -0,0 +1,27 @@
package com.baiyue.lastleg.fleet.trip;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.core.api.PageResult;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@Validated
@RequestMapping("/api/platform/v1/last-leg/fleet/vehicles/{vehicleId}")
public class PlatformVehicleFulfillmentController {
private final VehicleFulfillmentService service;
public PlatformVehicleFulfillmentController(VehicleFulfillmentService service) { this.service = service; }
@GetMapping("/deliveries")
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:list') and hasAuthority('platform:overseas-warehouse:delivery:list')")
public ApiResponse<PageResult<VehicleFulfillmentModels.Delivery>> deliveries(@PathVariable @Min(1) long vehicleId, @Valid VehicleFulfillmentModels.Query query) {
return ApiResponse.success(service.deliveries(vehicleId, query));
}
@GetMapping("/assignment-history")
@PreAuthorize("hasAuthority('platform:overseas-master-data:vehicle:list') and hasAuthority('platform:fleet:trip:list')")
public ApiResponse<PageResult<VehicleFulfillmentModels.Change>> changes(@PathVariable @Min(1) long vehicleId, @Valid VehicleFulfillmentModels.Query query) {
return ApiResponse.success(service.changes(vehicleId, query));
}
}
@@ -0,0 +1,38 @@
package com.baiyue.lastleg.fleet.trip;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/** Read projection in the Lastleg schema. Never derives vehicle identity from a mutable plate. */
@Mapper
public interface VehicleFulfillmentMapper {
String DEPARTED = "EXISTS (SELECT 1 FROM ll_fleet_trip_history h WHERE h.trip_id=t.id AND h.action='DEPART' "
+ "AND JSON_UNQUOTE(JSON_EXTRACT(h.snapshot_json,'$.trip.vehicleId'))=#{vehicleKey})";
String DELIVERIES = " FROM ll_delivery_order d JOIN ll_fleet_trip_dispatch b "
+ "ON b.dispatch_id=d.dispatch_order_id AND b.customer_id=d.customer_id "
+ "JOIN ll_fleet_trip t ON t.id=b.trip_id WHERE ((t.status='PLANNED' AND t.vehicle_id=#{vehicleId}) OR " + DEPARTED + ")";
String PREVIOUS_VEHICLE = "JSON_UNQUOTE(JSON_EXTRACT(p.snapshot_json,'$.trip.vehicleId'))";
String NEXT_VEHICLE = "JSON_UNQUOTE(JSON_EXTRACT(h.snapshot_json,'$.trip.vehicleId'))";
String CHANGES = " FROM ll_fleet_trip_history h JOIN ll_fleet_trip t ON t.id=h.trip_id "
+ "JOIN ll_fleet_trip_history p ON p.trip_id=h.trip_id AND p.record_version=h.record_version-1 "
+ "WHERE h.action='ASSIGN' AND " + PREVIOUS_VEHICLE + " IS NOT NULL AND " + PREVIOUS_VEHICLE + " <> 'null' "
+ "AND (" + PREVIOUS_VEHICLE + "=#{vehicleKey} OR " + NEXT_VEHICLE + "=#{vehicleKey}) "
+ "AND (" + PREVIOUS_VEHICLE + "<>" + NEXT_VEHICLE
+ " OR JSON_UNQUOTE(JSON_EXTRACT(p.snapshot_json,'$.trip.driverId'))<>JSON_UNQUOTE(JSON_EXTRACT(h.snapshot_json,'$.trip.driverId')))";
@Select("SELECT COUNT(*)" + DELIVERIES)
long countDeliveries(@Param("vehicleId") long vehicleId, @Param("vehicleKey") String vehicleKey);
@Select("SELECT d.delivery_no,d.dispatch_no,t.trip_no,d.bol_no,d.customer_name,d.destination_type,"
+ "d.destination_warehouse_code,d.destination_warehouse_name,d.delivery_address,d.planned_delivery_at,d.status,"
+ "CASE WHEN " + DEPARTED + " THEN 'DEPARTED' ELSE 'PLANNED' END AS relationship" + DELIVERIES
+ " ORDER BY d.created_at DESC,d.id DESC LIMIT #{size} OFFSET #{offset}")
List<VehicleFulfillmentModels.Delivery> deliveries(@Param("vehicleId") long vehicleId, @Param("vehicleKey") String vehicleKey,
@Param("offset") long offset, @Param("size") int size);
@Select("SELECT COUNT(*)" + CHANGES)
long countChanges(@Param("vehicleKey") String vehicleKey);
@Select("SELECT t.trip_no,h.record_version,h.occurred_at,h.reason,p.snapshot_json AS before_snapshot,h.snapshot_json AS after_snapshot"
+ CHANGES + " ORDER BY h.occurred_at DESC,h.id DESC LIMIT #{size} OFFSET #{offset}")
List<VehicleFulfillmentModels.ChangeRow> changes(@Param("vehicleKey") String vehicleKey, @Param("offset") long offset, @Param("size") int size);
}
@@ -0,0 +1,25 @@
package com.baiyue.lastleg.fleet.trip;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
public final class VehicleFulfillmentModels {
private VehicleFulfillmentModels() { }
public record Query(@Min(1) Integer page, @Min(1) @Max(100) Integer size) {
public Query { page = page == null ? 1 : page; size = size == null ? 10 : size; }
public long offset() { return ((long) page - 1) * size; }
}
public record Delivery(String deliveryNo, String dispatchNo, String tripNo, String bolNo,
String customerName, String destinationType, String destinationWarehouseCode,
String destinationWarehouseName, String deliveryAddress,
LocalDateTime plannedDeliveryAt, String status, String relationship) { }
public record ChangeRow(String tripNo, long recordVersion, LocalDateTime occurredAt, String reason,
String beforeSnapshot, String afterSnapshot) { }
public record Change(String tripNo, long recordVersion, Instant occurredAt, String reason,
String previousVehiclePlate, String vehiclePlate,
String previousDriverName, String driverName, String relationship,
List<String> dispatchNos) { }
}
@@ -0,0 +1,53 @@
package com.baiyue.lastleg.fleet.trip;
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.databind.JsonNode;
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.time.ZoneOffset;
import java.util.ArrayList;
@Service
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
public class VehicleFulfillmentService {
private final VehicleRepository vehicles;
private final VehicleFulfillmentMapper mapper;
private final ObjectMapper json;
public VehicleFulfillmentService(VehicleRepository vehicles, VehicleFulfillmentMapper mapper, ObjectMapper json) {
this.vehicles = vehicles; this.mapper = mapper; this.json = json;
}
public PageResult<VehicleFulfillmentModels.Delivery> deliveries(long vehicleId, VehicleFulfillmentModels.Query query) {
requireVehicle(vehicleId); String key = Long.toString(vehicleId);
long total = mapper.countDeliveries(vehicleId, key);
return new PageResult<>(mapper.deliveries(vehicleId, key, query.offset(), query.size()), query.page(), query.size(), total, pages(total, query.size()));
}
public PageResult<VehicleFulfillmentModels.Change> changes(long vehicleId, VehicleFulfillmentModels.Query query) {
requireVehicle(vehicleId); String key = Long.toString(vehicleId);
long total = mapper.countChanges(key);
var records = mapper.changes(key, query.offset(), query.size()).stream().map(row -> change(key, row)).toList();
return new PageResult<>(records, query.page(), query.size(), total, pages(total, query.size()));
}
private VehicleFulfillmentModels.Change change(String key, VehicleFulfillmentModels.ChangeRow row) {
try {
JsonNode before = json.readTree(row.beforeSnapshot()).path("trip"), snapshot = json.readTree(row.afterSnapshot()), after = snapshot.path("trip");
if (!before.hasNonNull("vehicleId") || !after.hasNonNull("vehicleId")) throw new IllegalStateException("车辆更换历史缺少身份快照");
var dispatches = new ArrayList<String>();
for (JsonNode binding : snapshot.path("dispatches")) if (binding.hasNonNull("dispatchNo")) dispatches.add(binding.get("dispatchNo").asText());
String relationship = before.path("vehicleId").asText().equals(after.path("vehicleId").asText()) ? "DRIVER_CHANGED"
: key.equals(before.path("vehicleId").asText()) ? "REPLACED_OUT" : "REPLACED_IN";
return new VehicleFulfillmentModels.Change(row.tripNo(), row.recordVersion(), row.occurredAt().toInstant(ZoneOffset.UTC), row.reason(),
text(before, "vehiclePlate"), text(after, "vehiclePlate"), text(before, "driverName"), text(after, "driverName"), relationship, java.util.List.copyOf(dispatches));
} catch (JsonProcessingException error) { throw new IllegalStateException("车辆更换历史快照无法读取", error); }
}
private static String text(JsonNode value, String key) { return value.hasNonNull(key) ? value.get(key).asText() : null; }
private static long pages(long total, int size) { return total / size + (total % size == 0 ? 0 : 1); }
private void requireVehicle(long vehicleId) {
vehicles.findById(vehicleId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "车辆不存在"));
}
}