212 lines
12 KiB
Java
212 lines
12 KiB
Java
package com.baiyue.firstleg.service;
|
|
|
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
|
import com.baiyue.common.core.api.PageResult;
|
|
import com.baiyue.firstleg.dto.InboundOrderDetail;
|
|
import com.baiyue.firstleg.dto.UnifiedInboundDetail;
|
|
import com.baiyue.firstleg.dto.UnifiedInboundQuery;
|
|
import com.baiyue.firstleg.dto.UnifiedInboundSummary;
|
|
import com.baiyue.firstleg.entity.InboundOrderEntity;
|
|
import com.baiyue.firstleg.entity.InboundTransportSnapshotEntity;
|
|
import com.baiyue.firstleg.loading.entity.LoadingEvidenceEntity;
|
|
import com.baiyue.firstleg.repository.InboundOrderRepository;
|
|
import com.baiyue.firstleg.repository.UnifiedInboundReadRepository;
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import jakarta.annotation.Resource;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.util.StringUtils;
|
|
|
|
import java.time.LocalDateTime;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Set;
|
|
import java.util.stream.Collectors;
|
|
|
|
/** Read-only adapter from internal inbound states to the product main statuses. */
|
|
@Service
|
|
public class UnifiedInboundQueryService {
|
|
private static final Set<String> MAIN_STATUSES = Set.of(
|
|
"PENDING_REVIEW", "WAIT_MEASURE", "INBOUNDED", "WAIT_SPLIT", "LOADING", "LOADED", "DELIVERED");
|
|
private static final Set<String> REVIEW_STATUSES = Set.of("UNRECORDED", "PENDING", "APPROVED", "REJECTED");
|
|
|
|
@Resource private InboundOrderRepository inbounds;
|
|
@Resource private UnifiedInboundReadRepository operations;
|
|
@Resource private ObjectMapper json;
|
|
|
|
public PageResult<UnifiedInboundSummary> page(UnifiedInboundQuery query) {
|
|
validate(query);
|
|
if ("PENDING_REVIEW".equals(query.mainStatus())
|
|
|| query.candidateOrderIds() != null && query.candidateOrderIds().isEmpty()) {
|
|
return new PageResult<>(List.of(), query.page(), query.size(), 0, 0);
|
|
}
|
|
Page<InboundOrderEntity> source = inbounds.pageUnifiedEntities(query, internalStatuses(query.mainStatus()));
|
|
List<UnifiedInboundSummary> records = summaries(source.getRecords());
|
|
return new PageResult<>(records, source.getCurrent(), source.getSize(), source.getTotal(), source.getPages());
|
|
}
|
|
|
|
public List<UnifiedInboundSummary> summaries(Long tenantId, List<Long> orderIds) {
|
|
Map<Long, UnifiedInboundSummary> byOrder = new LinkedHashMap<>();
|
|
for (UnifiedInboundSummary item : summaries(inbounds.findByOrderIds(tenantId, orderIds)))
|
|
byOrder.putIfAbsent(item.inbound().orderId(), item);
|
|
return orderIds.stream().distinct().map(byOrder::get).filter(java.util.Objects::nonNull).toList();
|
|
}
|
|
|
|
public UnifiedInboundDetail detail(long tenantId, long orderId) {
|
|
InboundOrderEntity inbound = inbounds.findByOrderId(tenantId, orderId);
|
|
if (inbound == null) return null;
|
|
InboundOrderDetail detail = inbounds.detail(tenantId, inbound);
|
|
String mainStatus = mainStatus(inbound.getProcessStatus());
|
|
boolean includePhaseThree = requiresPhaseThreeSummary(mainStatus);
|
|
List<UnifiedInboundDetail.TimelineEvent> timeline = detail.statusHistory().stream()
|
|
.map(item -> new UnifiedInboundDetail.TimelineEvent(
|
|
"FIRSTLEG", "STATUS", item.fromStatus(), item.toStatus(), item.action(), item.reason(),
|
|
item.operatorId(), item.operatorName(), item.occurredAt()))
|
|
.toList();
|
|
// Phase-three tables are optional during the phase-two measurement workflow.
|
|
com.baiyue.firstleg.split.entity.PreloadPlanEntity preload = null;
|
|
com.baiyue.firstleg.loading.entity.InboundLoadingPickTaskEntity pick = null;
|
|
List<LoadingEvidenceEntity> evidence = List.of();
|
|
LocalDateTime deliveryAt = null;
|
|
if (includePhaseThree) {
|
|
preload = operations.findPreload(tenantId, inbound.getId());
|
|
pick = operations.findPick(tenantId, inbound.getId());
|
|
evidence = operations.findEvidence(tenantId, inbound.getId());
|
|
deliveryAt = deliveryAt(detail.statusHistory());
|
|
}
|
|
InboundTransportSnapshotEntity transport = includePhaseThree
|
|
? operations.findTransport(tenantId, inbound.getId()) : null;
|
|
return new UnifiedInboundDetail(summary(inbound, detail, preload, pick, evidence, deliveryAt, transport, null), timeline);
|
|
}
|
|
|
|
private List<UnifiedInboundSummary> summaries(List<InboundOrderEntity> records) {
|
|
Map<Long, Long> phaseThreeOwners = records.stream()
|
|
.filter(inbound -> requiresPhaseThreeSummary(mainStatus(inbound.getProcessStatus())))
|
|
.collect(Collectors.toMap(
|
|
InboundOrderEntity::getId, InboundOrderEntity::getTenantId, (left, right) -> left));
|
|
var preloads = operations.findPreloads(phaseThreeOwners);
|
|
var picks = operations.findPicks(phaseThreeOwners);
|
|
var evidences = operations.findEvidence(phaseThreeOwners);
|
|
var deliveries = operations.findDeliveryHistory(phaseThreeOwners);
|
|
var transports = operations.findTransports(phaseThreeOwners);
|
|
Map<Long, Long> owners = records.stream().collect(Collectors.toMap(
|
|
InboundOrderEntity::getId, InboundOrderEntity::getTenantId, (left, right) -> left));
|
|
var locationCodes = inbounds.locationCodesMap(null, owners);
|
|
return records.stream().map(inbound -> summary(inbound, null, preloads.get(inbound.getId()),
|
|
picks.get(inbound.getId()), evidences.getOrDefault(inbound.getId(), List.of()),
|
|
deliveries.get(inbound.getId()) == null ? null : deliveries.get(inbound.getId()).getOccurredAt(),
|
|
transports.get(inbound.getId()), locationCodes.get(inbound.getId()))).toList();
|
|
}
|
|
|
|
private UnifiedInboundSummary summary(InboundOrderEntity inbound, InboundOrderDetail detail,
|
|
com.baiyue.firstleg.split.entity.PreloadPlanEntity preload,
|
|
com.baiyue.firstleg.loading.entity.InboundLoadingPickTaskEntity pick,
|
|
List<LoadingEvidenceEntity> evidence, LocalDateTime deliveryAt,
|
|
InboundTransportSnapshotEntity transport, String locationCodes) {
|
|
String mainStatus = mainStatus(inbound.getProcessStatus());
|
|
List<LoadingEvidenceEntity> activeEvidence = evidence.stream()
|
|
.filter(item -> item.getStatus() == null || "ACTIVE".equals(item.getStatus())).toList();
|
|
String sealNo = activeEvidence.stream().filter(item -> "SEAL".equals(item.getEvidenceType()))
|
|
.map(LoadingEvidenceEntity::getSealNo).filter(StringUtils::hasText).findFirst().orElse(null);
|
|
var preloadSummary = preload == null ? null : new UnifiedInboundSummary.PreloadSummary(
|
|
preload.getStatus(), preload.getVersion(), itemCount(preload.getItemsJson()), preload.getUpdatedAt());
|
|
var loadingSummary = pick == null && activeEvidence.isEmpty() ? null : new UnifiedInboundSummary.LoadingSummary(
|
|
pick == null ? null : pick.getStatus(), pick == null ? null : pick.getVersion(),
|
|
pick == null ? null : pick.getVersion(), pick == null ? null : pick.getExpectedCount(),
|
|
pick == null ? null : pick.getPickedCount(), activeEvidence.size(), sealNo,
|
|
pick == null ? activeEvidence.stream().map(LoadingEvidenceEntity::getUpdatedAt)
|
|
.filter(java.util.Objects::nonNull).max(LocalDateTime::compareTo).orElse(null) : pick.getUpdatedAt());
|
|
var deliverySummary = "LOADED".equals(mainStatus) || "DELIVERED".equals(mainStatus)
|
|
? new UnifiedInboundSummary.DeliverySummary(
|
|
"DELIVERED".equals(mainStatus) ? "COMPLETED" : "PENDING", deliveryAt,
|
|
inbound.getExpressTrackingNo()) : null;
|
|
var inboundSummary = detail == null
|
|
? com.baiyue.firstleg.dto.InboundOrderSummary.from(inbound, transport, locationCodes) : detail.summary();
|
|
return new UnifiedInboundSummary(inboundSummary, mainStatus,
|
|
nextAction(mainStatus, inbound.getProcessStatus(), preload == null ? null : preload.getStatus()),
|
|
preloadSummary, loadingSummary, deliverySummary);
|
|
}
|
|
|
|
private LocalDateTime deliveryAt(List<InboundOrderDetail.StatusHistorySummary> history) {
|
|
return history.stream()
|
|
.filter(item -> "COMPLETE_DELIVERY".equals(item.action()) || "DELIVERED".equals(item.toStatus()))
|
|
.map(InboundOrderDetail.StatusHistorySummary::occurredAt)
|
|
.filter(java.util.Objects::nonNull).max(LocalDateTime::compareTo).orElse(null);
|
|
}
|
|
|
|
static String mainStatus(String status) {
|
|
if (status == null) return null;
|
|
return switch (status) {
|
|
case "WAIT_MEASURE", "MEASURING", "MEASURE_PENDING", "MEASURE_REJECTED",
|
|
"WAIT_PRICING", "FEE_CONFIRMING", "INBOUNDING" -> "WAIT_MEASURE";
|
|
case "INBOUNDED", "WAIT_SPLIT", "LOADING", "LOADED", "DELIVERED" -> status;
|
|
default -> null;
|
|
};
|
|
}
|
|
|
|
static String nextAction(String mainStatus, String processStatus, String preloadStatus) {
|
|
if (mainStatus == null) return null;
|
|
return switch (mainStatus) {
|
|
case "PENDING_REVIEW" -> "APPROVE_ORDER";
|
|
case "WAIT_MEASURE" -> "MEASURE_PENDING".equals(processStatus) ? "CONFIRM_MEASUREMENT" : null;
|
|
case "INBOUNDED", "WAIT_SPLIT" -> !("INBOUNDED".equals(processStatus) || "WAIT_SPLIT".equals(processStatus)) ? null
|
|
: "CONFIRMED".equals(preloadStatus) ? null
|
|
: preloadStatus == null ? "SMART_SPLIT" : "CONFIRM_PRELOAD";
|
|
case "LOADING" -> "COMPLETE_LOADING";
|
|
case "LOADED" -> null;
|
|
case "DELIVERED" -> null;
|
|
default -> null;
|
|
};
|
|
}
|
|
|
|
static boolean requiresPhaseThreeSummary(String mainStatus) {
|
|
return mainStatus != null && Set.of("LOADING", "LOADED", "DELIVERED").contains(mainStatus);
|
|
}
|
|
|
|
private List<String> internalStatuses(String mainStatus) {
|
|
if (!StringUtils.hasText(mainStatus)) return List.of();
|
|
return switch (mainStatus) {
|
|
case "WAIT_MEASURE" -> List.of("WAIT_MEASURE", "MEASURING", "MEASURE_PENDING", "MEASURE_REJECTED",
|
|
"WAIT_PRICING", "FEE_CONFIRMING", "INBOUNDING");
|
|
case "INBOUNDED" -> List.of("INBOUNDED");
|
|
case "WAIT_SPLIT" -> List.of("WAIT_SPLIT");
|
|
case "LOADING", "LOADED", "DELIVERED" -> List.of(mainStatus);
|
|
default -> List.of("__NO_MATCH__");
|
|
};
|
|
}
|
|
|
|
private int itemCount(String itemsJson) {
|
|
if (!StringUtils.hasText(itemsJson)) return 0;
|
|
try {
|
|
JsonNode node = json.readTree(itemsJson);
|
|
return node.isArray() ? node.size() : 0;
|
|
} catch (Exception ignored) {
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
private void validate(UnifiedInboundQuery query) {
|
|
if (StringUtils.hasText(query.mainStatus())
|
|
&& !MAIN_STATUSES.contains(query.mainStatus())
|
|
) {
|
|
throw new com.baiyue.common.core.exception.BizException(
|
|
com.baiyue.common.core.api.ResultCode.BAD_REQUEST, "统一订单主状态不合法");
|
|
}
|
|
if (query.createdFrom() != null && query.createdTo() != null
|
|
&& query.createdFrom().isAfter(query.createdTo())) {
|
|
throw new com.baiyue.common.core.exception.BizException(
|
|
com.baiyue.common.core.api.ResultCode.BAD_REQUEST, "创建时间起点不能晚于终点");
|
|
}
|
|
if (StringUtils.hasText(query.feeReviewStatus()) && !REVIEW_STATUSES.contains(query.feeReviewStatus())) {
|
|
throw new com.baiyue.common.core.exception.BizException(
|
|
com.baiyue.common.core.api.ResultCode.BAD_REQUEST, "费用审核状态不合法");
|
|
}
|
|
if (StringUtils.hasText(query.measurementReviewStatus())
|
|
&& !REVIEW_STATUSES.contains(query.measurementReviewStatus())) {
|
|
throw new com.baiyue.common.core.exception.BizException(
|
|
com.baiyue.common.core.api.ResultCode.BAD_REQUEST, "测量审核状态不合法");
|
|
}
|
|
}
|
|
}
|