Merge branch 'dev' into dev-lyhfive

# Conflicts:
#	deploy/sql/头程数据库统一增量-MySQL8.sql
#	deploy/sql/海外区域统一增量-MySQL8.sql
#	lastleg-service/src/main/java/com/baiyue/lastleg/service/LoadingCompletedConsumer.java
#	lastleg-service/src/main/resources/db/lastleg.sql
#	lastleg-service/src/test/java/com/baiyue/lastleg/service/LoadingCompletedConsumerTest.java
This commit is contained in:
2026-08-26 16:05:24 +08:00
357 changed files with 7739 additions and 3505 deletions
@@ -44,8 +44,9 @@ public class InboundPlanController {
@PostMapping("/convert")
@PreAuthorize("hasAuthority('" + OverseasPermissions.INBOUND_ORDER_CREATE + "')")
/** 将入仓单转换为入仓计划。 */
@Operation(summary = "入仓单转入仓计划", description = "Required authority: " + OverseasPermissions.INBOUND_ORDER_CREATE)
/** 由平台人工将待分配尾程订单转换为入仓计划。 */
@Operation(summary = "人工创建入仓计划", description = "头程装柜完成只生成待分配尾程订单;平台确认后调用本接口创建入仓计划。Required authority: "
+ OverseasPermissions.INBOUND_ORDER_CREATE)
public ApiResponse<InboundPlanResponse> convert(@AuthenticationPrincipal AuthenticatedUser user,
@Valid @RequestBody ConvertInboundPlanRequest request) {
return ApiResponse.success(service.convert(scope(user, request.customerId()), request.orderId()));
@@ -3,6 +3,7 @@ package com.baiyue.lastleg.inboundplan.pda.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
@@ -14,7 +15,8 @@ public final class ReceivingContainerRequests {
public record Action(@NotBlank @Size(max = 255) String idempotencyKey) { }
public record Sign(@NotNull @Size(min = 3, max = 3) List<@Valid SignedPhoto> photos,
@NotBlank @Size(max = 255) String idempotencyKey) { }
public record SignedPhoto(@NotNull ReceivingPhotoRole role, @Positive long fileId) { }
public record SignedPhoto(@NotNull ReceivingPhotoRole role,
@NotBlank @Pattern(regexp = "^[1-9][0-9]{0,18}$") String fileId) { }
public record CartonResolve(@NotBlank String cartonMark) { }
public record SkuResolve(@NotBlank @Size(max = 128) String skuCode) { }
public record PalletResolve(@NotBlank String palletCode, @NotBlank String inboundCode) { }
@@ -17,7 +17,7 @@ public final class ReceivingContainerResponses {
int totalPackages, int receivedPackages, int pendingPackages,
List<Inbound> inbounds) { }
public record SignedPhoto(ReceivingPhotoRole role, long fileId) { }
public record SignedPhoto(ReceivingPhotoRole role, String fileId) { }
public record Inbound(String inboundCode, String destinationType,
String overseasWarehouseId, String overseasWarehouseName,
@@ -48,5 +48,5 @@ public final class ReceivingContainerResponses {
String destinationType, String palletCode, int acceptedPackages,
int receivedPackages, int pendingPackages, String sessionStatus) { }
public record Photo(long fileId, String fileName, String contentType, long sizeBytes) { }
public record Photo(String fileId, String fileName, String contentType, long sizeBytes) { }
}
@@ -169,7 +169,7 @@ public class ReceivingContainerService {
String customerId = session.getCustomerId();
if (!"WAIT_SIGN".equals(session.getStatus())) throw conflict("Unload photos can only be uploaded before signing");
UnloadPhotoFileGateway.UploadedFile uploaded = unloadPhotos.upload(customerId, session.getId(), operatorId, file);
return new ReceivingContainerResponses.Photo(uploaded.fileId(), uploaded.fileName(), uploaded.contentType(), uploaded.sizeBytes());
return new ReceivingContainerResponses.Photo(Long.toString(uploaded.fileId()), uploaded.fileName(), uploaded.contentType(), uploaded.sizeBytes());
}
@Transactional
@@ -181,7 +181,7 @@ public class ReceivingContainerService {
String customerId = session.getCustomerId();
if (!"WAIT_SIGN".equals(session.getStatus())) throw conflict("Container has already been signed");
List<ReceivingContainerResponses.SignedPhoto> photos = validateSignPhotos(request);
List<Long> photoFileIds = photos.stream().map(ReceivingContainerResponses.SignedPhoto::fileId).toList();
List<Long> photoFileIds = photos.stream().map(photo -> positiveFileId(photo.fileId())).toList();
photoFileIds.forEach(fileId -> unloadPhotos.validate(customerId, session.getId(), fileId));
LocalDateTime now = LocalDateTime.now();
session.setSignPhotos(write(photos)); session.setStatus("SIGNED"); session.setSignedAt(now);
@@ -513,9 +513,9 @@ public class ReceivingContainerService {
Set<com.baiyue.lastleg.inboundplan.pda.dto.ReceivingPhotoRole> roles = request.photos().stream()
.map(ReceivingContainerRequests.SignedPhoto::role).collect(Collectors.toSet());
if (roles.size() != 3 || roles.contains(null)) throw conflict("Each unload photo role is required exactly once");
Set<Long> fileIds = request.photos().stream().map(ReceivingContainerRequests.SignedPhoto::fileId)
Set<Long> fileIds = request.photos().stream().map(value -> positiveFileId(value.fileId()))
.collect(Collectors.toSet());
if (fileIds.size() != 3 || fileIds.stream().anyMatch(value -> value == null || value <= 0)) {
if (fileIds.size() != 3) {
throw conflict("Unload photo file IDs must be positive and unique");
}
return request.photos().stream()
@@ -523,6 +523,16 @@ public class ReceivingContainerService {
.map(value -> new ReceivingContainerResponses.SignedPhoto(value.role(), value.fileId())).toList();
}
private long positiveFileId(String value) {
try {
long fileId = Long.parseLong(value);
if (fileId > 0) return fileId;
} catch (NumberFormatException ignored) {
// Validation normally rejects this before the service; keep the domain fail-closed.
}
throw conflict("Unload photo file ID must be a positive decimal string");
}
private SkuRef requireSku(InboundRef ref, String skuCode) {
SkuRef result = skuRef(ref, skuCode);
if (result == null) throw notFound("SKU is not part of the selected inbound code");
@@ -18,6 +18,7 @@ import com.baiyue.lastleg.inboundplan.mapper.InboundPlanPalletAllocationMapper;
import com.baiyue.lastleg.inboundplan.mapper.InboundPlanPalletMapper;
import com.baiyue.lastleg.inboundplan.mapper.InboundPlanQueryMapper;
import com.baiyue.lastleg.inboundplan.model.SourceOrderSnapshot;
import com.baiyue.lastleg.inventory.mapper.InventoryBalanceMapper;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
@@ -41,6 +42,7 @@ public class InboundPlanService {
@Resource private InboundPlanPalletAllocationMapper allocationMapper;
@Resource private InboundPlanOrderMapper orderMapper;
@Resource private InboundPlanQueryMapper queryMapper;
@Resource private InventoryBalanceMapper inventoryBalanceMapper;
@Transactional(readOnly = true)
public PageResult<InboundPlanListResponse> page(String customerId, InboundPlanRequests.Query query) {
@@ -147,6 +149,8 @@ public class InboundPlanService {
if (orderMapper.markPlanned(customerId, order.orderId(), plan.getPlanNo(), count, now) != 1) {
throw new IllegalStateException("Failed to update order " + order.orderId());
}
inventoryBalanceMapper.bindInboundPlan(customerId, order.orderId(), order.inboundCode(),
plan.getPlanNo(), now);
orderMapper.insertHistory(customerId, order.orderId(), order.currentStatus(),
"Inbound order converted to inbound plan " + plan.getPlanNo(), now);
}
@@ -5,7 +5,9 @@ import com.baiyue.lastleg.inventory.model.InventorySummary;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.time.LocalDateTime;
import java.util.List;
public interface InventoryBalanceMapper extends BaseMapper<InventoryBalance> {
@@ -29,6 +31,14 @@ public interface InventoryBalanceMapper extends BaseMapper<InventoryBalance> {
@Param("inboundOrderId") Long inboundOrderId,
@Param("inboundCode") String inboundCode);
@Update("UPDATE ll_inventory_balance SET inbound_order_no=#{planNo},updated_at=#{updatedAt} " +
"WHERE customer_id=#{customerId} AND inbound_order_id=#{inboundOrderId} AND inbound_code=#{inboundCode}")
int bindInboundPlan(@Param("customerId") String customerId,
@Param("inboundOrderId") Long inboundOrderId,
@Param("inboundCode") String inboundCode,
@Param("planNo") String planNo,
@Param("updatedAt") LocalDateTime updatedAt);
@Select("<script>SELECT * FROM ll_inventory_balance WHERE customer_id=#{customerId}" +
"<if test='overseasWarehouseId != null and overseasWarehouseId != \"\"'> AND overseas_warehouse_id=#{overseasWarehouseId}</if>" +
"<if test='destinationWarehouseCode != null and destinationWarehouseCode != \"\"'> AND destination_warehouse_code=#{destinationWarehouseCode}</if>" +
@@ -1,10 +0,0 @@
package com.baiyue.lastleg.masterdata.exchange;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/** 注册尾程主数据域的所有 Mapper。 */
@Configuration
@MapperScan("com.baiyue.lastleg.masterdata")
public class ExchangeMapperConfiguration {
}
@@ -24,7 +24,7 @@ public interface PdaPalletOperationMapper extends BaseMapper<PdaPalletOperation>
@Param("idempotencyKey") String idempotencyKey);
@Select(CONTENT_SELECT + "WHERE b.overseas_warehouse_id=#{warehouseId} AND p.pallet_id=#{palletId} " +
"AND (p.available_packages+p.hold_packages+p.allocated_packages+p.picked_packages+p.receiving_packages)&gt;0 " +
"AND (p.available_packages+p.hold_packages+p.allocated_packages+p.picked_packages+p.receiving_packages)>0 " +
"ORDER BY b.customer_id,b.inbound_code,p.id")
List<PalletInventoryRow> content(@Param("warehouseId") String warehouseId,
@Param("palletId") long palletId);
@@ -71,6 +71,9 @@ public class PdaPalletOperationService {
public PalletOperationResponses.Operation assemble(PdaWarehouseIdentity identity,
PalletOperationRequests.Assemble request) {
PalletOperationResponses.Operation replay = replayIfPresent(identity, "PALLET_ASSEMBLE",
request.idempotencyKey(), request);
if (replay != null) return replay;
Map<String, PalletPhysicalGateway.PalletReference> pallets = resolvePallets(identity.overseasWarehouseId(),
request.target(), request.sources());
PalletPhysicalGateway.PalletReference target = pallets.get(code(request.target().palletCode()));
@@ -85,6 +88,9 @@ public class PdaPalletOperationService {
public PalletOperationResponses.Operation disassemble(PdaWarehouseIdentity identity,
PalletOperationRequests.Disassemble request) {
PalletOperationResponses.Operation replay = replayIfPresent(identity, "PALLET_DISASSEMBLE",
request.idempotencyKey(), request);
if (replay != null) return replay;
LinkedHashMap<String, PalletOperationRequests.PalletExpectation> expectations = new LinkedHashMap<>();
expectations.put(code(request.source().palletCode()), request.source());
request.targets().forEach(value -> expectations.put(code(value.target().palletCode()), value.target()));
@@ -109,6 +115,9 @@ public class PdaPalletOperationService {
public PalletOperationResponses.Operation swap(PdaWarehouseIdentity identity,
PalletOperationRequests.Swap request) {
PalletOperationResponses.Operation replay = replayIfPresent(identity, "PALLET_SWAP",
request.idempotencyKey(), request);
if (replay != null) return replay;
Map<String, PalletPhysicalGateway.PalletReference> pallets = resolvePallets(identity.overseasWarehouseId(),
request.source(), List.of(request.target()));
PalletPhysicalGateway.PalletReference source = pallets.get(code(request.source().palletCode()));
@@ -129,6 +138,9 @@ public class PdaPalletOperationService {
public PalletOperationResponses.Operation unbind(PdaWarehouseIdentity identity,
PalletOperationRequests.Unbind request) {
PalletOperationResponses.Operation replay = replayIfPresent(identity, "PALLET_UNBIND",
request.idempotencyKey(), request);
if (replay != null) return replay;
Map<String, PalletPhysicalGateway.PalletReference> pallets = resolvePallets(identity.overseasWarehouseId(),
List.of(request.source()));
PalletPhysicalGateway.PalletReference source = pallets.get(code(request.source().palletCode()));
@@ -264,7 +276,8 @@ public class PdaPalletOperationService {
ledger.setBusinessType(operation.getOperationType()); ledger.setBusinessOrderId(operation.getId());
ledger.setBusinessOrderNo(String.valueOf(operation.getId())); ledger.setInboundCode(balance.getInboundCode());
ledger.setInboundOrderNo(balance.getInboundOrderNo()); ledger.setIdempotencyKey(idempotencyKey);
ledger.setStatusFrom("PALLET:" + sourcePallet); ledger.setStatusTo("PALLET:" + targetPallet);
ledger.setStatusFrom("OCCUPIED");
ledger.setStatusTo("UNBOUND".equals(targetPallet) ? "UNBOUND" : "OCCUPIED");
ledger.setBeforePackages(before); ledger.setDeltaPackages(delta); ledger.setAfterPackages(after);
ledger.setOperatorId(identity.operatorKey()); ledger.setRemark(trim(reason));
ledger.setOccurredAt(LocalDateTime.now()); ledger.setCreatedAt(ledger.getOccurredAt()); ledgers.insert(ledger);
@@ -412,6 +425,15 @@ public class PdaPalletOperationService {
return value;
}
private PalletOperationResponses.Operation replayIfPresent(PdaWarehouseIdentity identity, String type,
String key, Object request) {
String normalizedKey = required(key, "幂等键不能为空");
PdaPalletOperation existing = mapper.findOperation(identity.operatorKey(), normalizedKey);
if (existing == null) return null;
validateExisting(existing, type, hash(request));
return read(existing).asReplay();
}
private void saveTransitions(long operationId, List<PalletPhysicalGateway.Transition> transitions) {
newTransaction.executeWithoutResult(status -> {
PdaPalletOperation operation = mapper.selectById(operationId);
@@ -117,8 +117,7 @@ public class PdaInventoryMoveService {
position.setWarehouseLocationId(target.locationId()); position.setWarehouseLocationCode(target.locationCode());
position.setVersion(value(position.getVersion()) + 1); position.setUpdatedAt(completedAt);
positions.updateById(position);
ledger(operation, position, balance, operatorKey, key, request.reason(), source.locationCode(),
target.locationCode(), completedAt);
ledger(operation, position, balance, operatorKey, key, request.reason(), completedAt);
}
operation.setPalletVersionAfter(relocated.afterVersion()); operation.setStatus("COMPLETED");
operation.setCompletedAt(completedAt);
@@ -150,18 +149,18 @@ public class PdaInventoryMoveService {
}
private void ledger(PdaInventoryMove operation, InventoryPosition position, InventoryBalance balance,
String operator, String key, String reason, String source, String target,
LocalDateTime now) {
String operator, String key, String reason, LocalDateTime now) {
InventoryLedger row = new InventoryLedger(); row.setId(IdWorker.getId()); row.setCustomerId(position.getCustomerId());
row.setBalanceId(balance.getId()); row.setPositionId(position.getId());
row.setOverseasWarehouseId(String.valueOf(operation.getOverseasWarehouseId()));
row.setDestinationWarehouseCode(balance.getDestinationWarehouseCode()); row.setInboundOrderId(balance.getInboundOrderId());
row.setPalletId(position.getPalletId()); row.setPalletNo(position.getPalletNo()); row.setBatchNo(position.getBatchNo());
row.setSkuCode(balance.getSkuCode()); row.setWarehouseLocationCode(target); row.setBusinessType("INTERNAL_MOVE");
row.setSkuCode(balance.getSkuCode()); row.setWarehouseLocationCode(position.getWarehouseLocationCode());
row.setBusinessType("INTERNAL_MOVE");
row.setBusinessOrderId(operation.getId()); row.setBusinessOrderNo(operation.getMoveNo());
row.setInboundCode(balance.getInboundCode()); row.setInboundOrderNo(balance.getInboundOrderNo());
row.setIdempotencyKey("MOVE:" + operation.getId() + ":" + position.getId());
row.setStatusFrom(source); row.setStatusTo(target); long packages = physical(position);
row.setStatusFrom("OCCUPIED"); row.setStatusTo("OCCUPIED"); long packages = physical(position);
row.setBeforePackages(packages); row.setDeltaPackages(0L); row.setAfterPackages(packages);
row.setOperatorId(operator); row.setRemark(reason.trim()); row.setOccurredAt(now); row.setCreatedAt(now);
ledgers.insert(row);
@@ -55,7 +55,7 @@ public interface PdaStocktakeItemMapper extends BaseMapper<PdaStocktakeItem> {
int counted(@Param("taskId") long taskId);
@Select("SELECT COUNT(*) FROM ll_pda_stocktake_item WHERE task_id=#{taskId} " +
"AND actual_packages IS NOT NULL AND difference_packages&lt;&gt;0")
"AND actual_packages IS NOT NULL AND difference_packages<>0")
int differences(@Param("taskId") long taskId);
@Select("SELECT id item_id,customer_id,balance_id,position_id,sku_code,product_name,inbound_code," +
@@ -0,0 +1,53 @@
package com.baiyue.lastleg.security.controller;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.event.EventEnvelope;
import com.baiyue.lastleg.security.InternalServiceTokenGuard;
import com.baiyue.lastleg.security.dto.LastlegSecurityDtos.Acknowledgement;
import com.baiyue.lastleg.security.dto.LastlegSecurityDtos.ValidationRequest;
import com.baiyue.lastleg.security.dto.LastlegSecurityDtos.ValidationResponse;
import com.baiyue.lastleg.security.service.LastlegSecurityProjectionService;
import com.baiyue.lastleg.security.service.LastlegSecurityValidationService;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
@Hidden
@RestController
@RequestMapping("/internal/lastleg/security/v1")
public class LastlegSecurityController {
private final InternalServiceTokenGuard tokenGuard;
private final LastlegSecurityProjectionService projections;
private final LastlegSecurityValidationService validations;
public LastlegSecurityController(InternalServiceTokenGuard tokenGuard,
LastlegSecurityProjectionService projections,
LastlegSecurityValidationService validations) {
this.tokenGuard = tokenGuard;
this.projections = projections;
this.validations = validations;
}
@PostMapping("/events")
public ApiResponse<Acknowledgement> receive(
@RequestHeader(value = "X-Internal-Service-Token", required = false) String token,
@RequestBody EventEnvelope envelope) {
tokenGuard.verify(token);
var result = projections.consume(envelope);
return ApiResponse.success(new Acknowledgement(envelope.eventId(), result.result(), Instant.now()));
}
@PostMapping("/validate")
public ApiResponse<ValidationResponse> validate(
@RequestHeader(value = "X-Internal-Service-Token", required = false) String token,
@Valid @RequestBody ValidationRequest request) {
tokenGuard.verify(token);
return ApiResponse.success(validations.validate(request));
}
}
@@ -0,0 +1,31 @@
package com.baiyue.lastleg.security.dto;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.time.Instant;
public final class LastlegSecurityDtos {
private LastlegSecurityDtos() { }
public record Acknowledgement(String eventId, String result, Instant receivedAt) { }
public record ValidationRequest(@NotNull @Min(1) Long userId,
@NotNull @Min(0) Long tenantId,
@NotNull @Min(0) Long permissionVersion) { }
public record ValidationResponse(boolean valid, FailureReason failureReason) {
public static ValidationResponse accepted() { return new ValidationResponse(true, null); }
public static ValidationResponse rejected(FailureReason reason) {
return new ValidationResponse(false, reason);
}
}
public enum FailureReason {
SECURITY_PROJECTION_MISSING,
SECURITY_PROJECTION_NOT_READY,
USER_DISABLED,
TENANT_DISABLED,
PERMISSION_VERSION_STALE
}
}
@@ -0,0 +1,36 @@
package com.baiyue.lastleg.security.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
/** 非授权真相的可重建 Redis 镜像;失败不影响已提交的 MySQL 投影。 */
@Component
@Slf4j
public class LastlegSecurityProjectionRedisMirror {
private final StringRedisTemplate redis;
private final ObjectMapper objectMapper;
@Value("${baiyue.security.permission-snapshot-key-prefix:baiyue:permission-snapshot}")
private String keyPrefix;
public LastlegSecurityProjectionRedisMirror(StringRedisTemplate redis, ObjectMapper objectMapper) {
this.redis = redis;
this.objectMapper = objectMapper;
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void mirror(LastlegSecurityProjectionService.ProjectionChanged event) {
var value = event.projection();
try {
redis.opsForValue().set(keyPrefix + ':' + value.aggregateType() + ':' + value.aggregateId(),
objectMapper.writeValueAsString(value));
} catch (Exception exception) {
log.warn("海外安全投影 Redis 镜像写入失败 aggregateType={}, aggregateId={}",
value.aggregateType(), value.aggregateId());
}
}
}
@@ -0,0 +1,188 @@
package com.baiyue.lastleg.security.service;
import com.baiyue.common.core.api.ResultCode;
import com.baiyue.common.core.exception.BizException;
import com.baiyue.common.event.EventEnvelope;
import com.baiyue.common.event.EventPayloadCanonicalizer;
import com.baiyue.common.event.EventPayloadHash;
import com.baiyue.common.event.EventTypes;
import com.baiyue.common.event.IamSecurityEventsV1;
import com.baiyue.common.event.RegionCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
@Service
public class LastlegSecurityProjectionService {
private static final List<String> TYPES = List.of(EventTypes.IAM_USER_STATUS_CHANGED,
EventTypes.IAM_TENANT_STATUS_CHANGED, EventTypes.IAM_PERMISSION_VERSION_CHANGED);
private final JdbcTemplate jdbc;
private final ObjectMapper objectMapper;
private final ApplicationEventPublisher events;
public LastlegSecurityProjectionService(JdbcTemplate jdbc, ObjectMapper objectMapper,
ApplicationEventPublisher events) {
this.jdbc = jdbc;
this.objectMapper = objectMapper;
this.events = events;
}
@Transactional
public ConsumeResult consume(EventEnvelope envelope) {
envelope.requireValid();
requireSecurityEnvelope(envelope);
String payloadHash = validatedStorageHash(envelope);
String payloadJson = envelope.payload().toString();
try {
jdbc.update("INSERT INTO ll_security_event_inbox(event_id,event_type,payload_hash,payload_json,status,received_at) "
+ "VALUES (?,?,?,?, 'RECEIVED', NOW(3))", envelope.eventId(), envelope.eventType(),
payloadHash, payloadJson);
} catch (DuplicateKeyException duplicate) {
InboxRow existing = jdbc.queryForObject(
"SELECT event_type,payload_hash,status FROM ll_security_event_inbox "
+ "WHERE event_id=? FOR UPDATE",
(rs, row) -> new InboxRow(rs.getString(1), rs.getString(2), rs.getString(3)),
envelope.eventId());
if (existing == null || !Objects.equals(existing.eventType(), envelope.eventType())
|| existing.payloadHash() == null
|| !existing.payloadHash().equalsIgnoreCase(payloadHash)) {
throw new BizException(ResultCode.CONFLICT, "相同 eventId 的 payloadHash 冲突");
}
if ("PROCESSED".equals(existing.status())) return new ConsumeResult("DUPLICATE", null);
}
ProjectionInput input = input(envelope, payloadHash);
ProjectionRow current = findForUpdate(input.aggregateType(), input.aggregateId());
SecurityProjectionMonotonicity.Decision decision = SecurityProjectionMonotonicity.decide(
current == null ? null : current.aggregateVersion(), current == null ? null : current.payloadHash(),
input.aggregateVersion(), input.payloadHash());
String result = decision.name();
if (decision == SecurityProjectionMonotonicity.Decision.APPLY) {
upsert(input);
result = "APPLIED";
events.publishEvent(new ProjectionChanged(input));
}
jdbc.update("UPDATE ll_security_event_inbox SET status='PROCESSED',result=?,processed_at=NOW(3) "
+ "WHERE event_id=?", result, envelope.eventId());
return new ConsumeResult(result, input);
}
private void requireSecurityEnvelope(EventEnvelope envelope) {
if (!TYPES.contains(envelope.eventType()) || envelope.eventVersion() != IamSecurityEventsV1.VERSION
|| envelope.sourceRegion() != RegionCode.CN || envelope.targetRegion() != RegionCode.OVERSEAS) {
throw new BizException(ResultCode.BAD_REQUEST, "仅接受 CN→OVERSEAS IAM V1 安全事件");
}
}
static String validatedStorageHash(EventEnvelope envelope) {
if (!EventPayloadHash.matches(EventPayloadCanonicalizer.canonicalize(envelope.payload()),
envelope.payloadHash())) {
throw new BizException(ResultCode.BAD_REQUEST, "payloadHash 与 IAM 安全事件负载不一致");
}
// 表内只保存固定 64 位摘要;信封传输契约仍保留 sha256: 前缀。
return envelope.payloadHash().substring("sha256:".length()).toLowerCase(Locale.ROOT);
}
private ProjectionInput input(EventEnvelope envelope, String payloadHash) {
try {
return switch (envelope.eventType()) {
case EventTypes.IAM_USER_STATUS_CHANGED -> {
var value = objectMapper.treeToValue(envelope.payload(),
IamSecurityEventsV1.UserStatusChanged.class);
requireIdentity(envelope, "USER", value.authUserId(), value.tenantId());
requirePayload(value.status(), value.changedAt(), value.permissionVersion(),
envelope.aggregateVersion());
requireStatus(value.status());
yield new ProjectionInput("USER", String.valueOf(value.authUserId()), value.tenantId(),
value.status(), value.permissionVersion(), envelope.aggregateVersion(),
payloadHash, envelope.eventId(), value.changedAt());
}
case EventTypes.IAM_TENANT_STATUS_CHANGED -> {
var value = objectMapper.treeToValue(envelope.payload(),
IamSecurityEventsV1.TenantStatusChanged.class);
requireIdentity(envelope, "TENANT", value.tenantId(), value.tenantId());
requirePayload(value.status(), value.changedAt(), envelope.aggregateVersion(),
envelope.aggregateVersion());
requireStatus(value.status());
yield new ProjectionInput("TENANT", String.valueOf(value.tenantId()), value.tenantId(),
value.status(), null, envelope.aggregateVersion(), payloadHash,
envelope.eventId(), value.changedAt());
}
case EventTypes.IAM_PERMISSION_VERSION_CHANGED -> {
var value = objectMapper.treeToValue(envelope.payload(),
IamSecurityEventsV1.PermissionVersionChanged.class);
requireIdentity(envelope, "AUTHORIZATION", value.authUserId(), value.tenantId());
requirePayload(value.appCode(), value.changedAt(), value.permissionVersion(),
envelope.aggregateVersion());
yield new ProjectionInput("AUTHORIZATION", String.valueOf(value.authUserId()), value.tenantId(),
null, value.permissionVersion(), envelope.aggregateVersion(), payloadHash,
envelope.eventId(), value.changedAt());
}
default -> throw new IllegalArgumentException("unsupported type");
};
} catch (BizException exception) {
throw exception;
} catch (Exception exception) {
throw new BizException(ResultCode.BAD_REQUEST, "IAM 安全事件 payload 无效");
}
}
private static void requireIdentity(EventEnvelope envelope, String aggregateType,
long aggregateId, long tenantId) {
if (!aggregateType.equals(envelope.aggregateType())
|| !String.valueOf(aggregateId).equals(envelope.aggregateId())
|| !String.valueOf(tenantId).equals(envelope.tenantId())) {
throw new BizException(ResultCode.CONFLICT, "IAM 安全事件信封与 payload 身份不一致");
}
}
private static void requirePayload(String requiredText, Instant changedAt,
long payloadVersion, long aggregateVersion) {
if (requiredText == null || requiredText.isBlank() || changedAt == null
|| payloadVersion != aggregateVersion) {
throw new BizException(ResultCode.CONFLICT, "IAM 安全事件 payload 版本或必填字段无效");
}
}
private static void requireStatus(String status) {
if (!"ACTIVE".equals(status) && !"DISABLED".equals(status)) {
throw new BizException(ResultCode.BAD_REQUEST, "IAM 安全状态仅允许 ACTIVE 或 DISABLED");
}
}
private ProjectionRow findForUpdate(String type, String id) {
List<ProjectionRow> rows = jdbc.query(
"SELECT aggregate_version,payload_hash FROM ll_security_projection "
+ "WHERE aggregate_type=? AND aggregate_id=? FOR UPDATE",
(rs, row) -> new ProjectionRow(rs.getLong(1), rs.getString(2)), type, id);
return rows.isEmpty() ? null : rows.get(0);
}
private void upsert(ProjectionInput value) {
jdbc.update("INSERT INTO ll_security_projection(aggregate_type,aggregate_id,tenant_id,security_status,"
+ "permission_version,aggregate_version,payload_hash,last_event_id,changed_at,updated_at) "
+ "VALUES (?,?,?,?,?,?,?,?,?,NOW(3)) ON DUPLICATE KEY UPDATE tenant_id=VALUES(tenant_id),"
+ "security_status=VALUES(security_status),permission_version=VALUES(permission_version),"
+ "aggregate_version=VALUES(aggregate_version),payload_hash=VALUES(payload_hash),"
+ "last_event_id=VALUES(last_event_id),changed_at=VALUES(changed_at),updated_at=NOW(3)",
value.aggregateType(), value.aggregateId(), value.tenantId(), value.status(),
value.permissionVersion(), value.aggregateVersion(), value.payloadHash(), value.eventId(),
value.changedAt());
}
private record InboxRow(String eventType, String payloadHash, String status) { }
private record ProjectionRow(long aggregateVersion, String payloadHash) { }
public record ConsumeResult(String result, ProjectionInput projection) { }
public record ProjectionChanged(ProjectionInput projection) { }
public record ProjectionInput(String aggregateType, String aggregateId, long tenantId, String status,
Long permissionVersion, long aggregateVersion, String payloadHash,
String eventId, Instant changedAt) { }
}
@@ -0,0 +1,60 @@
package com.baiyue.lastleg.security.service;
import com.baiyue.lastleg.security.dto.LastlegSecurityDtos.FailureReason;
import com.baiyue.lastleg.security.dto.LastlegSecurityDtos.ValidationRequest;
import com.baiyue.lastleg.security.dto.LastlegSecurityDtos.ValidationResponse;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class LastlegSecurityValidationService {
private final JdbcTemplate jdbc;
public LastlegSecurityValidationService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public ValidationResponse validate(ValidationRequest request) {
String userStatus = status("USER", String.valueOf(request.userId()), request.tenantId());
if (userStatus == null) {
return ValidationResponse.rejected(FailureReason.SECURITY_PROJECTION_MISSING);
}
if (!"ACTIVE".equals(userStatus)) {
return ValidationResponse.rejected(FailureReason.USER_DISABLED);
}
if (request.tenantId() > 0) {
String tenantStatus = status("TENANT", String.valueOf(request.tenantId()), request.tenantId());
if (tenantStatus == null) {
return ValidationResponse.rejected(FailureReason.SECURITY_PROJECTION_MISSING);
}
if (!"ACTIVE".equals(tenantStatus)) {
return ValidationResponse.rejected(FailureReason.TENANT_DISABLED);
}
}
List<Long> projectedVersions = jdbc.query(
"SELECT MAX(permission_version) FROM ll_security_projection "
+ "WHERE aggregate_id=? AND tenant_id=? "
+ "AND aggregate_type IN ('USER','AUTHORIZATION') HAVING COUNT(permission_version)>0",
(rs, row) -> rs.getLong(1), String.valueOf(request.userId()), request.tenantId());
if (projectedVersions.isEmpty()) {
return ValidationResponse.rejected(FailureReason.SECURITY_PROJECTION_MISSING);
}
long projectedVersion = projectedVersions.get(0);
if (request.permissionVersion() < projectedVersion) {
return ValidationResponse.rejected(FailureReason.PERMISSION_VERSION_STALE);
}
if (request.permissionVersion() > projectedVersion) {
return ValidationResponse.rejected(FailureReason.SECURITY_PROJECTION_NOT_READY);
}
return ValidationResponse.accepted();
}
private String status(String type, String id, long tenantId) {
List<String> values = jdbc.query("SELECT security_status FROM ll_security_projection "
+ "WHERE aggregate_type=? AND aggregate_id=? AND tenant_id=?",
(rs, row) -> rs.getString(1), type, id, tenantId);
return values.isEmpty() ? null : values.get(0);
}
}
@@ -0,0 +1,19 @@
package com.baiyue.lastleg.security.service;
import com.baiyue.common.core.api.ResultCode;
import com.baiyue.common.core.exception.BizException;
import java.util.Objects;
final class SecurityProjectionMonotonicity {
private SecurityProjectionMonotonicity() { }
static Decision decide(Long currentVersion, String currentHash, long incomingVersion, String incomingHash) {
if (currentVersion == null || incomingVersion > currentVersion) return Decision.APPLY;
if (incomingVersion < currentVersion) return Decision.STALE;
if (Objects.equals(currentHash, incomingHash)) return Decision.DUPLICATE_VERSION;
throw new BizException(ResultCode.CONFLICT, "相同聚合版本的安全事件 payloadHash 冲突");
}
enum Decision { APPLY, STALE, DUPLICATE_VERSION }
}
@@ -7,8 +7,6 @@ import com.baiyue.lastleg.dropship.dto.DropshipRequests;
import com.baiyue.lastleg.dropship.service.DropshipOrderService;
import com.baiyue.lastleg.inboundplan.entity.InboundPlanCarton;
import com.baiyue.lastleg.inboundplan.mapper.InboundPlanCartonMapper;
import com.baiyue.lastleg.inboundplan.service.InboundPlanService;
import com.baiyue.lastleg.inboundplan.dto.InboundPlanResponse;
import com.baiyue.lastleg.inventory.command.dto.InventoryCommandRequests;
import com.baiyue.lastleg.inventory.command.service.InventoryCommandService;
import com.baiyue.lastleg.shipping.mapper.ContainerShippingGateMapper;
@@ -37,7 +35,6 @@ public class LoadingCompletedConsumer {
@Resource private LastlegOrderDetailMapper detailMapper;
@Resource private LastlegOrderStatusHistoryMapper historyMapper;
@Resource private InboundPlanCartonMapper cartonMapper;
@Resource private InboundPlanService inboundPlans;
@Resource private ObjectMapper objectMapper;
@Resource private LastlegOrderNoGenerator orderNoGenerator;
@Resource private DropshipOrderService dropshipOrders;
@@ -228,12 +225,9 @@ public class LoadingCompletedConsumer {
history.setOrderId(order.getId()); history.setToStatus("PENDING_ASSIGNMENT"); history.setEventId(event.eventId());
history.setRemark("头程装柜完成自动生成"); history.setCreatedAt(LocalDateTime.now()); historyMapper.insert(history);
if ("FIRST_LEG".equals(orderType)) {
List<String> sourcePalletNos = source.pallets() == null ? List.of() : source.pallets().stream()
.map(FirstLegLoadingPlanCompletedV1.PalletSnapshot::palletNo).filter(Objects::nonNull).toList();
InboundPlanResponse plan = sourcePalletNos.isEmpty()
? inboundPlans.convert(customerId, order.getId())
: inboundPlans.convert(customerId, order.getId(), sourcePalletNos);
registerInTransit(event, payload, source, order, plan.planNo());
// The cross-region handover freezes the source inbound code only. An inbound plan is
// created later by an explicit platform conversion, which replaces this display snapshot.
registerInTransit(event, payload, source, order, source.inboundCode());
}
if ("ONE_CLICK_DROPSHIP".equals(orderType)) {
long warehouseId;
@@ -241,11 +235,6 @@ public class LoadingCompletedConsumer {
catch (Exception exception) { throw new IllegalArgumentException("One-click dropship warehouseId is invalid", exception); }
dropshipOrders.receive(new DropshipRequests.Receive(customerId, order.getId(), warehouseId,
event.eventId() + ":DROPSHIP", dropshipPallets));
InboundPlanResponse plan = inboundPlans.convertDropship(customerId, order.getId(), dropshipPallets.stream()
.map(pallet -> new InboundPlanService.WholePalletInput(pallet.palletNo(), pallet.skuPackages().stream()
.mapToInt(sku -> Math.toIntExact(sku.packageCount())).sum()))
.toList());
registerInTransit(event, payload, source, order, plan.planNo());
}
}