diff --git a/config-data-executor/src/main/java/org/micord/service/DownloadService.java b/config-data-executor/src/main/java/org/micord/service/DownloadService.java index 13a4e8a..529fe6d 100644 --- a/config-data-executor/src/main/java/org/micord/service/DownloadService.java +++ b/config-data-executor/src/main/java/org/micord/service/DownloadService.java @@ -31,7 +31,7 @@ public class DownloadService { private static final Logger logger = LoggerFactory.getLogger(DownloadService.class); - public File download(BaseDownloadRequest selectedRequest, List ids, RequestParameters parameters, Map validationResults) { + public File download(BaseDownloadRequest selectedRequest, List ids, RequestParameters parameters, Map validationResults) throws SQLException { LocalDate startDate = parameters.getStartDate(); LocalDate endDate = parameters.getEndDate(); if (selectedRequest instanceof SQLDownloadRequest) { @@ -42,43 +42,65 @@ public class DownloadService { throw new IllegalArgumentException("Unsupported request type: " + selectedRequest.getClass().getSimpleName()); } - private File processAqlDownloadRequest(AQLDownloadRequest request, List ids, LocalDate startDate, LocalDate endDate, Map validationResults) { - ArangoDatabase arangoDb = ArangoDBConnection.getConnection(request.getAqlConnectionParams()); + private File processAqlDownloadRequest(AQLDownloadRequest request, List ids, LocalDate startDate, LocalDate endDate, Map validationResults) throws SQLException { + try { + ArangoDatabase arangoDb = ArangoDBConnection.getConnection(request.getAqlConnectionParams()); - Boolean emptyIdsAllowed = validationResults.get(ValidationService.IS_EMPTY_IDS_ALLOWED); - Boolean emptyDatesAllowed = validationResults.get(ValidationService.IS_EMPTY_DATES_ALLOWED); + Boolean emptyIdsAllowed = validationResults.get(ValidationService.IS_EMPTY_IDS_ALLOWED); + Boolean emptyDatesAllowed = validationResults.get(ValidationService.IS_EMPTY_DATES_ALLOWED); + List> entities = executeSelectAqlRequest( + arangoDb, + request.getDownloadRequestEntitySelectorQuery(), + ids, + startDate, + endDate, + emptyIdsAllowed, + emptyDatesAllowed + ); - Map entities = executeSelectAqlRequest(arangoDb, request.getDownloadRequestEntitySelectorQuery(), ids, emptyIdsAllowed); + if (entities.isEmpty()) { + logger.warn("No entities found for main AQL request."); + throw new NoDownloadReportRecordsException( + "Отчет не может быть сгенерирован. Нет записей в базе для успешной генерации." + ); + } - if (entities.isEmpty()) { - logger.warn("No entities found for main AQL request."); - throw new NoDownloadReportRecordsException("Отчет не может быть сгенерирован. Нет записей в базе для успешной генерации."); + return writeResultsToCsv(entities); + + } catch (ArangoDBException e) { + logger.error("Error connecting to ArangoDB or executing AQL query: {}", e.getMessage(), e); + throw new SQLException("Ошибка работы с базой данных. Попробуйте позже.", e); + } catch (NoDownloadReportRecordsException e) { + logger.warn("No records available for report generation: {}", e.getMessage()); + throw e; + } catch (Exception e) { + logger.error("Unexpected error occurred during report generation: {}", e.getMessage(), e); + throw new RuntimeException("Произошла непредвиденная ошибка при генерации отчета.", e); } - List> results = new ArrayList<>(); - request.getAqlRequestCollections().forEach(collection -> { - String type = collection.getCollectionUrl(); - String entityType; +// request.getAqlRequestCollections().forEach(collection -> { +// String type = collection.getCollectionUrl(); +// String entityType; +// +// if (Objects.equals(type, "applications")) { +// entityType = "applicationId"; +// } else { +// entityType = type + "Id"; +// } +// +// Object entityIds = entities.get(entityType); +// +// if (entityIds instanceof String) { +// entityIds = Collections.singletonList((String) entityIds); +// } +// +// String aqlQuery = buildAqlQuery(type, ids, collection.getDateAttribute(), startDate, endDate, emptyIdsAllowed, emptyDatesAllowed); +// +// results.addAll(executeAqlQuery(arangoDb, aqlQuery, (List) entityIds, startDate, endDate, emptyIdsAllowed, emptyDatesAllowed)); +// }); - if (Objects.equals(type, "applications")) { - entityType = "applicationId"; - } else { - entityType = type + "Id"; - } - - Object entityIds = entities.get(entityType); - - if (entityIds instanceof String) { - entityIds = Collections.singletonList((String) entityIds); - } - - String aqlQuery = buildAqlQuery(type, ids, collection.getDateAttribute(), startDate, endDate, emptyIdsAllowed, emptyDatesAllowed); - - results.addAll(executeAqlQuery(arangoDb, aqlQuery, (List) entityIds, startDate, endDate, emptyIdsAllowed, emptyDatesAllowed)); - }); - - return writeResultsToCsv(results); +// return writeResultsToCsv(results); } private File processSqlDownloadRequest(SQLDownloadRequest request, List ids, LocalDate startDate, LocalDate endDate, Map validationResults) { @@ -114,35 +136,77 @@ public class DownloadService { return null; } - private Map executeSelectAqlRequest(ArangoDatabase arangoDb, + private List> executeSelectAqlRequest(ArangoDatabase arangoDb, String downloadRequestEntitySelectorQuery, - List ids, Boolean emptyIdsAllowed) { - Map entities = new HashMap<>(); + List ids, LocalDate startDate, LocalDate endDate, Boolean emptyIdsAllowed, Boolean emptyDatesAllowed) { + List> results = new ArrayList<>(); - Map bindVars = new HashMap<>(); - - if (!emptyIdsAllowed) bindVars.put("ids", ids); - - AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); - - try (ArangoCursor cursor = arangoDb.query(downloadRequestEntitySelectorQuery, Map.class, bindVars, aqlQueryOptions)) { - while (cursor.hasNext()) { - Map result = cursor.next(); - - for (Map.Entry entry : result.entrySet()) { - String key = entry.getKey(); - Object entityValue = entry.getValue(); - - entities.put(key, entityValue); + try { + Map bindVars = new HashMap<>(); + if (!emptyIdsAllowed && ids != null && !ids.isEmpty()) { + bindVars.put("ids", ids); + } + if (!emptyDatesAllowed) { + if (startDate != null) { + bindVars.put("startDate", startDate.toString()); + } + if (endDate != null) { + bindVars.put("endDate", endDate.toString()); } } - } - catch (Exception e) { - logger.error("Failed to execute AQL url", e); - } - return entities; + logger.info("Executing AQL query: {}\nWith bindVars: {}", downloadRequestEntitySelectorQuery, bindVars); + + AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); + try (ArangoCursor cursor = arangoDb.query(downloadRequestEntitySelectorQuery, Map.class, bindVars, aqlQueryOptions)) { + while (cursor.hasNext()) { + results.add(cursor.next()); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + + } catch (ArangoDBException e) { + logger.error("AQL query execution failed: {}\nError: {}", downloadRequestEntitySelectorQuery, e.getMessage(), e); + } + return results; +// Map entities = new HashMap<>(); +// +// Map bindVars = new HashMap<>(); +// if (!emptyIdsAllowed && ids != null && !ids.isEmpty()) { +// bindVars.put("ids", ids); +// } +// if (!emptyDatesAllowed) { +// if (startDate != null) { +// bindVars.put("startDate", startDate.toString()); +// } +// if (endDate != null) { +// bindVars.put("endDate", endDate.toString()); +// } +// } +// +// logger.info("Executing AQL query: {}\nWith bindVars: {}", aqlQuery, bindVars); +// +// AqlQueryOptions aqlQueryOptions = new AqlQueryOptions(); +// +// try (ArangoCursor cursor = arangoDb.query(downloadRequestEntitySelectorQuery, Map.class, bindVars, aqlQueryOptions)) { +// while (cursor.hasNext()) { +// Map result = cursor.next(); +// +// for (Map.Entry entry : result.entrySet()) { +// String key = entry.getKey(); +// Object entityValue = entry.getValue(); +// +// entities.put(key, entityValue); +// } +// } +// } +// catch (Exception e) { +// logger.error("Failed to execute AQL url", e); +// } +// +// return entities; } private String buildAqlQuery(String collectionName, List ids, String dateAttribute, LocalDate startDate, LocalDate endDate, Boolean emptyIdsAllowed, Boolean emptyDatesAllowed) {