feat(lastleg): connect appointment followups and fleet intake

This commit is contained in:
2026-10-09 22:04:49 +08:00
parent 1202cafadf
commit 0d75e311d0
54 changed files with 2315 additions and 25 deletions
@@ -0,0 +1,37 @@
package com.baiyue.lastleg.appointmentplanning;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/** Read-only loaded cargo, independent of inbound-plan materialization. */
@Data
public class AppointmentCargo {
private String sourceKey;
private Long orderId;
private String customerId;
private String customerName;
private String inboundCode;
private String containerBookingId;
private String containerNo;
private String originWarehouseId;
private String originWarehouseCode;
private String originWarehouseName;
private String destinationWarehouseCode;
private Integer packages;
private Integer receivedPackages;
private Integer shippedPackages;
private Integer sourcePalletCount;
private BigDecimal volumeCbm;
private LocalDateTime estimatedArrivalAt;
private LocalDateTime estimatedWarehouseAt;
private Integer orderVersion;
private String standardNode;
private Long shippingVersion;
private LocalDateTime shippingObservedAt;
private String shippingProvider;
private boolean hasInboundPlan;
private boolean hasActiveAppointment;
private boolean detained;
private boolean mixedDestinations;
}
@@ -0,0 +1,45 @@
package com.baiyue.lastleg.appointmentplanning;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface AppointmentCargoMapper {
String FILTER = """
FROM ll_order o JOIN ll_container_shipping_gate g ON g.container_booking_id=o.source_container_booking_id
WHERE o.order_type='FIRST_LEG' AND o.destination_type='FBA' AND g.node_sequence >=40
AND o.current_status NOT IN ('CANCELLED','COMPLETED')
AND o.overseas_warehouse_id IN
<foreach collection='origins' item='id' open='(' separator=',' close=')'>#{id}</foreach>
AND o.fba_warehouse_code IN
<foreach collection='destinations' item='code' open='(' separator=',' close=')'>#{code}</foreach>
<if test='warehouseId != null'>AND o.overseas_warehouse_id=#{warehouseId}</if>
<if test='destination != null'>AND o.fba_warehouse_code=#{destination}</if>
<if test='keyword != null'>AND (o.inbound_code LIKE CONCAT('%',#{keyword},'%') OR o.container_no LIKE CONCAT('%',#{keyword},'%') OR o.customer_name LIKE CONCAT('%',#{keyword},'%'))</if>
""";
@Select("<script>SELECT COUNT(*) " + FILTER + "</script>")
long count(@Param("origins") List<String> origins, @Param("destinations") List<String> destinations,
@Param("warehouseId") String warehouseId, @Param("destination") String destination, @Param("keyword") String keyword);
@Select("<script>" + """
SELECT CONCAT('ORDER:',o.id) AS source_key,o.id AS order_id,o.customer_id,o.customer_name,o.inbound_code,
o.source_container_booking_id AS container_booking_id,o.container_no,
o.overseas_warehouse_id AS origin_warehouse_id,o.overseas_warehouse_code AS origin_warehouse_code,
o.overseas_warehouse_name AS origin_warehouse_name,o.fba_warehouse_code AS destination_warehouse_code,
o.package_count AS packages,o.received_package_count AS received_packages,o.shipped_package_count AS shipped_packages,
o.pallet_count AS source_pallet_count,o.volume_cbm,o.estimated_arrival_at,o.estimated_warehouse_at,
o.version AS order_version,g.standard_node,g.aggregate_version AS shipping_version,
g.observed_at AS shipping_observed_at,g.provider_code AS shipping_provider,o.detained,
EXISTS(SELECT 1 FROM ll_inbound_plan p WHERE p.source_order_id=o.id AND p.customer_id=o.customer_id) AS has_inbound_plan,
EXISTS(SELECT 1 FROM ll_inbound_fba_appointment_item i JOIN ll_inbound_fba_appointment a ON a.id=i.appointment_id
WHERE i.order_id=o.id AND i.customer_id=o.customer_id AND a.appointment_status NOT IN ('CANCELLED','FAILED')) AS has_active_appointment,
EXISTS(SELECT 1 FROM ll_order_detail d WHERE d.order_id=o.id AND d.customer_id=o.customer_id
AND d.destination_warehouse_code IS NOT NULL AND d.destination_warehouse_code&lt;&gt;o.fba_warehouse_code) AS mixed_destinations
""" + FILTER + " ORDER BY o.created_at DESC,o.id DESC LIMIT #{size} OFFSET #{offset}</script>")
List<AppointmentCargo> page(@Param("origins") List<String> origins, @Param("destinations") List<String> destinations,
@Param("warehouseId") String warehouseId, @Param("destination") String destination,
@Param("keyword") String keyword, @Param("size") int size, @Param("offset") long offset);
}
@@ -0,0 +1,57 @@
package com.baiyue.lastleg.appointmentplanning;
import com.baiyue.common.core.api.PageResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Set;
@Service
public class AppointmentCargoService {
private final AppointmentCargoMapper mapper;
private final AppointmentWarehouseClient warehouses;
private final String token;
public AppointmentCargoService(AppointmentCargoMapper mapper, AppointmentWarehouseClient warehouses,
@Value("${baiyue.security.internal-service-token:}") String token) {
this.mapper = mapper; this.warehouses = warehouses; this.token = token;
}
public PageResult<AppointmentCargo> page(int page, int size, String warehouseId, String destination, String keyword) {
if (page < 1 || size < 1 || size > 100) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "每页数量必须为1至100");
if (keyword != null && keyword.length() > 128) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "搜索词过长");
var scope = scope();
var origins = scope.origins();
var destinations = scope.destinations();
warehouseId = clean(warehouseId); destination = clean(destination); keyword = clean(keyword);
if (warehouseId != null && !origins.contains(warehouseId) || destination != null && !destinations.contains(destination)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请选择已启用的美国接仓点及FBA目的仓");
}
if (origins.isEmpty() || destinations.isEmpty()) return new PageResult<>(List.of(), page, size, 0, 0);
long total = mapper.count(origins, destinations, warehouseId, destination, keyword);
var rows = mapper.page(origins, destinations, warehouseId, destination, keyword, size, (long) (page - 1) * size);
return new PageResult<>(rows, page, size, total, (total + size - 1) / size);
}
private record Scope(List<String> origins, List<String> destinations) { }
private Scope scope() {
final List<AppointmentWarehouseClient.Warehouse> catalog;
try {
var result = warehouses.catalog(token);
if (result == null || !result.successful() || result.data() == null) throw new IllegalStateException();
catalog = result.data();
} catch (RuntimeException error) {
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "仓库目录暂不可用,无法核实美国货物范围", error);
}
var us = catalog.stream().filter(w -> w != null && w.id() != null && w.id() > 0 && "US".equals(w.countryCode())).toList();
var origins = us.stream().filter(w -> Set.of("OVERSEAS", "OVERSEAS_PARTNER").contains(w.warehouseType() == null ? "" : w.warehouseType()))
.map(w -> w.id().toString()).distinct().toList();
var destinations = us.stream().filter(w -> "FBA".equals(w.warehouseType()) && clean(w.warehouseCode()) != null)
.map(AppointmentWarehouseClient.Warehouse::warehouseCode).distinct().toList();
return new Scope(origins, destinations);
}
private static String clean(String value) { return value == null || value.isBlank() ? null : value.trim(); }
}
@@ -0,0 +1,37 @@
package com.baiyue.lastleg.appointmentplanning;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDateTime;
import java.util.List;
@Mapper
public interface AppointmentCoverageMapper {
record OrderRef(String customerId, Long orderId) { }
record Source(Long orderId, String customerId, String destinationType, String fbaWarehouseCode,
Integer packages, Integer version, LocalDateTime updatedAt, boolean shipmentReferencesMissing) { }
record Fact(Long orderId, String customerId, String appointmentNo, String status,
LocalDateTime appointmentAt, LocalDateTime appointmentEndAt, LocalDateTime updatedAt,
Long lineId, Integer packages, String warehouseCode) { }
@Select({"<script>SELECT o.id AS orderId,o.customer_id AS customerId,o.destination_type AS destinationType,",
"o.fba_warehouse_code AS fbaWarehouseCode,o.package_count AS packages,o.version,o.updated_at AS updatedAt, ",
"(NOT EXISTS(SELECT 1 FROM ll_order_detail d WHERE d.order_id=o.id AND d.customer_id=o.customer_id) OR ",
"EXISTS(SELECT 1 FROM ll_order_detail d WHERE d.order_id=o.id AND d.customer_id=o.customer_id ",
"AND (d.shipment_no IS NULL OR TRIM(d.shipment_no)='') AND (d.fba_tracking_no IS NULL OR TRIM(d.fba_tracking_no)=''))) AS shipmentReferencesMissing ",
"FROM ll_order o WHERE <foreach collection='sources' item='s' open='(' separator=' OR ' close=')'>",
"(o.id=#{s.orderId} AND o.customer_id=#{s.customerId})</foreach></script>"})
List<Source> sources(@Param("sources") List<OrderRef> sources);
@Select({"<script>SELECT i.order_id AS orderId,i.customer_id AS customerId,a.appointment_no AS appointmentNo,",
"a.appointment_status AS status,a.appointment_at AS appointmentAt,a.appointment_end_at AS appointmentEndAt,",
"a.updated_at AS updatedAt,i.line_id AS lineId,l.required_package_count AS packages,l.fba_warehouse_code AS warehouseCode ",
"FROM ll_inbound_fba_appointment_item i JOIN ll_inbound_fba_appointment a ON a.id=i.appointment_id ",
"JOIN ll_inbound_plan_line l ON l.id=i.line_id AND l.plan_id=i.plan_id AND l.order_id=i.order_id AND l.customer_id=i.customer_id ",
"WHERE a.appointment_status NOT IN ('FAILED','CANCELLED') AND ",
"<foreach collection='sources' item='s' open='(' separator=' OR ' close=')'>",
"(i.order_id=#{s.orderId} AND i.customer_id=#{s.customerId})</foreach>",
" ORDER BY a.appointment_at,a.id,i.id</script>"})
List<Fact> appointments(@Param("sources") List<OrderRef> sources);
}
@@ -0,0 +1,101 @@
package com.baiyue.lastleg.appointmentplanning;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
/** Shared read projection. Callers authorize the customer/source before invoking; never confirms bookings. */
@Service
public class AppointmentCoverageService {
public record SourceRef(String customerId, String sourceKey, String destinationKey) { }
public record Appointment(String appointmentNo, String confirmationNo, String status,
LocalDateTime confirmedAt, LocalDateTime confirmedEndAt, String timezone) { }
public record Coverage(String customerId, String sourceKey, String destinationKey, String status,
List<Appointment> appointments, List<String> missingFields,
String sourceVersion, boolean changeReviewRequired) { }
private final AppointmentCoverageMapper mapper;
private final AppointmentExternalSourceGateway external;
public AppointmentCoverageService(AppointmentCoverageMapper mapper, AppointmentExternalSourceGateway external) {
this.mapper=mapper; this.external=external;
}
public List<Coverage> query(List<SourceRef> input) {
if (input==null || input.isEmpty()) return List.of();
if (input.size()>100 || input.stream().anyMatch(s -> s==null || blank(s.customerId()) || blank(s.sourceKey()) || blank(s.destinationKey()))) {
throw new IllegalArgumentException("每次最多核对100个完整的预约来源");
}
var requested=input.stream().distinct().toList();
var externalRefs=requested.stream().filter(s -> s.sourceKey().startsWith("BOOKING:"))
.map(s -> new AppointmentExternalSourceGateway.SourceRef(s.customerId(),s.sourceKey().substring(8))).toList();
var bookings=externalRefs.isEmpty() ? List.<AppointmentExternalSourceGateway.Source>of() : external.resolve(externalRefs);
var bookingMap=bookings.stream().collect(Collectors.toMap(s -> key(s.customerId(),"BOOKING:"+s.bookingNo()),s -> s));
var refs=new LinkedHashMap<SourceRef,AppointmentCoverageMapper.OrderRef>();
for (var source:requested) {
if (source.sourceKey().startsWith("ORDER:")) {
try {
long id=Long.parseLong(source.sourceKey().substring(6));
if (id>0) refs.put(source,new AppointmentCoverageMapper.OrderRef(source.customerId(),id));
} catch (NumberFormatException ignored) { /* Invalid source is returned explicitly below. */ }
} else if (source.sourceKey().startsWith("BOOKING:")) {
var booking=bookingMap.get(key(source.customerId(),source.sourceKey()));
if (booking!=null && booking.orderId()!=null && Objects.equals(source.destinationKey(),booking.destinationKey())) {
refs.put(source,new AppointmentCoverageMapper.OrderRef(source.customerId(),booking.orderId()));
}
}
}
var unique=refs.values().stream().distinct().toList();
if (unique.size()!=refs.size()) throw new IllegalArgumentException("同一货物存在重复来源,请保留原外接登记来源后再核对");
var orders=unique.isEmpty() ? List.<AppointmentCoverageMapper.Source>of() : mapper.sources(unique);
var orderMap=orders.stream().collect(Collectors.toMap(s -> new AppointmentCoverageMapper.OrderRef(s.customerId(),s.orderId()),s -> s));
var facts=unique.isEmpty() ? List.<AppointmentCoverageMapper.Fact>of() : mapper.appointments(unique);
var byOrder=facts.stream().collect(Collectors.groupingBy(f -> new AppointmentCoverageMapper.OrderRef(f.customerId(),f.orderId())));
var output=new ArrayList<Coverage>();
for (var source:requested) {
var booking=bookingMap.get(key(source.customerId(),source.sourceKey()));
if (booking!=null && !source.destinationKey().equals(booking.destinationKey())) {
output.add(empty(source,"DESTINATION_MISMATCH","DESTINATION",version(booking.recordVersion()),true)); continue;
}
if (booking!=null && !Set.of("CONFIRMED","RECEIVED","BOUND").contains(booking.bookingStatus()==null ? "" : booking.bookingStatus())) {
output.add(empty(source,"SOURCE_NOT_READY","CARRIER_CONFIRMATION",version(booking.recordVersion()),false)); continue;
}
var order=orderMap.get(refs.get(source));
if (order==null) {
output.add(empty(source,booking==null ? "SOURCE_NOT_FOUND" : "SOURCE_NOT_MATERIALIZED","REAL_CARGO_MATERIALS",booking==null ? null : version(booking.recordVersion()),false)); continue;
}
if (!"FBA".equals(order.destinationType()) || !source.destinationKey().equals("FBA:"+order.fbaWarehouseCode())) {
output.add(empty(source,"DESTINATION_MISMATCH","DESTINATION",version(order.version()),true)); continue;
}
var relevant=byOrder.getOrDefault(refs.get(source),List.of());
var distinct=new LinkedHashMap<String,Appointment>();
var seen=new HashSet<Long>(); long confirmed=0, covered=0; boolean invalid=false, changed=false;
for (var fact:relevant) {
if (!Objects.equals(order.fbaWarehouseCode(),fact.warehouseCode()) || fact.packages()==null || fact.packages()<=0 || !seen.add(fact.lineId())) { invalid=true; continue; }
covered+=fact.packages();
if ("SUCCESS".equals(fact.status()) && fact.appointmentAt()!=null) confirmed+=fact.packages();
boolean success="SUCCESS".equals(fact.status());
distinct.putIfAbsent(fact.appointmentNo(),new Appointment(fact.appointmentNo(),success ? fact.appointmentNo() : null,fact.status(),success ? fact.appointmentAt() : null,success ? fact.appointmentEndAt() : null,null));
changed|=order.updatedAt()==null || fact.updatedAt()==null || order.updatedAt().isAfter(fact.updatedAt());
}
var missing=new ArrayList<String>();
String status;
if (invalid || order.packages()==null || order.packages()<=0 || covered>order.packages()) { status="REVIEW_REQUIRED"; missing.add("CARGO_QUANTITY_REVIEW"); }
else if (covered==0) { status="UNASSIGNED"; missing.add("RECEIVING_APPOINTMENT"); }
else if (covered<order.packages()) { status="PARTIAL"; missing.add("UNCOVERED_CARGO"); }
else if (confirmed<order.packages()) { status="PENDING"; missing.add("RECEIVING_CONFIRMATION"); }
else { status="CONFIRMED"; }
if (confirmed>0) missing.add("APPOINTMENT_TIMEZONE_UNVERIFIED");
if (order.shipmentReferencesMissing()) missing.add("FBA_SHIPMENT_REFERENCES");
if (changed) missing.add("SOURCE_CHANGED_REVIEW");
output.add(new Coverage(source.customerId(),source.sourceKey(),source.destinationKey(),status,List.copyOf(distinct.values()),List.copyOf(missing),
(booking==null ? "" : "BOOKING:"+version(booking.recordVersion())+"/")+"ORDER:"+version(order.version()),changed || invalid));
}
return List.copyOf(output);
}
private static Coverage empty(SourceRef s,String status,String missing,String version,boolean review) {
return new Coverage(s.customerId(),s.sourceKey(),s.destinationKey(),status,List.of(),List.of(missing),version,review);
}
private static String key(String customerId,String sourceKey) { return customerId+"\n"+sourceKey; }
private static String version(Number version) { return version==null ? null : version.toString(); }
private static boolean blank(String value) { return value==null || value.isBlank(); }
}
@@ -0,0 +1,11 @@
package com.baiyue.lastleg.appointmentplanning;
import java.util.List;
/** Implemented by the external-booking owner; planning must not query Fleet's persistence directly. */
public interface AppointmentExternalSourceGateway {
record SourceRef(String customerId, String bookingNo) { }
record Source(String customerId, String bookingNo, String tripNo, String bookingStatus,
String warehouseId, String destinationKey, Long orderId, Integer packageCount, Long recordVersion) { }
List<Source> resolve(List<SourceRef> sources);
}
@@ -0,0 +1,28 @@
package com.baiyue.lastleg.appointmentplanning;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@TableName("ll_appointment_followup")
public class AppointmentFollowup {
@TableId(type = IdType.INPUT) private Long id;
private Long sourceOrderId;
private String sourceKey;
private String customerId;
private String stage;
private Integer version;
private String contactedParty;
private String result;
private String nextAction;
private LocalDate followupDate;
private String operatorId;
private String operatorName;
private String commandKey;
private String requestHash;
private LocalDateTime createdAt;
}
@@ -0,0 +1,19 @@
package com.baiyue.lastleg.appointmentplanning;
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 java.util.List;
@Mapper
public interface AppointmentFollowupMapper extends BaseMapper<AppointmentFollowup> {
@Select("SELECT * FROM ll_appointment_followup WHERE source_key=#{sourceKey} AND customer_id=#{customerId} AND stage=#{stage} AND command_key=#{key}")
AppointmentFollowup command(@Param("sourceKey") String sourceKey, @Param("customerId") String customerId, @Param("stage") String stage, @Param("key") String key);
@Select("SELECT COALESCE(MAX(version),0) FROM ll_appointment_followup WHERE source_key=#{sourceKey} AND customer_id=#{customerId} AND stage=#{stage}")
int version(@Param("sourceKey") String sourceKey, @Param("customerId") String customerId, @Param("stage") String stage);
@Select("SELECT * FROM ll_appointment_followup WHERE source_key=#{sourceKey} AND customer_id=#{customerId} ORDER BY created_at DESC,id DESC LIMIT #{size} OFFSET #{offset}")
List<AppointmentFollowup> page(@Param("sourceKey") String sourceKey, @Param("customerId") String customerId, @Param("size") int size, @Param("offset") long offset);
@Select("SELECT COUNT(*) FROM ll_appointment_followup WHERE source_key=#{sourceKey} AND customer_id=#{customerId}")
long count(@Param("sourceKey") String sourceKey, @Param("customerId") String customerId);
}
@@ -0,0 +1,83 @@
package com.baiyue.lastleg.appointmentplanning;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baiyue.common.core.api.PageResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.constraints.*;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.Instant;
import java.util.Set;
@Service
public class AppointmentFollowupService {
private final AppointmentSourceService sources;
private final AppointmentFollowupMapper mapper;
private final ObjectMapper json;
public AppointmentFollowupService(AppointmentSourceService sources, AppointmentFollowupMapper mapper, ObjectMapper json) {
this.sources = sources; this.mapper = mapper; this.json = json;
}
public record Save(@NotBlank @Size(max=32) String stage, @Min(0) int expectedVersion,
@NotBlank @Size(max=64) String idempotencyKey,
@Size(max=200) String contactedParty, @NotBlank @Size(max=1000) String result,
@Size(max=500) String nextAction, LocalDate followupDate) { }
public record Record(String stage, int version, String contactedParty, String result, String nextAction,
LocalDate followupDate, String operatorName, Instant createdAt) { }
public record History(PageResult<Record> history, java.util.Map<String,Integer> versions) { }
private static final Set<String> STAGES = Set.of("DRAYAGE_CONTACT", "TERMINAL_APPOINTMENT", "WAREHOUSE_RECEIVING", "FBA_RECEIVING");
public History history(String sourceKey, String customerId, int page, int size) {
if (page<1 || size<1 || size>100) throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"分页参数无效");
long total = mapper.count(sourceKey,customerId);
if (total == 0) sources.resolve(sourceKey,customerId,null);
var records = mapper.page(sourceKey,customerId,size,(long)(page-1)*size).stream().map(AppointmentFollowupService::view).toList();
var versions = new java.util.LinkedHashMap<String,Integer>();
STAGES.stream().sorted().forEach(stage -> versions.put(stage, mapper.version(sourceKey,customerId,stage)));
return new History(new PageResult<>(records,page,size,total,(total+size-1)/size),versions);
}
@Transactional(isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED)
public Record save(String sourceKey, String customerId, Save request, String operatorId, String operatorName) {
if (!STAGES.contains(request.stage())) throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"请选择有效跟进事项");
if (request.followupDate()!=null && (request.nextAction()==null || request.nextAction().isBlank())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"设置跟进日期时请填写下一步安排");
}
final String hash;
try { hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest((customerId+"\n"+operatorId+"\n"+json.writeValueAsString(request)).getBytes(StandardCharsets.UTF_8))); }
catch (JsonProcessingException | NoSuchAlgorithmException error) { throw new IllegalStateException("无法保存跟进请求",error); }
var existing = mapper.command(sourceKey,customerId,request.stage(),request.idempotencyKey());
if (existing!=null) {
if (!hash.equals(existing.getRequestHash())) throw new ResponseStatusException(HttpStatus.CONFLICT,"重复请求内容不一致,请核对跟进记录");
return view(existing);
}
var source = sources.resolve(sourceKey,customerId,null);
if (!source.canFollowup()) throw new ResponseStatusException(HttpStatus.CONFLICT,"当前来源仅可查看,请先核对承运状态");
if (mapper.version(sourceKey,customerId,request.stage())!=request.expectedVersion()) throw new ResponseStatusException(HttpStatus.CONFLICT,"跟进记录已更新,请重新读取后提交");
var value = new AppointmentFollowup(); value.setId(IdWorker.getId()); value.setSourceOrderId(source.orderId()); value.setSourceKey(source.sourceKey()); value.setCustomerId(source.customerId());
value.setStage(request.stage()); value.setVersion(request.expectedVersion()+1); value.setContactedParty(clean(request.contactedParty()));
value.setResult(request.result().trim()); value.setNextAction(clean(request.nextAction())); value.setFollowupDate(request.followupDate());
value.setOperatorId(operatorId); value.setOperatorName(clean(operatorName)); value.setCommandKey(request.idempotencyKey());
value.setRequestHash(hash); value.setCreatedAt(LocalDateTime.now(ZoneOffset.UTC));
try { mapper.insert(value); }
catch (org.springframework.dao.DuplicateKeyException conflict) {
var raced = mapper.command(sourceKey,customerId,request.stage(),request.idempotencyKey());
if (raced!=null && hash.equals(raced.getRequestHash())) return view(raced);
throw new ResponseStatusException(HttpStatus.CONFLICT,"跟进记录已更新或请求内容冲突,请重新读取",conflict);
}
return view(value);
}
private static String clean(String value) { return value==null || value.isBlank() ? null : value.trim(); }
private static Record view(AppointmentFollowup row) {
return new Record(row.getStage(),row.getVersion(),row.getContactedParty(),row.getResult(),row.getNextAction(),row.getFollowupDate(),row.getOperatorName(),row.getCreatedAt().toInstant(ZoneOffset.UTC));
}
}
@@ -0,0 +1,70 @@
package com.baiyue.lastleg.appointmentplanning;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.core.api.PageResult;
import com.baiyue.common.security.AuthenticatedUser;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import jakarta.validation.Valid;
import org.springframework.web.server.ResponseStatusException;
@RestController
@RequestMapping("/api/platform/v1/last-leg/appointment-planning")
public class AppointmentPlanningController {
private final AppointmentCargoService service;
private final AppointmentFollowupService followups;
private final AppointmentSourceService sources;
private final AppointmentCoverageService coverage;
public AppointmentPlanningController(AppointmentCargoService service, AppointmentFollowupService followups,
AppointmentSourceService sources, AppointmentCoverageService coverage) {
this.service = service; this.followups = followups; this.sources = sources; this.coverage = coverage;
}
public record Resolved(AppointmentSourceService.Source source, AppointmentCoverageService.Coverage coverage) { }
@GetMapping("/sources/resolve")
@PreAuthorize("hasAuthority('platform:appointment:list') and hasAuthority('platform:overseas-warehouse:last-mile-order:list')")
public ApiResponse<Resolved> resolve(@AuthenticationPrincipal AuthenticatedUser user,
@RequestParam String sourceKey, @RequestParam String customerId, @RequestParam(required=false) String destinationKey) {
requirePlatform(user);
var source = sources.resolve(sourceKey,customerId,destinationKey);
var result = coverage.query(java.util.List.of(new AppointmentCoverageService.SourceRef(source.customerId(),source.sourceKey(),source.destinationKey())));
return ApiResponse.success(new Resolved(source,result.get(0)));
}
@GetMapping("/cargo")
@PreAuthorize("hasAuthority('platform:appointment:list') and hasAuthority('platform:overseas-warehouse:last-mile-order:list')")
public ApiResponse<PageResult<AppointmentCargo>> cargo(@AuthenticationPrincipal AuthenticatedUser user,
@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String warehouseId, @RequestParam(required = false) String destination,
@RequestParam(required = false) String keyword) {
requirePlatform(user);
return ApiResponse.success(service.page(page, size, warehouseId, destination, keyword));
}
@GetMapping("/sources/{sourceKey}/follow-ups")
@PreAuthorize("hasAuthority('platform:appointment:list') and hasAuthority('platform:overseas-warehouse:last-mile-order:list')")
public ApiResponse<AppointmentFollowupService.History> history(@AuthenticationPrincipal AuthenticatedUser user,
@PathVariable String sourceKey, @RequestParam String customerId, @RequestParam(defaultValue="1") int page, @RequestParam(defaultValue="20") int size) {
requirePlatform(user); return ApiResponse.success(followups.history(sourceKey,customerId,page,size));
}
@PostMapping("/sources/{sourceKey}/follow-ups")
@PreAuthorize("hasAuthority('platform:appointment:list') and hasAuthority('platform:overseas-warehouse:last-mile-order:list') and hasAuthority('platform:appointment:followup')")
public ApiResponse<AppointmentFollowupService.Record> followup(@AuthenticationPrincipal AuthenticatedUser user,
@PathVariable String sourceKey, @RequestParam String customerId, @Valid @RequestBody AppointmentFollowupService.Save request) {
requirePlatform(user);
return ApiResponse.success(followups.save(sourceKey,customerId,request,user.userId().toString(),user.displayName()==null ? user.username() : user.displayName()));
}
private static void requirePlatform(AuthenticatedUser user) {
if (user == null || user.userId()==null) throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
if (!"PLATFORM".equals(user.appCode()) || !Long.valueOf(0).equals(user.tenantId())) throw new ResponseStatusException(HttpStatus.FORBIDDEN);
}
}
@@ -0,0 +1,83 @@
package com.baiyue.lastleg.appointmentplanning;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/** Stage-specific planning rules. Planning never creates stock, vehicles or carrier confirmations. */
public final class AppointmentPlanningPolicy {
private AppointmentPlanningPolicy() { }
public record Cargo(String sourceKey, String customerId, String originWarehouseId,
String destinationKey, String originCountry, String destinationCountry,
Integer packages, Instant readyFrom, Instant readyTo,
boolean eligibleForPlanning, String blockReason) { }
public record Group(String originWarehouseId, String destinationKey, long packages,
int sourceCount, int customerCount, Instant readyFrom, Instant readyTo,
boolean readinessIncomplete) { }
public record Forecast(String sourceKey, String sourceVersion, Instant eta, Instant readyAt) { }
public record Impact(String sourceKey, String reason, Instant previousEta, Instant latestEta,
Instant confirmedAt, boolean reviewRequired) { }
public static Group group(List<Cargo> cargo) {
if (cargo == null || cargo.isEmpty()) throw new IllegalArgumentException("请选择需要安排的真实货物");
if (cargo.size() > 500) throw new IllegalArgumentException("每批最多选择500条来源货物");
Set<String> sources = new HashSet<>();
Set<String> customers = new HashSet<>();
String origin = null, destination = null;
long packages = 0;
Instant from = null, to = null;
boolean incomplete = false;
for (Cargo row : cargo) {
if (row == null || blank(row.sourceKey()) || blank(row.customerId())) {
throw new IllegalArgumentException("货物缺少稳定来源或客户归属");
}
if (!sources.add(row.sourceKey())) throw new IllegalArgumentException("同一来源货物不能重复选择");
if (!row.eligibleForPlanning()) throw new IllegalArgumentException(
blank(row.blockReason()) ? "所选货物暂不具备筹划资格" : row.blockReason());
if (!"US".equals(row.originCountry()) || !"US".equals(row.destinationCountry())) {
throw new IllegalArgumentException("请选择已确认美国起运点及目的地的货物");
}
if (blank(row.originWarehouseId()) || blank(row.destinationKey())) {
throw new IllegalArgumentException("货物缺少实际接仓点或目的地");
}
if (origin == null) { origin = row.originWarehouseId(); destination = row.destinationKey(); }
if (!origin.equals(row.originWarehouseId()) || !destination.equals(row.destinationKey())) {
throw new IllegalArgumentException("同批货物必须具有相同实际起运仓和目的地");
}
if (row.packages() == null || row.packages() <= 0) throw new IllegalArgumentException("货物箱数待核实,不能填默认数量");
packages = Math.addExact(packages, row.packages().longValue());
customers.add(row.customerId());
if (row.readyFrom() == null || row.readyTo() == null) incomplete = true;
if (row.readyFrom() != null && row.readyTo() != null && row.readyTo().isBefore(row.readyFrom())) {
throw new IllegalArgumentException("货物预计备妥窗口无效");
}
if (row.readyFrom() != null && (from == null || row.readyFrom().isAfter(from))) from = row.readyFrom();
if (row.readyTo() != null && (to == null || row.readyTo().isBefore(to))) to = row.readyTo();
}
if (from != null && to != null && to.isBefore(from)) throw new IllegalArgumentException("所选货物预计备妥窗口不相容,请分别安排");
return new Group(origin, destination, packages, sources.size(), customers.size(), from, to, incomplete);
}
/** A new forecast only requests review; it never changes an externally confirmed appointment. */
public static Impact compare(Forecast acknowledged, Forecast latest, Instant confirmedAt) {
if (acknowledged == null || latest == null || blank(latest.sourceKey())
|| !Objects.equals(acknowledged.sourceKey(), latest.sourceKey())) {
throw new IllegalArgumentException("只能比较同一真实货源的预测");
}
boolean changed = !Objects.equals(acknowledged.eta(), latest.eta())
|| !Objects.equals(acknowledged.readyAt(), latest.readyAt());
String reason = "UNCHANGED";
if (changed) {
reason = latest.eta() == null ? "FORECAST_MISSING" : "FORECAST_CHANGED";
if (confirmedAt != null && latest.readyAt() != null && latest.readyAt().isAfter(confirmedAt)) {
reason = "READINESS_AFTER_APPOINTMENT";
}
}
return new Impact(latest.sourceKey(), reason, acknowledged.eta(), latest.eta(), confirmedAt, changed);
}
private static boolean blank(String value) { return value == null || value.isBlank(); }
}
@@ -0,0 +1,86 @@
package com.baiyue.lastleg.appointmentplanning;
import com.baiyue.lastleg.mapper.LastlegOrderMapper;
import com.baiyue.lastleg.shipping.mapper.ContainerShippingGateMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
@Service
public class AppointmentSourceService {
public record Source(String sourceKey, String customerId, Long orderId, String inboundCode, String bookingNo,
String containerNo, String originWarehouseId, String originWarehouseName,
String destinationKey, String destinationWarehouseCode, Integer packages,
String sourceVersion, boolean canFollowup, List<String> blockReasons) { }
private final LastlegOrderMapper orders;
private final ContainerShippingGateMapper shipping;
private final AppointmentExternalSourceGateway external;
private final AppointmentWarehouseClient warehouses;
private final String token;
public AppointmentSourceService(LastlegOrderMapper orders, ContainerShippingGateMapper shipping,
AppointmentExternalSourceGateway external, AppointmentWarehouseClient warehouses,
@Value("${baiyue.security.internal-service-token:}") String token) {
this.orders=orders; this.shipping=shipping; this.external=external; this.warehouses=warehouses; this.token=token;
}
public Source resolve(String sourceKey,String customerId,String destinationKey) {
if (blank(sourceKey) || sourceKey.length()>160 || blank(customerId) || customerId.length()>128) throw bad("请选择完整的真实货源");
com.baiyue.lastleg.entity.LastlegOrder order=null;
String bookingNo=null,origin,destination,version;
Integer packages;
boolean followup=true;
List<String> reasons=List.of();
if (sourceKey.startsWith("ORDER:")) {
long id;
try { id=Long.parseLong(sourceKey.substring(6)); if (id<=0 || !sourceKey.equals("ORDER:"+id)) throw new NumberFormatException(); }
catch (NumberFormatException error) { throw bad("货源标识无效"); }
order=orders.selectById(id);
if (order==null || !customerId.equals(order.getCustomerId())) throw missing();
if (!"FIRST_LEG".equals(order.getOrderType())) throw bad("请从原外接登记继续跟进,避免重复建立货源");
var gate=order.getSourceContainerBookingId()==null ? null : shipping.selectById(order.getSourceContainerBookingId());
if (gate==null || gate.getNodeSequence()==null || gate.getNodeSequence()<40) throw bad("货物尚无已开船或后续实际船节点");
origin=order.getOverseasWarehouseId(); destination="FBA:"+order.getFbaWarehouseCode();
if (!"FBA".equals(order.getDestinationType())) throw bad("当前货源不是FBA送仓货物");
packages=order.getPackageCount(); version=order.getVersion()==null ? null : "ORDER:"+order.getVersion();
} else if (sourceKey.startsWith("BOOKING:")) {
bookingNo=sourceKey.substring(8);
if (blank(bookingNo)) throw bad("外接登记号不能为空");
var matches=external.resolve(List.of(new AppointmentExternalSourceGateway.SourceRef(customerId,bookingNo)));
if (matches.size()!=1) throw missing();
var source=matches.get(0);
if (!Objects.equals(source.customerId(),customerId) || !Objects.equals(source.bookingNo(),bookingNo)) throw missing();
origin=source.warehouseId(); destination=source.destinationKey(); packages=source.packageCount();
version=source.recordVersion()==null ? null : "BOOKING:"+source.recordVersion();
followup=Set.of("CONFIRMED","RECEIVED","BOUND").contains(source.bookingStatus()==null ? "" : source.bookingStatus());
if (!followup) reasons=List.of("当前登记尚未确认承运或已取消,仅可查看跟进记录");
if (source.orderId()!=null) {
order=orders.selectById(source.orderId());
if (order==null || !customerId.equals(order.getCustomerId())) throw missing();
if (!Objects.equals(order.getOverseasWarehouseId(),origin)) throw bad("来货的接仓点与原登记不一致,请先核对");
if (!"FBA".equals(order.getDestinationType()) || !Objects.equals(destination,"FBA:"+order.getFbaWarehouseCode())) throw bad("来货目的仓与原登记不一致,请先核对");
packages=order.getPackageCount();
}
} else throw bad("不支持的货源类型");
if (order!=null && Set.of("CANCELLED","COMPLETED").contains(order.getCurrentStatus()==null ? "" : order.getCurrentStatus())) {
followup=false; reasons=List.of("该货物已取消或完成,仅可查看跟进记录");
}
if (!blank(destinationKey) && !Objects.equals(destination,destinationKey)) throw bad("目的地已变化,请返回原业务重新核对");
if (destination==null || !destination.startsWith("FBA:")) throw bad("当前仅支持FBA收货跟进来源");
var catalog=catalog(); final String originId=origin; final String code=destination.substring(4);
var warehouse=catalog.stream().filter(w -> w.id()!=null && w.id().toString().equals(originId) && "US".equals(w.countryCode())
&& Set.of("OVERSEAS","OVERSEAS_PARTNER").contains(w.warehouseType()==null ? "" : w.warehouseType())).findFirst().orElseThrow(() -> bad("接仓点不在启用的美国仓目录中"));
if (catalog.stream().noneMatch(w -> "FBA".equals(w.warehouseType()) && "US".equals(w.countryCode()) && code.equals(w.warehouseCode()))) throw bad("目的仓不在启用的美国FBA目录中");
return new Source(sourceKey,customerId,order==null ? null : order.getId(),order==null ? null : order.getInboundCode(),bookingNo,
order==null ? null : order.getContainerNo(),origin,warehouse.warehouseName(),destination,code,packages,version,followup,reasons);
}
private List<AppointmentWarehouseClient.Warehouse> catalog() {
try { var result=warehouses.catalog(token); if (result==null || !result.successful() || result.data()==null) throw new IllegalStateException(); return result.data().stream().filter(Objects::nonNull).toList(); }
catch (RuntimeException error) { throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE,"仓库目录暂不可用,请稍后重新核对",error); }
}
private static boolean blank(String value) { return value==null || value.isBlank(); }
private static ResponseStatusException bad(String message) { return new ResponseStatusException(HttpStatus.BAD_REQUEST,message); }
private static ResponseStatusException missing() { return new ResponseStatusException(HttpStatus.NOT_FOUND,"未找到当前客户的货物来源"); }
}
@@ -0,0 +1,42 @@
package com.baiyue.lastleg.appointmentplanning;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
/** Resolves a location's appointment window without using the operator's system time zone. */
public final class AppointmentTimePolicy {
private AppointmentTimePolicy() { }
public record Window(Instant start, Instant end, String timezone) { }
public static Window resolve(LocalDateTime start, LocalDateTime end, String timezone,
ZoneOffset startOffset, ZoneOffset endOffset) {
if (start == null) throw new IllegalArgumentException("请填写预约开始时间");
if (timezone == null || timezone.isBlank()) throw new IllegalArgumentException("请先补齐预约地点时区");
final ZoneId zone;
try { zone = ZoneId.of(timezone); }
catch (DateTimeException error) { throw new IllegalArgumentException("预约地点时区无效", error); }
if (zone instanceof ZoneOffset) throw new IllegalArgumentException("预约地点需要地区时区,不能仅填写固定时差");
Instant first = instant(start, zone, startOffset);
Instant last = end == null ? null : instant(end, zone, endOffset);
if (end == null && endOffset != null) throw new IllegalArgumentException("未填写结束时间,不能指定结束时差");
if (last != null && !last.isAfter(first)) throw new IllegalArgumentException("预约结束时间必须晚于开始时间");
return new Window(first, last, zone.getId());
}
private static Instant instant(LocalDateTime value, ZoneId zone, ZoneOffset selected) {
List<ZoneOffset> offsets = zone.getRules().getValidOffsets(value);
if (offsets.isEmpty()) throw new IllegalArgumentException("该当地时间因夏令时切换不存在,请重新选择");
if (selected == null && offsets.size() > 1) {
throw new IllegalArgumentException("该当地时间在夏令时切换期间出现两次,请明确时差");
}
if (selected != null && !offsets.contains(selected)) {
throw new IllegalArgumentException("所选时差与预约地点及日期不符");
}
return value.toInstant(selected == null ? offsets.get(0) : selected);
}
}
@@ -0,0 +1,14 @@
package com.baiyue.lastleg.appointmentplanning;
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 = "appointmentWarehouseClient", url = "${baiyue.clients.domestic-warehouse.url:}")
public interface AppointmentWarehouseClient {
@GetMapping("/internal/warehouses/order-catalog")
ApiResponse<List<Warehouse>> catalog(@RequestHeader("X-Internal-Service-Token") String token);
record Warehouse(Long id, String warehouseCode, String warehouseName, String warehouseType, String countryCode) { }
}