OrderStatusMachine.java 1.1 KB

1234567891011121314151617181920212223242526272829
  1. package com.campus.trade.common;
  2. import org.springframework.stereotype.Component;
  3. import java.util.List;
  4. import java.util.Map;
  5. @Component
  6. public class OrderStatusMachine {
  7. private static final Map<String, List<String>> ALLOWED_TRANSITIONS = Map.of(
  8. "PENDING", List.of("CONFIRMED", "CANCELLED"),
  9. "CONFIRMED", List.of("DELIVERED", "CANCELLED"),
  10. "DELIVERED", List.of("COMPLETED", "CANCELLED"),
  11. "COMPLETED", List.of(),
  12. "CANCELLED", List.of()
  13. );
  14. public void validateTransition(String currentStatus, String targetStatus) {
  15. if (currentStatus == null || targetStatus == null) {
  16. throw new BusinessException(StatusCode.BAD_REQUEST, "订单状态参数不能为空");
  17. }
  18. List<String> allowed = ALLOWED_TRANSITIONS.get(currentStatus);
  19. if (allowed == null || !allowed.contains(targetStatus)) {
  20. throw new BusinessException(StatusCode.BAD_REQUEST,
  21. "订单状态不允许从 " + currentStatus + " 转移到 " + targetStatus);
  22. }
  23. }
  24. }