fix: refactor MarketingController constructor with

This commit is contained in:
arys
2026-01-24 00:48:07 +05:00
parent 155ed629cf
commit b51b0b003f
@@ -10,6 +10,7 @@ import kz.konturai.parser.service.MarketingAnalysisService;
import kz.konturai.parser.service.MarketingStrategyService;
import kz.konturai.parser.service.MinIOService;
import kz.konturai.parser.service.PostingTaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -30,6 +31,7 @@ import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/marketing/analysis")
@RequiredArgsConstructor
public class MarketingController {
private static final Logger logger = LoggerFactory.getLogger(MarketingController.class);
@@ -40,19 +42,6 @@ public class MarketingController {
private final JwtService jwtService;
private final PostingTaskService postingTaskService;
public MarketingController(
MarketingAnalysisService marketingAnalysisService,
MarketingStrategyService marketingStrategyService,
MinIOService minIOService,
JwtService jwtService,
PostingTaskService postingTaskService) {
this.marketingAnalysisService = marketingAnalysisService;
this.marketingStrategyService = marketingStrategyService;
this.minIOService = minIOService;
this.jwtService = jwtService;
this.postingTaskService = postingTaskService;
}
private String extractUserIdFromHeader(String authHeader) {
if (authHeader == null || authHeader.isEmpty()) {
logger.debug("Authorization header is null or empty");
@@ -366,70 +355,81 @@ public class MarketingController {
}
}
@PostMapping("/strategy/generate")
public ResponseEntity<?> generateStrategy(
@RequestHeader(value = "Authorization", required = false) String authHeader,
@RequestParam String analysisId,
@Valid @RequestBody(required = false) MarketingStrategyRequest request) {
@PostMapping("/strategy/generate")
public ResponseEntity<?> generateStrategy(
@RequestHeader(value = "Authorization", required = false) String authHeader,
@RequestParam String analysisId,
@Valid @RequestBody(required = false) MarketingStrategyRequest request) {
String userId = extractUserIdFromHeader(authHeader);
if (userId == null) {
return unauthorizedResponse();
}
// Check if user owns the analysis
Optional<MarketingAnalysis> optAnalysis = marketingAnalysisService.getAnalysisById(analysisId);
if (optAnalysis.isEmpty()) {
ErrorResponse error = new ErrorResponse("INVALID_ANALYSIS", "Анализ не найден");
return ResponseEntity.status(404)
.body(ApiResponse.error("Анализ не найден", error));
}
MarketingAnalysis analysis = optAnalysis.get();
if (!userId.equals(analysis.getUserId())) {
ErrorResponse error = new ErrorResponse(
"FORBIDDEN",
"У вас нет доступа к этому анализу");
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ApiResponse.error("Доступ запрещен", error));
}
if (request == null) {
request = new MarketingStrategyRequest();
}
try {
MarketingStrategy strategy = marketingStrategyService.generateStrategy(analysisId, request,
userId);
MarketingStrategyResponse response = new MarketingStrategyResponse();
response.setStrategyId(strategy.getId());
response.setAnalysisId(strategy.getAnalysisId());
response.setStatus(strategy.getStatus());
response.setCreatedAt(strategy.getCreatedAt());
response.setDurationWeeks(strategy.getDurationWeeks());
response.setPriorityPlatforms(strategy.getPriorityPlatforms());
return ResponseEntity.ok(ApiResponse.success(
"Генерация стратегии запущена успешно. Результаты будут готовы в течение 3-5 минут.",
response));
} catch (IllegalArgumentException e) {
ErrorResponse error = new ErrorResponse("INVALID_ANALYSIS", e.getMessage());
return ResponseEntity.status(404)
.body(ApiResponse.error("Анализ не найден", error));
} catch (IllegalStateException e) {
ErrorResponse error = new ErrorResponse("ANALYSIS_NOT_COMPLETED", e.getMessage());
return ResponseEntity.status(400)
.body(ApiResponse.error("Анализ еще не завершен", error));
} catch (Exception e) {
ErrorResponse error = new ErrorResponse(
"INTERNAL_SERVER_ERROR",
"Произошла ошибка при запуске генерации стратегии");
return ResponseEntity.status(500)
.body(ApiResponse.error("Внутренняя ошибка сервера", error));
}
String userId = extractUserIdFromHeader(authHeader);
if (userId == null) {
return unauthorizedResponse();
}
Optional<MarketingAnalysis> optAnalysis = marketingAnalysisService.getAnalysisById(analysisId);
if (optAnalysis.isEmpty()) {
Optional<MarketingAnalysisV2Document> optV2 = marketingAnalysisService.getAnalysisV2ById(analysisId);
if (optV2.isEmpty()) {
ErrorResponse error = new ErrorResponse("INVALID_ANALYSIS", "Анализ не найден");
return ResponseEntity.status(404)
.body(ApiResponse.error("Анализ не найден", error));
}
if (!userId.equals(optV2.get().getUserId())) {
ErrorResponse error = new ErrorResponse(
"FORBIDDEN",
"У вас нет доступа к этому анализу");
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ApiResponse.error("Доступ запрещен", error));
}
} else {
if (!userId.equals(optAnalysis.get().getUserId())) {
ErrorResponse error = new ErrorResponse(
"FORBIDDEN",
"У вас нет доступа к этому анализу");
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ApiResponse.error("Доступ запрещен", error));
}
}
if (request == null) {
request = new MarketingStrategyRequest();
}
try {
MarketingStrategy strategy = marketingStrategyService.generateStrategy(analysisId, request,
userId);
MarketingStrategyResponse response = new MarketingStrategyResponse();
response.setStrategyId(strategy.getId());
response.setAnalysisId(strategy.getAnalysisId());
response.setStatus(strategy.getStatus());
response.setCreatedAt(strategy.getCreatedAt());
response.setDurationWeeks(strategy.getDurationWeeks());
response.setPriorityPlatforms(strategy.getPriorityPlatforms());
return ResponseEntity.ok(ApiResponse.success(
"Генерация стратегии запущена успешно. Результаты будут готовы в течение 3-5 минут.",
response));
} catch (IllegalArgumentException e) {
ErrorResponse error = new ErrorResponse("INVALID_ANALYSIS", e.getMessage());
return ResponseEntity.status(404)
.body(ApiResponse.error("Анализ не найден", error));
} catch (IllegalStateException e) {
ErrorResponse error = new ErrorResponse("ANALYSIS_NOT_COMPLETED", e.getMessage());
return ResponseEntity.status(400)
.body(ApiResponse.error("Анализ еще не завершен", error));
} catch (Exception e) {
ErrorResponse error = new ErrorResponse(
"INTERNAL_SERVER_ERROR",
"Произошла ошибка при запуске генерации стратегии");
return ResponseEntity.status(500)
.body(ApiResponse.error("Внутренняя ошибка сервера", error));
}
}
@GetMapping("/strategy/{strategyId}")
public ResponseEntity<?> getStrategy(
@RequestHeader(value = "Authorization", required = false) String authHeader,