diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index 1771ccd..da32ff4 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -229,7 +229,8 @@ jobs: --env-var "clientSecretPsp=${{ secrets.NEWMAN_IT_PA_TOKEN_CLIENT_SECRET }}" \ --env-var "clientIdPa=${{ secrets.NEWMAN_IT__PSP_TOKEN_CLIENT_ID }}" \ --env-var "clientSecretPa=${{ secrets.NEWMAN_IT_PSP_TOKEN_CLIENT_SECRET }}" \ - --env-var "filePathBulkload=${{ secrets.MIL_PAPOS_BULKLOAD_FILE_PATH }}" + --env-var "clientIdAdm=${{ secrets.NEWMAN_IT__PAPOS_ADMIN_TOKEN_CLIENT_ID }}" \ + --env-var "clientSecretAdm=${{ secrets.NEWMAN_IT_PAPOS_ADMIN_TOKEN_CLIENT_SECRET }}" # # STABLE - Update of pom.xml with the new version. diff --git a/src/main/java/it/pagopa/swclient/mil/papos/dao/BulkLoadStatusEntity.java b/src/main/java/it/pagopa/swclient/mil/papos/dao/BulkLoadStatusEntity.java index 1b76139..38ddba0 100644 --- a/src/main/java/it/pagopa/swclient/mil/papos/dao/BulkLoadStatusEntity.java +++ b/src/main/java/it/pagopa/swclient/mil/papos/dao/BulkLoadStatusEntity.java @@ -13,6 +13,7 @@ public class BulkLoadStatusEntity extends PanacheMongoEntity { private String bulkLoadingId; + private String pspId; private int totalRecords; private int successRecords; private int failedRecords; diff --git a/src/main/java/it/pagopa/swclient/mil/papos/model/BulkLoadStatus.java b/src/main/java/it/pagopa/swclient/mil/papos/model/BulkLoadStatus.java index 8949dc7..c3ad086 100644 --- a/src/main/java/it/pagopa/swclient/mil/papos/model/BulkLoadStatus.java +++ b/src/main/java/it/pagopa/swclient/mil/papos/model/BulkLoadStatus.java @@ -12,6 +12,7 @@ @ToString public class BulkLoadStatus { private String bulkLoadingId; + private String pspId; private int totalRecords; private int successRecords; private int failedRecords; diff --git a/src/main/java/it/pagopa/swclient/mil/papos/resource/SolutionResource.java b/src/main/java/it/pagopa/swclient/mil/papos/resource/SolutionResource.java index 6d136aa..4679026 100644 --- a/src/main/java/it/pagopa/swclient/mil/papos/resource/SolutionResource.java +++ b/src/main/java/it/pagopa/swclient/mil/papos/resource/SolutionResource.java @@ -71,10 +71,13 @@ public Uni createSolution( @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ "mil_papos_admin" }) public Uni getSolutions( - @HeaderParam("RequestId") @NotNull(message = ErrorCodes.ERROR_REQUESTID_MUST_NOT_BE_NULL_MSG) @Pattern(regexp = RegexPatterns.REQUEST_ID_PATTERN) String requestId, + @HeaderParam("RequestId") @NotNull(message = ErrorCodes.ERROR_REQUESTID_MUST_NOT_BE_NULL_MSG) + @Pattern(regexp = RegexPatterns.REQUEST_ID_PATTERN) String requestId, @QueryParam("page") int pageNumber, @QueryParam("size") int pageSize) { + Log.debugf("SolutionResource -> getSolutions - Input requestId, pageNumber, pageSize: %s, %s, %s", requestId, pageNumber, pageSize); + return solutionService .getSolutionsCount() .onFailure() @@ -91,7 +94,7 @@ public Uni getSolutions( .transformToUni(numberOfSolutions -> { Log.debugf("SolutionResource -> findAll: found a total count of [%s] solutions", numberOfSolutions); - return solutionService.findSolutions(requestId, pageNumber, pageSize) + return solutionService.findSolutions(pageNumber, pageSize) .onFailure() .transform(err -> { Log.errorf(err, diff --git a/src/main/java/it/pagopa/swclient/mil/papos/resource/TerminalResource.java b/src/main/java/it/pagopa/swclient/mil/papos/resource/TerminalResource.java index d65ada2..311c4e5 100644 --- a/src/main/java/it/pagopa/swclient/mil/papos/resource/TerminalResource.java +++ b/src/main/java/it/pagopa/swclient/mil/papos/resource/TerminalResource.java @@ -26,6 +26,8 @@ import java.io.IOException; import java.io.InputStream; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; @Path("/terminals") public class TerminalResource { @@ -47,7 +49,7 @@ public TerminalResource(TerminalService terminalService, SolutionService solutio @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed({ "pos_service_provider" }) + @RolesAllowed({"pos_service_provider"}) public Uni createTerminal( @HeaderParam("RequestId") @NotNull(message = ErrorCodes.ERROR_REQUESTID_MUST_NOT_BE_NULL_MSG) @@ -60,7 +62,7 @@ public Uni createTerminal( .onItem() .transformToUni(solution -> { if (solution == null) { - Log.errorf("TerminalResource -> createTerminal: error 404 during searching solution with solutionId: %s", terminal.solutionId()); + Log.errorf("TerminalResource -> createTerminal: error 404 during searching solution with solutionId: [%s]", terminal.solutionId()); return Uni.createFrom().failure(new NotFoundException(Response .status(Response.Status.NOT_FOUND) @@ -127,11 +129,11 @@ public Uni bulkLoadTerminals( try { List terminalRequests = objectMapper.readValue(file, objectMapper.getTypeFactory().constructCollectionType(List.class, TerminalDto.class)); -// TODO: CHECK THIS for (TerminalDto terminal : terminalRequests) { -// checkToken(terminal.pspId()); -// } + List solutionIds = terminalRequests.stream() + .map(TerminalDto::solutionId) + .toList(); - return terminalService.processBulkLoad(terminalRequests) + return solutionService.findAllByPspAndSolutionId(jwt.getSubject(), solutionIds) .onFailure() .transform(err -> { Log.errorf(err, "TerminalResource -> bulkLoadTerminals: error during bulkLoad process with file: length [%d] bytes", file.length); @@ -142,16 +144,47 @@ public Uni bulkLoadTerminals( .build()); }) .onItem() - .transform(bulkLoadStatus -> { - Log.debugf("TerminalResource -> bulkLoadTerminals: bulkLoad terminals completed [%s]", bulkLoadStatus); - - return Response - .status(Response.Status.ACCEPTED) - .entity(bulkLoadStatus) - .build(); + .transformToUni(solutionEntities -> { + if (solutionEntities.isEmpty()) { + Log.errorf("TerminalResource -> bulkLoadTerminals: no solutions found for pspId %s and solutionIds %s", jwt.getSubject(), solutionIds); + + return Uni.createFrom().item(() -> + Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_NO_SOLUTIONS_FOUND, ErrorCodes.ERROR_NO_SOLUTIONS_FOUND_MSG)) + .build() + ); + } + + Set uniqueSolutions = solutionEntities.stream() + .map(solution -> solution.id.toString()) + .collect(Collectors.toSet()); + + List filteredTerminals = terminalRequests.stream() + .filter(terminal -> uniqueSolutions.contains(terminal.solutionId())) + .toList(); + + return terminalService.processBulkLoad(filteredTerminals, terminalRequests.size(), jwt.getSubject()) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> bulkLoadTerminals: error during bulkLoad process with file: length [%d] bytes", file.length); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) + .build()); + }) + .onItem() + .transform(bulkLoadStatus -> { + Log.debugf("TerminalResource -> bulkLoadTerminals: bulkLoad terminals completed [%s]", bulkLoadStatus); + + return Response + .status(Response.Status.ACCEPTED) + .entity(bulkLoadStatus) + .build(); + }); }); } catch (IOException e) { - Log.error("TerminalService -> processBulkLoad: Error processing file", e); + Log.error("TerminalService -> bulkLoadTerminals: Error processing file", e); return Uni.createFrom().failure(new InternalServerErrorException(Response .status(Response.Status.INTERNAL_SERVER_ERROR) @@ -199,6 +232,7 @@ public Uni getBulkLoadingStatusFile( .entity(new Errors(ErrorCodes.ERROR_BULKLOADSTATUS_NOT_FOUND, ErrorCodes.ERROR_BULKLOADSTATUS_NOT_FOUND_MSG)) .build())); } + checkToken(bulkLoadStatus.getPspId()); return Uni.createFrom().item(Response .status(Response.Status.OK) @@ -220,9 +254,10 @@ public Uni findByPayeeCode( @QueryParam("page") int pageNumber, @QueryParam("size") int pageSize) { + Log.debugf("TerminalResource -> findBy - Input requestId: %s, payeeCode: %s, pageNumber: %s, size: %s", requestId, payeeCode, pageNumber, pageSize); checkToken(payeeCode); - return findByAttribute(requestId, "payeeCode", payeeCode, pageNumber, pageSize); + return findByLocationOrPsp("locationCode", payeeCode, pageNumber, pageSize); } @GET @@ -238,9 +273,10 @@ public Uni findByPspId( @QueryParam("page") int pageNumber, @QueryParam("size") int pageSize) { + Log.debugf("TerminalResource -> findBy - Input requestId: %s, payeeCode: %s, pageNumber: %s, size: %s", requestId, pspId, pageNumber, pageSize); checkToken(pspId); - return findByAttribute(requestId, "pspId", pspId, pageNumber, pageSize); + return findByLocationOrPsp("pspId", pspId, pageNumber, pageSize); } @GET @@ -253,10 +289,78 @@ public Uni findByWorkstation( @NotNull(message = ErrorCodes.ERROR_REQUESTID_MUST_NOT_BE_NULL_MSG) @Pattern(regexp = RegexPatterns.REQUEST_ID_PATTERN) String requestId, @QueryParam("workstation") String workstation, + @QueryParam("payeeCode") String payeeCode, @QueryParam("page") int pageNumber, @QueryParam("size") int pageSize) { - return findByAttribute(requestId, "workstation", workstation, pageNumber, pageSize); + Log.debugf("TerminalResource -> findByWorkstation - Input requestId: %s, workstation: %s, pageNumber: %s, size: %s", requestId, workstation, pageNumber, pageSize); + checkToken(payeeCode); + + return solutionService.getSolutionsListByLocationCode(payeeCode) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> findByWorkstation: error while counting terminals for [%s]", workstation); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_COUNTING_TERMINALS, ErrorCodes.ERROR_COUNTING_TERMINALS_MSG)) + .build()); + }) + .onItem() + .transformToUni(solutionEntities -> { + if (solutionEntities.isEmpty()) { + Log.errorf("TerminalResource -> findByWorkstation: no solutions found for payeeCode %s", payeeCode); + + return Uni.createFrom().item(() -> Response + .status(Response.Status.NOT_FOUND) + .entity(new Errors(ErrorCodes.ERROR_NO_SOLUTIONS_FOUND, ErrorCodes.ERROR_NO_SOLUTIONS_FOUND_PAYEE_MSG)) + .build() + ); + } + Log.debugf("TerminalResource -> findByWorkstation: found a total count of [%s] solutions associated to payeeCode [%s]", solutionEntities.size(), payeeCode); + + List solutionIds = solutionEntities.stream() + .map(solution -> solution.id.toString()) + .toList(); + + return terminalService.getTerminalCountByWorkstation(workstation, solutionIds) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> findByWorkstation: error while counting terminals for [%s]", workstation); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_COUNTING_TERMINALS, ErrorCodes.ERROR_COUNTING_TERMINALS_MSG)) + .build()); + }) + .onItem() + .transformToUni(numberOfTerminals -> { + Log.debugf("TerminalResource -> findByWorkstation: found a total count of [%s] terminals", numberOfTerminals); + + return terminalService.getTerminalListPagedByWorkstation(workstation, pageNumber, pageSize, solutionIds) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> findByWorkstation: Error while retrieving list of terminals for workstation [%s], index and size [%s, %s]", workstation, pageNumber, pageSize); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_LIST_TERMINALS, ErrorCodes.ERROR_LIST_TERMINALS_MSG)) + .build()); + }) + .onItem() + .transform(terminalsPaged -> { + Log.debugf("TerminalResource -> findByWorkstation: size of list of terminals paginated found: [%s]", terminalsPaged.size()); + + int totalPages = (int) Math.ceil((double) numberOfTerminals / pageSize); + PageMetadata pageMetadata = new PageMetadata(pageSize, numberOfTerminals, totalPages); + + return Response + .status(Response.Status.OK) + .entity(new TerminalPageResponse(terminalsPaged, pageMetadata)) + .build(); + }); + }); + }); } @PATCH @@ -276,9 +380,7 @@ public Uni updateWorkstations( return terminalService.findTerminal(terminalUuid) .onFailure() .transform(err -> { - Log.errorf(err, - "TerminalResource -> updateWorkstations: error during search terminal with terminalUuid: [%s]", - terminalUuid); + Log.errorf(err, "TerminalResource -> updateWorkstations: error during search terminal with terminalUuid: [%s]", terminalUuid); return new InternalServerErrorException(Response .status(Response.Status.INTERNAL_SERVER_ERROR) @@ -288,9 +390,7 @@ public Uni updateWorkstations( .onItem() .transformToUni(terminalEntity -> { if (terminalEntity == null) { - Log.errorf( - "TerminalResource -> updateWorkstations: error 404 during searching terminal with terminalUuid: [%s]", - terminalUuid); + Log.errorf("TerminalResource -> updateWorkstations: error 404 during searching terminal with terminalUuid: [%s]", terminalUuid); return Uni.createFrom().failure(new NotFoundException(Response .status(Response.Status.NOT_FOUND) @@ -298,11 +398,10 @@ public Uni updateWorkstations( .build())); } - return terminalService.updateWorkstations(workstations, terminalEntity) + return solutionService.findById(terminalEntity.getSolutionId()) .onFailure() .transform(err -> { - Log.errorf(err, "TerminalResource -> updateWorkstations: error during update workstations of terminalUuid: [%s]", - terminalUuid); + Log.errorf(err, "TerminalResource -> updateWorkstations: error during find solution with id: [%s]", terminalEntity.getSolutionId()); return new InternalServerErrorException(Response .status(Response.Status.INTERNAL_SERVER_ERROR) @@ -310,13 +409,28 @@ public Uni updateWorkstations( .build()); }) .onItem() - .transform(terminalUpdated -> { - Log.debugf("TerminalResource -> updateWorkstations: workstations updated correctly on DB [%s]", - terminalUpdated); - - return Response - .status(Response.Status.NO_CONTENT) - .build(); + .transformToUni(solutionFound -> { + Log.debugf("TerminalResource -> updateWorkstations: solution found correctly on DB [%s]", solutionFound); + checkToken(solutionFound.getPspId()); + + return terminalService.updateWorkstations(workstations, terminalEntity) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> updateWorkstations: error during update workstations of terminalUuid: [%s]", terminalUuid); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) + .build()); + }) + .onItem() + .transform(terminalUpdated -> { + Log.debugf("TerminalResource -> updateWorkstations: workstations updated correctly on DB [%s]", terminalUpdated); + + return Response + .status(Response.Status.NO_CONTENT) + .build(); + }); }); }); } @@ -335,38 +449,23 @@ public Uni updateTerminal( Log.debugf("TerminalResource -> updateTerminal - Input requestId, updateTerminal: %s, %s", requestId, terminal); -// TODO: CHECHK THIS checkToken(terminal.pspId()); - - return terminalService.findTerminal(terminalUuid) - .onFailure() - .transform(err -> { - Log.errorf(err, - "TerminalResource -> updateTerminal: error during search terminal with terminalUuid: [%s]", - terminalUuid); - - return new InternalServerErrorException(Response - .status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) - .build()); - }) + return solutionService.findById(terminal.solutionId()) .onItem() - .transformToUni(terminalEntity -> { - if (terminalEntity == null) { - Log.errorf( - "TerminalResource -> updateTerminal: error 404 during searching terminal with terminalUuid: [%s]", - terminalUuid); + .transformToUni(solution -> { + if (solution == null) { + Log.errorf("TerminalResource -> createTerminal: error 404 during searching solution with solutionId: %s", terminal.solutionId()); return Uni.createFrom().failure(new NotFoundException(Response .status(Response.Status.NOT_FOUND) - .entity(new Errors(ErrorCodes.ERROR_TERMINAL_NOT_FOUND, ErrorCodes.ERROR_TERMINAL_NOT_FOUND_MSG)) + .entity(new Errors(ErrorCodes.ERROR_SOLUTION_NOT_FOUND, ErrorCodes.ERROR_SOLUTION_NOT_FOUND_MSG)) .build())); } - return terminalService.updateTerminal(terminalUuid, terminal, terminalEntity) + checkToken(solution.getPspId()); + return terminalService.findTerminal(terminalUuid) .onFailure() .transform(err -> { - Log.errorf(err, "TerminalResource -> updateTerminal: error during update terminal [%s]", - terminal); + Log.errorf(err, "TerminalResource -> updateTerminal: error during search terminal with terminalUuid: [%s]", terminalUuid); return new InternalServerErrorException(Response .status(Response.Status.INTERNAL_SERVER_ERROR) @@ -374,13 +473,34 @@ public Uni updateTerminal( .build()); }) .onItem() - .transform(terminalUpdated -> { - Log.debugf("TerminalResource -> updateTerminal: terminal updated correctly on DB [%s]", - terminalUpdated); - - return Response - .status(Response.Status.NO_CONTENT) - .build(); + .transformToUni(terminalEntity -> { + if (terminalEntity == null) { + Log.errorf("TerminalResource -> updateTerminal: error 404 during searching terminal with terminalUuid: [%s]", terminalUuid); + + return Uni.createFrom().failure(new NotFoundException(Response + .status(Response.Status.NOT_FOUND) + .entity(new Errors(ErrorCodes.ERROR_TERMINAL_NOT_FOUND, ErrorCodes.ERROR_TERMINAL_NOT_FOUND_MSG)) + .build())); + } + + return terminalService.updateTerminal(terminalUuid, terminal, terminalEntity) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> updateTerminal: error during update terminal [%s]", terminal); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) + .build()); + }) + .onItem() + .transform(terminalUpdated -> { + Log.debugf("TerminalResource -> updateTerminal: terminal updated correctly on DB [%s]", terminalUpdated); + + return Response + .status(Response.Status.NO_CONTENT) + .build(); + }); }); }); } @@ -402,9 +522,7 @@ public Uni deleteTerminal( return terminalService.findTerminal(terminalUuid) .onFailure() .transform(err -> { - Log.errorf(err, - "TerminalResource -> deleteTerminal: error during search terminal with terminalUuid: [%s]", - terminalUuid); + Log.errorf(err, "TerminalResource -> deleteTerminal: error during search terminal with terminalUuid: [%s]", terminalUuid); return new InternalServerErrorException(Response .status(Response.Status.INTERNAL_SERVER_ERROR) @@ -414,9 +532,7 @@ public Uni deleteTerminal( .onItem() .transformToUni(terminalEntity -> { if (terminalEntity == null) { - Log.errorf( - "TerminalResource -> deleteTerminal: error 404 during searching terminal with terminalUuid: [%s, %s]", - terminalUuid); + Log.errorf("TerminalResource -> deleteTerminal: error 404 during searching terminal with terminalUuid: [%s]", terminalUuid); return Uni.createFrom().failure(new NotFoundException(Response .status(Response.Status.NOT_FOUND) @@ -424,69 +540,102 @@ public Uni deleteTerminal( .build())); } - return terminalService.deleteTerminal(terminalEntity) - .onFailure() - .transform(err -> { - Log.errorf(err, - "TerminalResource -> deleteTerminal: error during deleting terminal [%s]", - terminalEntity); - - return new InternalServerErrorException(Response - .status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) - .build()); - }) + return solutionService.findById(terminalEntity.getSolutionId()) .onItem() - .transform(terminalUpdated -> { - Log.debugf("TerminalResource -> deleteTerminal: terminal deleted correctly on DB [%s]", - terminalUpdated); - - return Response - .status(Response.Status.NO_CONTENT) - .build(); + .transformToUni(solution -> { + if (solution == null) { + Log.errorf("TerminalResource -> createTerminal: error 404 during searching solution with solutionId: %s", terminalEntity.getSolutionId()); + + return Uni.createFrom().failure(new NotFoundException(Response + .status(Response.Status.NOT_FOUND) + .entity(new Errors(ErrorCodes.ERROR_SOLUTION_NOT_FOUND, ErrorCodes.ERROR_SOLUTION_NOT_FOUND_MSG)) + .build())); + } + + checkToken(solution.getPspId()); + return terminalService.deleteTerminal(terminalEntity) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> deleteTerminal: error during deleting terminal [%s]", terminalEntity); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) + .build()); + }) + .onItem() + .transform(terminalUpdated -> { + Log.debugf("TerminalResource -> deleteTerminal: terminal deleted correctly on DB [%s]", + terminalUpdated); + + return Response + .status(Response.Status.NO_CONTENT) + .build(); + }); }); }); } - private Uni findByAttribute(String requestId, String attributeName, String attributeValue, int pageNumber, int pageSize) { - Log.debugf("TerminalResource -> findBy - Input requestId: %s, attributeName: %s, attributeValue: %s, pageNumber: %s, size: %s", requestId, attributeName, attributeValue, pageNumber, pageSize); - - return terminalService.getTerminalCountByAttribute(attributeName, attributeValue) + private Uni findByLocationOrPsp(String attributeName, String attributeValue, int pageNumber, int pageSize) { + return solutionService.findAllByLocationOrPsp(attributeName, attributeValue) .onFailure() .transform(err -> { - Log.errorf(err, "TerminalResource -> findBy: error while counting terminals for [%s, %s]", attributeName, attributeValue); + Log.errorf(err, "TerminalResource -> findByLocationOrPsp: error during search solutions with" + attributeName + ": %s", attributeValue); return new InternalServerErrorException(Response .status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Errors(ErrorCodes.ERROR_COUNTING_TERMINALS, ErrorCodes.ERROR_COUNTING_TERMINALS_MSG)) + .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) .build()); }) .onItem() - .transformToUni(numberOfTerminals -> { - Log.debugf("TerminalResource -> findBy: found a total count of [%s] terminals", numberOfTerminals); + .transformToUni(solutions -> { + if (solutions.isEmpty()) { + Log.errorf("TerminalResource -> findByLocationOrPsp: error 404 during searching solutions with locationCode" + attributeName + ": [%s]", attributeValue); + + return Uni.createFrom().failure(new NotFoundException(Response + .status(Response.Status.NOT_FOUND) + .entity(new Errors(ErrorCodes.ERROR_SOLUTION_NOT_FOUND, ErrorCodes.ERROR_SOLUTION_NOT_FOUND_MSG)) + .build())); + } - return terminalService.getTerminalListPagedByAttribute(attributeName, attributeValue, pageNumber, pageSize) + List solutionIds = solutions.stream() + .map(solution -> solution.id.toString()) + .toList(); + + return terminalService.countBySolutionIds(solutionIds) .onFailure() .transform(err -> { - Log.errorf(err, "TerminalResource -> findBy: Error while retrieving list of terminals for [%s, %s], index and size [%s, %s]", attributeName, attributeValue, pageNumber, pageSize); + Log.errorf(err, "TerminalResource -> findByLocationOrPsp: error during search solutions with locationCode" + attributeName + ": [%s]", attributeValue); return new InternalServerErrorException(Response .status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Errors(ErrorCodes.ERROR_LIST_TERMINALS, ErrorCodes.ERROR_LIST_TERMINALS_MSG)) + .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) .build()); }) .onItem() - .transform(terminalsPaged -> { - Log.debugf("TerminalResource -> findBy: size of list of terminals paginated found: [%s]", terminalsPaged.size()); - - int totalPages = (int) Math.ceil((double) numberOfTerminals / pageSize); - PageMetadata pageMetadata = new PageMetadata(pageSize, numberOfTerminals, totalPages); - - return Response - .status(Response.Status.OK) - .entity(new TerminalPageResponse(terminalsPaged, pageMetadata)) - .build(); - }); + .transformToUni(numberOfTerminals -> + terminalService.findBySolutionIds(solutionIds, pageNumber, pageSize) + .onFailure() + .transform(err -> { + Log.errorf(err, "TerminalResource -> findByLocationOrPsp: error during finding terminal with solutionIds [%s]", solutionIds); + + return new InternalServerErrorException(Response + .status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new Errors(ErrorCodes.ERROR_GENERIC_FROM_DB, ErrorCodes.ERROR_GENERIC_FROM_DB_MSG)) + .build()); + }) + .onItem() + .transform(terminalsPaged -> { + Log.debugf("TerminalResource -> findByLocationOrPsp: size of list of terminals paginated found: [%s]", terminalsPaged.size()); + + int totalPages = (int) Math.ceil((double) numberOfTerminals / pageSize); + PageMetadata pageMetadata = new PageMetadata(pageSize, numberOfTerminals, totalPages); + + return Response + .status(Response.Status.OK) + .entity(new TerminalPageResponse(terminalsPaged, pageMetadata)) + .build(); + })); }); } diff --git a/src/main/java/it/pagopa/swclient/mil/papos/service/SolutionService.java b/src/main/java/it/pagopa/swclient/mil/papos/service/SolutionService.java index 1f3f223..5602f76 100644 --- a/src/main/java/it/pagopa/swclient/mil/papos/service/SolutionService.java +++ b/src/main/java/it/pagopa/swclient/mil/papos/service/SolutionService.java @@ -38,16 +38,20 @@ public Uni createSolution(SolutionDto solutionDto) { .onItem() .transform(solutionSaved -> solutionSaved); } - - /** + + /** * Find all the solutions. * - * @param requestId + * @param pageNumber 0-based page index + * @param pageSize page size * @return Solutions found */ - public Uni> findSolutions(String requestId, int pageNumber, int pageSize) { - Log.debugf("SolutionService -> findSolutions - Input requestId: %s, pageNumber: %s, size: %s", requestId, pageNumber, pageSize); - return solutionRepository.findAll().page(pageNumber,pageSize).list(); + public Uni> findSolutions(int pageNumber, int pageSize) { + Log.debugf("SolutionService -> findSolutions - Input pageNumber: %s, size: %s", pageNumber, pageSize); + + return solutionRepository.findAll() + .page(pageNumber, pageSize) + .list(); } /** @@ -62,8 +66,6 @@ public Uni findById(String solutionId) { return solutionRepository.findById(new ObjectId(solutionId)); } - - /** * Delete solution starting from a solutionEntity. * @@ -80,7 +82,6 @@ public Uni deleteSolution(SolutionEntity solution) { .transform(solutionDeleted -> solutionDeleted); } - /** * Returns a number corresponding to the total number of solutions found. * @@ -88,11 +89,10 @@ public Uni deleteSolution(SolutionEntity solution) { */ public Uni getSolutionsCount() { Log.debugf("SolutionService -> getSolutionsCount"); - + return solutionRepository.count(); } - /** * Returns a number corresponding to the total number of solutions found. * @@ -106,7 +106,7 @@ public Uni getSolutionCountByAttribute(String attributeName, String attrib return solutionRepository.count(attributeName, attributeValue); } - /** + /** * Returns a list of solutions paginated. The query filters on attributeName. * * @param attributeName string representing the name of attribute to be filtered @@ -124,4 +124,46 @@ public Uni> getSolutionsListPagedByAttribute(String attribu .list(); } + /** + * Returns a list of solutions. The query filters on locationCode. + * + * @param locationCode of the solution to be filtered + * @return a list of solutions + */ + public Uni> getSolutionsListByLocationCode(String locationCode) { + Log.debugf("SolutionService -> getSolutionsListByLocationCode - Input parameters: %s", locationCode); + + return solutionRepository + .find("locationCode = ?1", locationCode) + .list(); + } + + /** + * Find all solution equals to attributeValue given in input. + * + * @param attributeName string representing the name of attribute to be filtered + * @param attributeValue value of attribute + * @return list of Solution found + */ + public Uni> findAllByLocationOrPsp(String attributeName, String attributeValue) { + Log.debugf("SolutionService -> findAllByLocationOrPsp - Input parameters: [%s, %s]", attributeName, attributeValue); + + return solutionRepository.list(String.format("%s = ?1", attributeName), attributeValue); + } + + /** + * Find all solution equals to pspId and solutionId given in input. + * + * @param pspId ID of the POS service provider + * @param solutionIds id of the solution + * @return list of Solution found + */ + public Uni> findAllByPspAndSolutionId(String pspId, List solutionIds) { + Log.debugf("SolutionService -> findAllByPspAndSolutionId - Input parameters: [%s, %s]", pspId, solutionIds); + List solutionObjectIds = solutionIds.stream() + .map(ObjectId::new) + .toList(); + + return solutionRepository.list("pspId = ?1 and _id in ?2", pspId, solutionObjectIds); + } } diff --git a/src/main/java/it/pagopa/swclient/mil/papos/service/TerminalService.java b/src/main/java/it/pagopa/swclient/mil/papos/service/TerminalService.java index 3fd107d..2fb9c37 100644 --- a/src/main/java/it/pagopa/swclient/mil/papos/service/TerminalService.java +++ b/src/main/java/it/pagopa/swclient/mil/papos/service/TerminalService.java @@ -52,13 +52,13 @@ public Uni createTerminal(TerminalDto terminalDto) { * @param terminalRequests file json containing a set of terminals * @return list of terminal created */ - public Uni processBulkLoad(List terminalRequests) { + public Uni processBulkLoad(List terminalRequests, int totalRecords, String pspId) { Log.debugf("TerminalService -> processBulkLoad - Input parameters: file content length: %d bytes", terminalRequests.size()); String bulkLoadingId = Utility.generateRandomUuid(); - BulkLoadStatus bulkLoadStatus = new BulkLoadStatus(bulkLoadingId, 0); - - bulkLoadStatus.setTotalRecords(terminalRequests.size()); + BulkLoadStatus bulkLoadStatus = new BulkLoadStatus(bulkLoadingId, totalRecords); + bulkLoadStatus.setFailedRecords(totalRecords - terminalRequests.size()); + bulkLoadStatus.setPspId(pspId); List> terminalCreationUnis = new ArrayList<>(); for (TerminalDto terminal : terminalRequests) { @@ -112,39 +112,28 @@ public Uni findBulkLoadStatus(String bulkLoadingId) { /** * Returns a number corresponding to the total number of terminal found. * - * @param attributeName name of the attribute - * @param attributeValue value of the attribute + * @param workstation name of workstation * @return a number */ - public Uni getTerminalCountByAttribute(String attributeName, String attributeValue) { - Log.debugf("TerminalService -> getTerminalCountByAttribute - Input parameters: %s, %s", attributeName, attributeValue); + public Uni getTerminalCountByWorkstation(String workstation, List solutionIds) { + Log.debugf("TerminalService -> getTerminalCountByWorkstation - Input parameter: %s", workstation); - if (attributeName.equals("workstation")) { - return terminalRepository.count("{ 'workstations': ?1 }", attributeValue); - } - return terminalRepository.count(attributeName, attributeValue); + return terminalRepository.count("workstations = ?1 and solutionId in ?2", workstation, solutionIds); } /** * Returns a list of terminals paginated. The query filters on attributeName. * - * @param attributeName string representing the name of attribute to be filtered - * @param attributeValue value of attribute - * @param pageIndex 0-based page index - * @param pageSize page size + * @param workstation name of workstation + * @param pageIndex 0-based page index + * @param pageSize page size * @return a list of terminals */ - public Uni> getTerminalListPagedByAttribute(String attributeName, String attributeValue, int pageIndex, int pageSize) { - Log.debugf("TerminalService -> getTerminalListPagedByAttribute - Input parameters: %s, %s, %s, %s", attributeName, attributeValue, pageIndex, pageSize); - - if (attributeName.equals("workstation")) { - return terminalRepository - .find("{ 'workstations': ?1 }", attributeValue) - .page(pageIndex, pageSize) - .list(); - } + public Uni> getTerminalListPagedByWorkstation(String workstation, int pageIndex, int pageSize, List solutionIds) { + Log.debugf("TerminalService -> getTerminalListPagedByWorkstation - Input parameters: %s, %s, %s, %s", workstation, pageIndex, pageSize, solutionIds); + return terminalRepository - .find(String.format("%s = ?1", attributeName), attributeValue) + .find("workstations = ?1 and solutionId in ?2", workstation, solutionIds) .page(pageIndex, pageSize) .list(); } @@ -219,6 +208,28 @@ public Uni deleteTerminal(TerminalEntity terminal) { .transform(terminalDeleted -> terminalDeleted); } + /** + * Returns a number corresponding to the total number of terminal found. + * + * @param solutionIds list of Solution + * @return a number + */ + public Uni countBySolutionIds(List solutionIds) { + return terminalRepository.count("solutionId in (?1)", solutionIds); + } + + /** + * Find all terminal equals to solutionIds given in input. + * + * @param solutionIds list of Solution + * @return Solutions found + */ + public Uni> findBySolutionIds(List solutionIds, int pageIndex, int pageSize) { + return terminalRepository.find("solutionId in ?1", solutionIds) + .page(pageIndex, pageSize) + .list(); + } + private TerminalEntity createTerminalEntity(TerminalDto terminalDto, String terminalUuid) { Log.debugf("TerminalService -> createTerminalEntity: storing terminal [%s] on DB", terminalDto); diff --git a/src/main/java/it/pagopa/swclient/mil/papos/util/ErrorCodes.java b/src/main/java/it/pagopa/swclient/mil/papos/util/ErrorCodes.java index 80a7a09..45e0e7d 100644 --- a/src/main/java/it/pagopa/swclient/mil/papos/util/ErrorCodes.java +++ b/src/main/java/it/pagopa/swclient/mil/papos/util/ErrorCodes.java @@ -31,7 +31,6 @@ private ErrorCodes() { public static final String ERROR_AMOUNT_MUST_NOT_BE_NULL = MODULE_ID + "000017"; public static final String ERROR_STATUS_MUST_NOT_BE_NULL = MODULE_ID + "000018"; public static final String ERROR_SOLUTIONID_MUST_NOT_BE_NULL = MODULE_ID + "000019"; - /* * Service errors code from 000200 to 000500 @@ -50,7 +49,7 @@ private ErrorCodes() { public static final String ERROR_SOLUTION_NOT_FOUND = MODULE_ID + "000211"; public static final String ERROR_LIST_SOLUTIONS = MODULE_ID + "000212"; public static final String ERROR_COUNTING_SOLUTIONS = MODULE_ID + "000213"; - + public static final String ERROR_NO_SOLUTIONS_FOUND = MODULE_ID + "000214"; /* * Error descriptions @@ -89,8 +88,8 @@ private ErrorCodes() { private static final String ERROR_SOLUTION_NOT_FOUND_DESCR = "solution not found on db"; private static final String ERROR_LIST_SOLUTIONS_DESCR = "error occurred while retrieving list of paginated solutions"; private static final String ERROR_COUNTING_SOLUTIONS_DESCR = "error occurred while counting solutions"; - - + private static final String ERROR_NO_SOLUTIONS_FOUND_DESCR = "no solutions found with given pspId and solutionIds"; + private static final String ERROR_NO_SOLUTIONS_FOUND_PAYEE_DESCR = "no solutions found with given payeeCode"; /* * Error complete message @@ -129,6 +128,7 @@ private ErrorCodes() { public static final String ERROR_SOLUTION_NOT_FOUND_MSG = "[" + ERROR_SOLUTION_NOT_FOUND + "] " + ERROR_SOLUTION_NOT_FOUND_DESCR; public static final String ERROR_LIST_SOLUTIONS_MSG = "[" + ERROR_LIST_SOLUTIONS + "] " + ERROR_LIST_SOLUTIONS_DESCR; public static final String ERROR_COUNTING_SOLUTIONS_MSG = "[" + ERROR_COUNTING_SOLUTIONS + "] " + ERROR_COUNTING_SOLUTIONS_DESCR; - + public static final String ERROR_NO_SOLUTIONS_FOUND_MSG = "[" + ERROR_NO_SOLUTIONS_FOUND + "] " + ERROR_NO_SOLUTIONS_FOUND_DESCR; + public static final String ERROR_NO_SOLUTIONS_FOUND_PAYEE_MSG = "[" + ERROR_NO_SOLUTIONS_FOUND + "] " + ERROR_NO_SOLUTIONS_FOUND_PAYEE_DESCR; } diff --git a/src/test/java/it/pagopa/swclient/mil/papos/resource/SolutionResourceTest.java b/src/test/java/it/pagopa/swclient/mil/papos/resource/SolutionResourceTest.java index 04d15be..33093cd 100644 --- a/src/test/java/it/pagopa/swclient/mil/papos/resource/SolutionResourceTest.java +++ b/src/test/java/it/pagopa/swclient/mil/papos/resource/SolutionResourceTest.java @@ -148,7 +148,7 @@ void testFindAll_200() { Mockito.when(solutionService.getSolutionsCount()) .thenReturn(Uni.createFrom().item(10L)); - Mockito.when(solutionService.findSolutions(anyString(), anyInt(), anyInt())) + Mockito.when(solutionService.findSolutions(anyInt(), anyInt())) .thenReturn(Uni.createFrom().item(new ArrayList<>())); Response response = given() @@ -189,7 +189,7 @@ void testFindSolutionsEndpoint_500TLP() { Mockito.when(solutionService.getSolutionsCount()) .thenReturn(Uni.createFrom().item(10L)); - Mockito.when(solutionService.findSolutions(anyString(), anyInt(), anyInt())) + Mockito.when(solutionService.findSolutions(anyInt(), anyInt())) .thenReturn(Uni.createFrom().failure(new WebApplicationException())); Response response = given() diff --git a/src/test/java/it/pagopa/swclient/mil/papos/resource/TerminalResourceTest.java b/src/test/java/it/pagopa/swclient/mil/papos/resource/TerminalResourceTest.java index 4e0b667..f7e0e5c 100644 --- a/src/test/java/it/pagopa/swclient/mil/papos/resource/TerminalResourceTest.java +++ b/src/test/java/it/pagopa/swclient/mil/papos/resource/TerminalResourceTest.java @@ -18,6 +18,7 @@ import it.pagopa.swclient.mil.papos.service.SolutionService; import it.pagopa.swclient.mil.papos.service.TerminalService; import it.pagopa.swclient.mil.papos.util.TestData; +import jakarta.ws.rs.InternalServerErrorException; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import org.junit.jupiter.api.Assertions; @@ -29,12 +30,13 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static io.restassured.RestAssured.given; -import static it.pagopa.swclient.mil.papos.util.TestData.mockedListTerminalDto; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; +import static it.pagopa.swclient.mil.papos.util.TestData.*; +import static org.mockito.ArgumentMatchers.*; @QuarkusTest @TestHTTPEndpoint(TerminalResource.class) @@ -171,13 +173,16 @@ void testCreateTerminalEndpoint_404() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testBulkLoadTerminals_Success() { - String fileContent = "[{\"pspId\": \"AGID_01\", \"terminalId\": \"term1\"}, {\"pspId\": \"AGID_01\", \"terminalId\": \"term2\"}]"; + String fileContent = "[{ \"solutionId\": \"66a79a4624356b00da07cfbf\", \"terminalId\": \"34523860\", \"enabled\": true }, { \"solutionId\": \"66a79a4624346b20da01cfbf\", \"terminalId\": \"84523987\", \"enabled\": false }]"; InputStream fileInputStream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); - Mockito.when(terminalService.processBulkLoad(mockedListTerminalDto())) + Mockito.when(solutionService.findAllByPspAndSolutionId("TMIL0101", Arrays.asList("66a79a4624356b00da07cfbf", "66a79a4624346b20da01cfbf"))) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + Mockito.when(terminalService.processBulkLoad(anyList(), eq(2), anyString())) .thenReturn(Uni.createFrom().item(new BulkLoadStatusEntity())); Response response = given() @@ -227,6 +232,53 @@ void testBulkLoadTerminals_FileEmpty() { Assertions.assertEquals(400, response.statusCode()); } + @Test + @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "TMIL0101") + }) + void testBulkLoadTerminals_500() { + String fileContent = "[{ \"solutionId\": \"66a79a4624356b00da07cfbf\", \"terminalId\": \"34523860\", \"enabled\": true }, { \"solutionId\": \"66a79a4624346b20da01cfbf\", \"terminalId\": \"84523987\", \"enabled\": false }]"; + InputStream fileInputStream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); + + Mockito.when(solutionService.findAllByPspAndSolutionId("TMIL0101", Arrays.asList("66a79a4624356b00da07cfbf", "66a79a4624346b20da01cfbf"))) + .thenReturn(Uni.createFrom().failure(new WebApplicationException())); + + Response response = given() + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .multiPart("file", "file.json", fileInputStream, MediaType.APPLICATION_OCTET_STREAM) + .when() + .post("/bulkload") + .then() + .extract().response(); + + Assertions.assertEquals(500, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "TMIL0101") + }) + void testBulkLoadTerminals_500ES() { + String fileContent = "[{ \"solutionId\": \"66a79a4624356b00da07cfbf\", \"terminalId\": \"34523860\", \"enabled\": true }, { \"solutionId\": \"66a79a4624346b20da01cfbf\", \"terminalId\": \"84523987\", \"enabled\": false }]"; + InputStream fileInputStream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); + + List empty = new ArrayList<>(); + Mockito.when(solutionService.findAllByPspAndSolutionId("TMIL0101", Arrays.asList("66a79a4624356b00da07cfbf", "66a79a4624346b20da01cfbf"))) + .thenReturn(Uni.createFrom().item(empty)); + + Response response = given() + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .multiPart("file", "file.json", fileInputStream, MediaType.APPLICATION_OCTET_STREAM) + .when() + .post("/bulkload") + .then() + .extract().response(); + + Assertions.assertEquals(500, response.statusCode()); + } + @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { @@ -236,7 +288,7 @@ void testBulkLoadTerminals_ServiceError() { byte[] fileContent = "malformed content".getBytes(); InputStream fileInputStream = new ByteArrayInputStream(fileContent); - Mockito.when(terminalService.processBulkLoad(mockedListTerminalDto())) + Mockito.when(terminalService.processBulkLoad(mockedListTerminalDto(), 2, "AGID_01")) .thenReturn(Uni.createFrom().failure(new RuntimeException("Service error"))); Response response = given() @@ -253,14 +305,30 @@ void testBulkLoadTerminals_ServiceError() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testBulkLoadTerminals_InternalServerErrorException() { - String fileContent = "[{\"pspId\": \"AGID_01\", \"terminalId\": \"term1\"}, {\"pspId\": \"AGID_01\", \"terminalId\": \"term2\"}]"; + String fileContent = "[{ \"solutionId\": \"66a79a4624356b00da07cfbf\", \"terminalId\": \"34523860\", \"enabled\": true }, { \"solutionId\": \"66a79a4624346b20da01cfbf\", \"terminalId\": \"84523987\", \"enabled\": false }]"; InputStream fileInputStream = new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8)); - Mockito.when(terminalService.processBulkLoad(anyList())) - .thenReturn(Uni.createFrom().failure(new WebApplicationException())); + List mockedSolutions = mockedListSolution(); + + Mockito.when(solutionService.findAllByPspAndSolutionId("TMIL0101", Arrays.asList("66a79a4624356b00da07cfbf", "66a79a4624346b20da01cfbf"))) + .thenReturn(Uni.createFrom().item(mockedSolutions)); + + Set uniqueSolutions = mockedSolutions.stream() + .map(solution -> solution.id.toString()) + .collect(Collectors.toSet()); + + List filteredTerminals = Stream.of( + new TerminalDto("66a79a4624356b00da07cfbf", "34523860", true, null), + new TerminalDto("66a79a4624346b20da01cfbf", "84523987", false, null) + ) + .filter(terminal -> uniqueSolutions.contains(terminal.solutionId())) + .toList(); + + Mockito.when(terminalService.processBulkLoad(filteredTerminals, filteredTerminals.size(), "TMIL0101")) + .thenReturn(Uni.createFrom().failure(new InternalServerErrorException())); Response response = given() .contentType(ContentType.MULTIPART) @@ -342,11 +410,14 @@ void testGetBulkLoadingStatusFile_404() { @Claim(key = "sub", value = "payeeCode") }) void testFindByPayeeCode_200() { - Mockito.when(terminalService.getTerminalCountByAttribute("payeeCode", "payeeCode")) + Mockito.when(solutionService.findAllByLocationOrPsp(any(String.class), any(String.class))) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + Mockito.when(terminalService.countBySolutionIds(Collections.singletonList("payeeCode"))) .thenReturn(Uni.createFrom().item(10L)); - Mockito.when(terminalService.getTerminalListPagedByAttribute("payeeCode", "payeeCode", 0, 10)) - .thenReturn(Uni.createFrom().item(new ArrayList<>())); + Mockito.when(terminalService.findBySolutionIds(Collections.singletonList("payeeCode"), 0, 10)) + .thenReturn(Uni.createFrom().item(mockedList())); Response response = given() .contentType(ContentType.JSON) @@ -368,11 +439,14 @@ void testFindByPayeeCode_200() { @Claim(key = "sub", value = "AGID_01") }) void testFindByPspId_200() { - Mockito.when(terminalService.getTerminalCountByAttribute("AGID_01", "AGID_01")) + Mockito.when(solutionService.findAllByLocationOrPsp(any(String.class), any(String.class))) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + Mockito.when(terminalService.countBySolutionIds(Collections.singletonList("pspId"))) .thenReturn(Uni.createFrom().item(10L)); - Mockito.when(terminalService.getTerminalListPagedByAttribute("AGID_01", "AGID_01", 0, 10)) - .thenReturn(Uni.createFrom().item(new ArrayList<>())); + Mockito.when(terminalService.findBySolutionIds(Collections.singletonList("pspId"), 0, 10)) + .thenReturn(Uni.createFrom().item(mockedList())); Response response = given() .contentType(ContentType.JSON) @@ -393,8 +467,63 @@ void testFindByPspId_200() { @JwtSecurity(claims = { @Claim(key = "sub", value = "payeeCode") }) - void testFindByPayeeCode_500TC() { - Mockito.when(terminalService.getTerminalCountByAttribute("payeeCode", "payeeCode")) + void testFindByPayeeCode_500FABL() { + Mockito.when(solutionService.findAllByLocationOrPsp(any(String.class), any(String.class))) + .thenReturn(Uni.createFrom().failure(new WebApplicationException())); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .queryParam("payeeCode", "payeeCode") + .queryParam("page", 0) + .queryParam("size", 10) + .when() + .get("/findByPayeeCode") + .then() + .extract().response(); + + Assertions.assertEquals(500, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "payeeCode") + }) + void testFindByPayeeCode_404() { + List empty = new ArrayList<>(); + Mockito.when(solutionService.findAllByLocationOrPsp(any(String.class), any(String.class))) + .thenReturn(Uni.createFrom().item(empty)); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .queryParam("payeeCode", "payeeCode") + .queryParam("page", 0) + .queryParam("size", 10) + .when() + .get("/findByPayeeCode") + .then() + .extract().response(); + + Assertions.assertEquals(404, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "payeeCode") + }) + void testFindByPayeeCode_500CBS() { + List mockedSolutions = mockedListSolution(); + Mockito.when(solutionService.findAllByLocationOrPsp(any(String.class), any(String.class))) + .thenReturn(Uni.createFrom().item(mockedSolutions)); + + List solutionIds = mockedSolutions.stream() + .map(solution -> solution.id.toString()) + .toList(); + + Mockito.when(terminalService.countBySolutionIds(solutionIds)) .thenReturn(Uni.createFrom().failure(new WebApplicationException())); Response response = given() @@ -416,11 +545,19 @@ void testFindByPayeeCode_500TC() { @JwtSecurity(claims = { @Claim(key = "sub", value = "payeeCode") }) - void testFindByPayeeCode_500TLP() { - Mockito.when(terminalService.getTerminalCountByAttribute("payeeCode", "payeeCode")) + void testFindByPayeeCode_500FBS() { + List mockedSolutions = mockedListSolution(); + Mockito.when(solutionService.findAllByLocationOrPsp(any(String.class), any(String.class))) + .thenReturn(Uni.createFrom().item(mockedSolutions)); + + List solutionIds = mockedSolutions.stream() + .map(solution -> solution.id.toString()) + .toList(); + + Mockito.when(terminalService.countBySolutionIds(solutionIds)) .thenReturn(Uni.createFrom().item(10L)); - Mockito.when(terminalService.getTerminalListPagedByAttribute("payeeCode", "payeeCode", 0, 10)) + Mockito.when(terminalService.findBySolutionIds(solutionIds, 0, 10)) .thenReturn(Uni.createFrom().failure(new WebApplicationException())); Response response = given() @@ -443,16 +580,20 @@ void testFindByPayeeCode_500TLP() { @Claim(key = "sub", value = "AGID_01") }) void testFindByWorkstation_200() { - Mockito.when(terminalService.getTerminalCountByAttribute("workstation", "workstation")) + Mockito.when(solutionService.getSolutionsListByLocationCode(anyString())) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + Mockito.when(terminalService.getTerminalCountByWorkstation("workstation", Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf"))) .thenReturn(Uni.createFrom().item(10L)); - Mockito.when(terminalService.getTerminalListPagedByAttribute("workstation", "workstation", 0, 10)) + Mockito.when(terminalService.getTerminalListPagedByWorkstation("workstation", 0, 10, Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf"))) .thenReturn(Uni.createFrom().item(new ArrayList<>())); Response response = given() .contentType(ContentType.JSON) .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") .queryParam("workstation", "workstation") + .queryParam("payeeCode", "AGID_01") .queryParam("page", 0) .queryParam("size", 10) .when() @@ -468,10 +609,121 @@ void testFindByWorkstation_200() { @JwtSecurity(claims = { @Claim(key = "sub", value = "AGID_01") }) + void testFindByWorkstation_500SL() { + Mockito.when(solutionService.getSolutionsListByLocationCode(anyString())) + .thenReturn(Uni.createFrom().failure(new WebApplicationException())); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .queryParam("workstation", "workstation") + .queryParam("payeeCode", "AGID_01") + .queryParam("page", 0) + .queryParam("size", 10) + .when() + .get("/findByWorkstation") + .then() + .extract().response(); + + Assertions.assertEquals(500, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "AGID_01") + }) + void testFindByWorkstation_404() { + List empty = new ArrayList<>(); + Mockito.when(solutionService.getSolutionsListByLocationCode(anyString())) + .thenReturn(Uni.createFrom().item(empty)); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .queryParam("workstation", "workstation") + .queryParam("payeeCode", "AGID_01") + .queryParam("page", 0) + .queryParam("size", 10) + .when() + .get("/findByWorkstation") + .then() + .extract().response(); + + Assertions.assertEquals(404, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "06534340721") + }) + void testFindByWorkstation_500TC() { + Mockito.when(solutionService.getSolutionsListByLocationCode("06534340721")) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + List solutionIds = mockedListSolution().stream().map(solution -> solution.id.toString()).toList(); + Mockito.when(terminalService.getTerminalCountByWorkstation("workstation", solutionIds)) + .thenReturn(Uni.createFrom().failure(new WebApplicationException())); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .queryParam("workstation", "workstation") + .queryParam("payeeCode", "06534340721") + .queryParam("page", 0) + .queryParam("size", 10) + .when() + .get("/findByWorkstation") + .then() + .extract().response(); + + Assertions.assertEquals(500, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "06534340721") + }) + void testFindByWorkstation_500TLP() { + Mockito.when(solutionService.getSolutionsListByLocationCode("06534340721")) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + List solutionIds = mockedListSolution().stream().map(solution -> solution.id.toString()).toList(); + Mockito.when(terminalService.getTerminalCountByWorkstation("workstation", solutionIds)) + .thenReturn(Uni.createFrom().item(10L)); + + Mockito.when(terminalService.getTerminalListPagedByWorkstation("workstation", 0, 10, solutionIds)) + .thenReturn(Uni.createFrom().failure(new WebApplicationException())); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .queryParam("workstation", "workstation") + .queryParam("payeeCode", "06534340721") + .queryParam("page", 0) + .queryParam("size", 10) + .when() + .get("/findByWorkstation") + .then() + .extract().response(); + + Assertions.assertEquals(500, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "TMIL0101") + }) void testUpdateWorkstations_204() { Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); + Mockito.when(solutionService.findById(terminalEntity.getSolutionId())) + .thenReturn(Uni.createFrom().item(solutionEntity)); + Mockito.when(terminalService.updateWorkstations(any(WorkstationsDto.class), any(TerminalEntity.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); @@ -488,6 +740,31 @@ void testUpdateWorkstations_204() { Assertions.assertEquals(204, response.statusCode()); } + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "AGID_01") + }) + void testUpdateWorkstations_401() { + Mockito.when(terminalService.findTerminal(any(String.class))) + .thenReturn(Uni.createFrom().item(terminalEntity)); + + Mockito.when(solutionService.findById(terminalEntity.getSolutionId())) + .thenReturn(Uni.createFrom().item(solutionEntity)); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .and() + .body(workstationsDto) + .when() + .patch("/d43d21a5-f8a7-4a68-8320-60b8f342c4aa/updateWorkstations") + .then() + .extract().response(); + + Assertions.assertEquals(401, response.statusCode()); + } + @Test @TestSecurity(user = "testUser", roles = {"public_administration"}) @JwtSecurity(claims = { @@ -537,12 +814,40 @@ void testUpdateWorkstations_500FT() { @Test @TestSecurity(user = "testUser", roles = {"public_administration"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") + }) + void testUpdateWorkstations_500SI() { + Mockito.when(terminalService.findTerminal(any(String.class))) + .thenReturn(Uni.createFrom().item(terminalEntity)); + + Mockito.when(solutionService.findById(terminalEntity.getSolutionId())) + .thenReturn(Uni.createFrom().failure(new WebApplicationException())); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .and() + .body(workstationsDto) + .when() + .patch("/d43d21a5-f8a7-4a68-8320-60b8f342c4aa/updateWorkstations") + .then() + .extract().response(); + + Assertions.assertEquals(500, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"public_administration"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "TMIL0101") }) void testUpdateWorkstations_500UT() { Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); + Mockito.when(solutionService.findById(terminalEntity.getSolutionId())) + .thenReturn(Uni.createFrom().item(solutionEntity)); + Mockito.when(terminalService.updateWorkstations(any(WorkstationsDto.class), any(TerminalEntity.class))) .thenReturn(Uni.createFrom().failure(new WebApplicationException())); @@ -562,9 +867,12 @@ void testUpdateWorkstations_500UT() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testUpdateTerminal_204() { + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); @@ -587,9 +895,36 @@ void testUpdateTerminal_204() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") + }) + void testUpdateTerminal_404SE() { + solutionEntity = null; + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .and() + .body(terminalDto) + .when() + .patch("/d43d21a5-f8a7-4a68-8320-60b8f342c4aa") + .then() + .extract().response(); + + solutionEntity = TestData.getCorrectSolutionEntity(); + Assertions.assertEquals(404, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "TMIL0101") }) void testUpdateTerminal_404() { + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + terminalEntity = null; Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); @@ -611,9 +946,12 @@ void testUpdateTerminal_404() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testUpdateTerminal_500FT() { + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().failure(new WebApplicationException())); @@ -633,9 +971,12 @@ void testUpdateTerminal_500FT() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testUpdateTerminal_500UT() { + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); @@ -658,12 +999,15 @@ void testUpdateTerminal_500UT() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testDeleteTerminal_204() { Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + Mockito.when(terminalService.deleteTerminal(any(TerminalEntity.class))) .thenReturn(Uni.createFrom().voidItem()); @@ -682,7 +1026,7 @@ void testDeleteTerminal_204() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testDeleteTerminal_404() { terminalEntity = null; @@ -706,7 +1050,34 @@ void testDeleteTerminal_404() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") + }) + void testDeleteTerminal_404SE() { + Mockito.when(terminalService.findTerminal(any(String.class))) + .thenReturn(Uni.createFrom().item(terminalEntity)); + + solutionEntity = null; + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + + Response response = given() + .contentType(ContentType.JSON) + .header("RequestId", "1a2b3c4d-5e6f-789a-bcde-f0123456789a") + .and() + .body(terminalDto) + .when() + .delete("/d43d21a5-f8a7-4a68-8320-60b8f342c4aa") + .then() + .extract().response(); + + solutionEntity = TestData.getCorrectSolutionEntity(); + Assertions.assertEquals(404, response.statusCode()); + } + + @Test + @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) + @JwtSecurity(claims = { + @Claim(key = "sub", value = "TMIL0101") }) void testDeleteTerminal_500FT() { Mockito.when(terminalService.findTerminal(any(String.class))) @@ -728,12 +1099,15 @@ void testDeleteTerminal_500FT() { @Test @TestSecurity(user = "testUser", roles = {"pos_service_provider"}) @JwtSecurity(claims = { - @Claim(key = "sub", value = "AGID_01") + @Claim(key = "sub", value = "TMIL0101") }) void testDeleteTerminal_500UT() { Mockito.when(terminalService.findTerminal(any(String.class))) .thenReturn(Uni.createFrom().item(terminalEntity)); + Mockito.when(solutionService.findById(any(String.class))) + .thenReturn(Uni.createFrom().item(solutionEntity)); + Mockito.when(terminalService.deleteTerminal(any(TerminalEntity.class))) .thenReturn(Uni.createFrom().failure(new WebApplicationException())); diff --git a/src/test/java/it/pagopa/swclient/mil/papos/service/SolutionServiceTest.java b/src/test/java/it/pagopa/swclient/mil/papos/service/SolutionServiceTest.java index a88a99d..ebe736d 100644 --- a/src/test/java/it/pagopa/swclient/mil/papos/service/SolutionServiceTest.java +++ b/src/test/java/it/pagopa/swclient/mil/papos/service/SolutionServiceTest.java @@ -18,10 +18,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockito.Mockito; - +import static it.pagopa.swclient.mil.papos.util.TestData.mockedListSolution; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; -import static it.pagopa.swclient.mil.papos.util.TestData.mockedSolutionEntityList; import java.util.List; @@ -97,19 +96,18 @@ void testGetSolutionsCount_Success() { @Test void testFindSolutions_Success() { - ReactivePanacheQuery query = Mockito.mock(ReactivePanacheQuery.class); Mockito.when(query.page(anyInt(), anyInt())).thenReturn(query); - Mockito.when(query.list()).thenReturn(Uni.createFrom().item(mockedSolutionEntityList())); + Mockito.when(query.list()).thenReturn(Uni.createFrom().item(mockedListSolution())); Mockito.when(solutionRepository.findAll()) .thenReturn(query); - Uni> solutionsEntityUni = solutionService.findSolutions("requestid", 1, 10); + Uni> solutionsEntityUni = solutionService.findSolutions(1, 10); solutionsEntityUni .subscribe() - .with(list -> Assertions.assertEquals(mockedSolutionEntityList(), list)); + .with(list -> Assertions.assertEquals(mockedListSolution(), list)); } @@ -128,16 +126,40 @@ void testGetSolutionByAttributeCount_Success() { @Test void testGetSolutionsList_Success() { - ReactivePanacheQuery query = Mockito.mock(ReactivePanacheQuery.class); Mockito.when(query.page(anyInt(), anyInt())).thenReturn(query); - Mockito.when(query.list()).thenReturn(Uni.createFrom().item(mockedSolutionEntityList())); + Mockito.when(query.list()).thenReturn(Uni.createFrom().item(mockedListSolution())); Mockito.when(solutionRepository.find(String.format("%s = ?1", "pspId"), "pspId")).thenReturn(query); Uni> result = solutionService.getSolutionsListPagedByAttribute("pspId", "pspId", 0, 10); result.subscribe() - .with(list -> Assertions.assertEquals(mockedSolutionEntityList(), list)); + .with(list -> Assertions.assertEquals(mockedListSolution(), list)); + } + + @Test + void testFindBy_Success() { + Mockito.when(solutionRepository.list(String.format("%s = ?1", "locationCode"), "12704343560")) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + Uni> result = solutionService.findAllByLocationOrPsp("locationCode", "12704343560"); + + result.subscribe() + .with(list -> Assertions.assertEquals(mockedListSolution(), list)); + } + + @Test + void testFindAllByPspAndSolutionId_Success() { + List solutionIds = List.of("66a79a4624356b00da07cfbf", "66a79a4624346b20da01cfbf"); + List solutionObjectIds = solutionIds.stream().map(ObjectId::new).toList(); + + Mockito.when(solutionRepository.list("pspId = ?1 and _id in ?2", "TMIL0101", solutionObjectIds)) + .thenReturn(Uni.createFrom().item(mockedListSolution())); + + Uni> result = solutionService.findAllByPspAndSolutionId("TMIL0101", solutionIds); + + result.subscribe() + .with(list -> Assertions.assertEquals(mockedListSolution(), list)); } @@ -164,4 +186,16 @@ void testDeleteSolution_Failure() { .assertFailedWith(WebApplicationException.class); } + @Test + void testFindByLocationCode_Success() { + ReactivePanacheQuery mockQuery = Mockito.mock(ReactivePanacheQuery.class); + Mockito.when(mockQuery.list()).thenReturn(Uni.createFrom().item(mockedListSolution())); + Mockito.when(solutionRepository.find("locationCode = ?1", "06534340721")) + .thenReturn(mockQuery); + + Uni> result = solutionService.getSolutionsListByLocationCode("06534340721"); + + result.subscribe() + .with(list -> Assertions.assertEquals(mockedListSolution(), list)); + } } diff --git a/src/test/java/it/pagopa/swclient/mil/papos/service/TerminalServiceTest.java b/src/test/java/it/pagopa/swclient/mil/papos/service/TerminalServiceTest.java index 5e74f76..da60bf9 100644 --- a/src/test/java/it/pagopa/swclient/mil/papos/service/TerminalServiceTest.java +++ b/src/test/java/it/pagopa/swclient/mil/papos/service/TerminalServiceTest.java @@ -4,10 +4,7 @@ import io.quarkus.test.junit.QuarkusTest; import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.helpers.test.UniAssertSubscriber; -import it.pagopa.swclient.mil.papos.dao.BulkLoadStatusEntity; -import it.pagopa.swclient.mil.papos.dao.BulkLoadStatusRepository; -import it.pagopa.swclient.mil.papos.dao.TerminalEntity; -import it.pagopa.swclient.mil.papos.dao.TerminalRepository; +import it.pagopa.swclient.mil.papos.dao.*; import it.pagopa.swclient.mil.papos.model.TerminalDto; import it.pagopa.swclient.mil.papos.model.WorkstationsDto; import it.pagopa.swclient.mil.papos.util.TestData; @@ -18,10 +15,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockito.Mockito; + +import java.util.Arrays; import java.util.List; -import static it.pagopa.swclient.mil.papos.util.TestData.mockedList; -import static it.pagopa.swclient.mil.papos.util.TestData.mockedListTerminalDto; +import static it.pagopa.swclient.mil.papos.util.TestData.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -84,7 +82,7 @@ void testProcessBulkLoad_Success() { Mockito.when(bulkLoadStatusRepository.persist(any(BulkLoadStatusEntity.class))) .thenReturn(Uni.createFrom().item(new BulkLoadStatusEntity())); - Uni result = terminalService.processBulkLoad(mockedListTerminalDto()); + Uni result = terminalService.processBulkLoad(mockedListTerminalDto(), 2, "AGID_01"); result.subscribe() .withSubscriber(UniAssertSubscriber.create()) @@ -98,7 +96,7 @@ void testProcessBulkLoad_CreateTerminalFailure() { Mockito.when(bulkLoadStatusRepository.persist(any(BulkLoadStatusEntity.class))) .thenReturn(Uni.createFrom().item(new BulkLoadStatusEntity())); - Uni result = terminalService.processBulkLoad(mockedListTerminalDto()); + Uni result = terminalService.processBulkLoad(mockedListTerminalDto(), 2, "AGID_01"); result.subscribe() .withSubscriber(UniAssertSubscriber.create()) @@ -126,32 +124,19 @@ void testProcessBulkLoad_PersistenceError() { Mockito.when(bulkLoadStatusRepository.persist(any(BulkLoadStatusEntity.class))) .thenReturn(Uni.createFrom().failure(new RuntimeException("Error persisting bulk load status"))); - Uni result = terminalService.processBulkLoad(mockedListTerminalDto()); + Uni result = terminalService.processBulkLoad(mockedListTerminalDto(), 2, "AGID_01"); result.subscribe() .withSubscriber(UniAssertSubscriber.create()) .assertFailedWith(RuntimeException.class, "Error persisting bulk load status"); } - @Test - void testGetTerminalCount_Success() { - Mockito.when(terminalRepository.count("pspId", "pspId")) - .thenReturn(Uni.createFrom().item(10L)); - - var terminalCount = terminalService.getTerminalCountByAttribute("pspId", "pspId"); - - terminalCount - .subscribe() - .withSubscriber(UniAssertSubscriber.create()) - .assertItem(10L); - } - @Test void testGetTerminalCountWorkstation_Success() { - Mockito.when(terminalRepository.count("{ 'workstations': ?1 }", "workstation")) + Mockito.when(terminalRepository.count("workstations = ?1 and solutionId in ?2", "workstation", Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf"))) .thenReturn(Uni.createFrom().item(10L)); - var terminalCount = terminalService.getTerminalCountByAttribute("workstation", "workstation"); + var terminalCount = terminalService.getTerminalCountByWorkstation("workstation", Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf")); terminalCount .subscribe() @@ -159,27 +144,14 @@ void testGetTerminalCountWorkstation_Success() { .assertItem(10L); } - @Test - void testGetTerminalList_Success() { - ReactivePanacheQuery query = Mockito.mock(ReactivePanacheQuery.class); - Mockito.when(query.page(anyInt(), anyInt())).thenReturn(query); - Mockito.when(query.list()).thenReturn(Uni.createFrom().item(mockedList())); - Mockito.when(terminalRepository.find(String.format("%s = ?1", "pspId"), "pspId")).thenReturn(query); - - Uni> result = terminalService.getTerminalListPagedByAttribute("pspId", "pspId", 0, 10); - - result.subscribe() - .with(list -> Assertions.assertEquals(mockedList(), list)); - } - @Test void testGetTerminalListWorkstation_Success() { ReactivePanacheQuery query = Mockito.mock(ReactivePanacheQuery.class); Mockito.when(query.page(anyInt(), anyInt())).thenReturn(query); Mockito.when(query.list()).thenReturn(Uni.createFrom().item(mockedList())); - Mockito.when(terminalRepository.find("{ 'workstations': ?1 }", "workstation")).thenReturn(query); + Mockito.when(terminalRepository.find("workstations = ?1 and solutionId in ?2", "workstation", Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf"))).thenReturn(query); - Uni> result = terminalService.getTerminalListPagedByAttribute("workstation", "workstation", 0, 10); + Uni> result = terminalService.getTerminalListPagedByWorkstation("workstation", 0, 10, Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf")); result.subscribe() .with(list -> Assertions.assertEquals(mockedList(), list)); @@ -267,4 +239,30 @@ void testDeleteTerminal_Failure() { .withSubscriber(UniAssertSubscriber.create()) .assertFailedWith(WebApplicationException.class); } + + @Test + void testCountBySolutionIds_Success() { + Mockito.when(terminalRepository.count("solutionId in (?1)", Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf"))) + .thenReturn(Uni.createFrom().item(10L)); + + var terminalCount = terminalService.countBySolutionIds(Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf")); + + terminalCount + .subscribe() + .withSubscriber(UniAssertSubscriber.create()) + .assertItem(10L); + } + + @Test + void testFindBySolutionIds_Success() { + ReactivePanacheQuery query = Mockito.mock(ReactivePanacheQuery.class); + Mockito.when(query.page(anyInt(), anyInt())).thenReturn(query); + Mockito.when(query.list()).thenReturn(Uni.createFrom().item(mockedList())); + Mockito.when(terminalRepository.find("solutionId in ?1", Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf"))).thenReturn(query); + + Uni> result = terminalService.findBySolutionIds(Arrays.asList("66a79a4624356b00da07cfbf", "16a79a4624356b00da07cfbf"), 0, 10); + + result.subscribe() + .with(list -> Assertions.assertEquals(mockedList(), list)); + } } diff --git a/src/test/java/it/pagopa/swclient/mil/papos/util/TestData.java b/src/test/java/it/pagopa/swclient/mil/papos/util/TestData.java index 0ba58e7..5f83f2c 100644 --- a/src/test/java/it/pagopa/swclient/mil/papos/util/TestData.java +++ b/src/test/java/it/pagopa/swclient/mil/papos/util/TestData.java @@ -18,6 +18,7 @@ public static TerminalDto getCorrectTerminalDto() { public static TerminalEntity getCorrectTerminalEntity() { TerminalEntity terminalEntity = new TerminalEntity(); + terminalEntity.setSolutionId("66a79a4624356b00da07cfbf"); terminalEntity.setTerminalUuid("74a7c24f-5c64-41c2-aeac-d1fae93bff49"); terminalEntity.setTerminalId("34523860"); terminalEntity.setEnabled(true); @@ -29,6 +30,7 @@ public static TerminalEntity getCorrectTerminalEntity() { public static BulkLoadStatusEntity getCorrectBulkLoadStatusEntity() { BulkLoadStatusEntity bulkLoadStatusEntity = new BulkLoadStatusEntity(); bulkLoadStatusEntity.setBulkLoadingId("74a7c24f-5c64-41c2-aeac-d1fae93bff49"); + bulkLoadStatusEntity.setPspId("AGID_01"); bulkLoadStatusEntity.setSuccessRecords(5); bulkLoadStatusEntity.setFailedRecords(0); bulkLoadStatusEntity.setTotalRecords(5); @@ -80,17 +82,19 @@ public static List mockedList() { return List.of(te1, te2); } - - public static List mockedSolutionEntityList() { - - SolutionEntity te1 = new SolutionEntity(); - te1.setPspId("uuid1"); - SolutionEntity te2 = new SolutionEntity(); - te2.setPspId("uuid2"); - return List.of(te1, te2); + public static List mockedListSolution() { + SolutionEntity se1 = new SolutionEntity(); + se1.id = new ObjectId("66a79a4624356b00da07cfbf"); + se1.setPspId("TMIL0101"); + se1.setLocationCode("06534340721"); + SolutionEntity se2 = new SolutionEntity(); + se2.id = new ObjectId("66a79a4624346b20da01cfbf"); + se2.setPspId("TMIL0101"); + se2.setLocationCode("06534340721"); + + return List.of(se1, se2); } - public static List mockedListTerminalDto() { TerminalDto td1 = new TerminalDto("66a79a4624356b00da07cfbf", "34523860", true, null); TerminalDto td2 = new TerminalDto("66a79a4624356b00da07cfbf", "34523861", false, null); diff --git a/src/test/postman/bulkloadTerminals.json b/src/test/postman/bulkloadTerminals.json deleted file mode 100644 index 9104217..0000000 --- a/src/test/postman/bulkloadTerminals.json +++ /dev/null @@ -1,32 +0,0 @@ -[ - { - "pspId": "TMIL0101", - "terminalId": "34523860", - "enabled": true, - "payeeCode": "06534340721" - }, - { - "pspId": "TMIL0101", - "terminalId": "84523987", - "enabled": false, - "payeeCode": "12345678901" - }, - { - "pspId": "TMIL0101", - "terminalId": "94523012", - "enabled": true, - "payeeCode": "98765432100" - }, - { - "pspId": "TMIL0101", - "terminalId": "74523123", - "enabled": false, - "payeeCode": "11223344556" - }, - { - "pspId": "TMIL0101", - "terminalId": "64523234", - "enabled": true, - "payeeCode": "66778899001" - } -] diff --git a/src/test/postman/dev.postman_environment.json b/src/test/postman/dev.postman_environment.json index 92d460e..e261c8f 100644 --- a/src/test/postman/dev.postman_environment.json +++ b/src/test/postman/dev.postman_environment.json @@ -1,6 +1,6 @@ { - "id": "99b9d59a-3023-4065-bbff-443e3d3967f8", - "name": "dev", + "id": "56489422-d079-41a7-89b3-db856e25df77", + "name": "mil-papos - DEV", "values": [ { "key": "MIL_PAPOS_BASE_URL", @@ -39,31 +39,37 @@ "enabled": true }, { - "key": "access_token_psp", + "key": "clientIdAdm", "value": "", - "type": "any", + "type": "default", "enabled": true }, { - "key": "access_token_pa", + "key": "clientSecretAdm", "value": "", "type": "default", "enabled": true }, { - "key": "access_token_admin", + "key": "access_token_psp", + "value": "", + "type": "any", + "enabled": true + }, + { + "key": "access_token_pa", "value": "", "type": "default", "enabled": true }, { - "key": "filePathBulkload", + "key": "access_token_admin", "value": "", "type": "default", "enabled": true } ], "_postman_variable_scope": "environment", - "_postman_exported_at": "2024-07-29T14:14:04.461Z", - "_postman_exported_using": "Postman/11.5.1" + "_postman_exported_at": "2024-08-02T09:21:24.954Z", + "_postman_exported_using": "Postman/11.6.2" } \ No newline at end of file diff --git a/src/test/postman/mil-papos.postman_collection.json b/src/test/postman/mil-papos.postman_collection.json index 7f03f4e..1608994 100644 --- a/src/test/postman/mil-papos.postman_collection.json +++ b/src/test/postman/mil-papos.postman_collection.json @@ -194,6 +194,97 @@ } }, "response": [] + }, + { + "name": "Get Papos Admin Access Token", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.have.status(200);\r", + "});\r", + "pm.test(\"Body matches string\", function () {\r", + " pm.expect(pm.response.text()).to.include(\"access_token\");\r", + " pm.expect(pm.response.text()).to.include(\"token_type\");\r", + " pm.expect(pm.response.text()).to.include(\"expires_in\");\r", + "\r", + " pm.test(\"Token type\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData.token_type).to.eql(\"Bearer\");\r", + " pm.environment.set(\"access_token_admin\", jsonData.access_token);\r", + "\r", + " });\r", + "\r", + " \r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "protocolProfileBehavior": { + "disabledSystemHeaders": {} + }, + "request": { + "auth": { + "type": "noauth" + }, + "method": "POST", + "header": [ + { + "key": "RequestId", + "value": "{{requestId}}" + }, + { + "key": "Version", + "value": "{{mil_auth_api_version}}" + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "grant_type", + "value": "client_credentials", + "type": "text" + }, + { + "key": "client_id", + "value": "{{clientIdAdm}}", + "type": "text" + }, + { + "key": "client_secret", + "value": "{{clientSecretAdm}}", + "type": "default" + } + ] + }, + "url": { + "raw": "{{MIL_AUTH_BASE_URL}}/token", + "host": [ + "{{MIL_AUTH_BASE_URL}}" + ], + "path": [ + "token" + ] + } + }, + "response": [] } ] }, @@ -220,9 +311,6 @@ } ], "request": { - "auth": { - "type": "noauth" - }, "method": "POST", "header": [ { @@ -253,6 +341,38 @@ }, "response": [] } + ], + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token_admin}}", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + } ] }, { @@ -298,8 +418,65 @@ }, "response": [] } + ], + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{access_token_admin}}", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + } ] } + ], + "auth": { + "type": "noauth" + }, + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + } ] }, { @@ -407,8 +584,8 @@ "formdata": [ { "key": "file", - "type": "file", - "src": "{{filePathBulkload}}" + "value": "[ { \"solutionId\": \"66a79a4624356b00da07cfbf\", \"terminalId\": \"34523860\", \"enabled\": true }, { \"solutionId\": \"66a79a4624346b20da01cfbf\", \"terminalId\": \"84523987\", \"enabled\": false }, { \"solutionId\": \"{{solutionId}}\", \"terminalId\": \"94523012\", \"enabled\": true }, { \"solutionId\": \"{{solutionId}}\", \"terminalId\": \"74523123\", \"enabled\": false }, { \"solutionId\": \"{{solutionId}}\", \"terminalId\": \"64523234\", \"enabled\": true } ]", + "type": "text" } ] }, @@ -544,7 +721,7 @@ } ], "url": { - "raw": "{{MIL_PAPOS_BASE_URL}}/terminals/findByPayeeCode?payeeCode={{payeeCode}}&page={{getTerminalPage}}&size={{getTerminalPageSize}}", + "raw": "{{MIL_PAPOS_BASE_URL}}/terminals/findByPayeeCode?payeeCode={{locationCode}}&page={{getTerminalPage}}&size={{getTerminalPageSize}}", "host": [ "{{MIL_PAPOS_BASE_URL}}" ], @@ -555,7 +732,7 @@ "query": [ { "key": "payeeCode", - "value": "{{payeeCode}}", + "value": "{{locationCode}}", "description": "(Required) Fiscal code of the subject that receives the payment" }, { @@ -640,16 +817,21 @@ "description": "Returns a page of terminals by psp id" }, "response": [] - }, + } + ] + }, + { + "name": "3. Update Terminal", + "item": [ { - "name": "Find By Workstation", + "name": "Update Workstations", "event": [ { "listen": "test", "script": { "exec": [ - "pm.test(\"Status code is 200\", function () {", - " pm.response.to.have.status(200);", + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", "});", "" ], @@ -669,7 +851,7 @@ } ] }, - "method": "GET", + "method": "PATCH", "header": [ { "key": "RequestId", @@ -677,51 +859,39 @@ "description": "(Required) Request Id that will be logged by services" } ], + "body": { + "mode": "raw", + "raw": "{\r\n \"workstations\": [\"cassa-1-ufficio-1\",\"cassa-3-ufficio-1\"]\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, "url": { - "raw": "{{MIL_PAPOS_BASE_URL}}/terminals/findByWorkstation?workstation={{workstation}}&page={{getTerminalPage}}&size={{getTerminalPageSize}}", + "raw": "{{MIL_PAPOS_BASE_URL}}/terminals/{{terminalUuid}}/updateWorkstations", "host": [ "{{MIL_PAPOS_BASE_URL}}" ], "path": [ "terminals", - "findByWorkstation" - ], - "query": [ - { - "key": "workstation", - "value": "{{workstation}}", - "description": "(Required) Fiscal code of the subject that receives the payment" - }, - { - "key": "page", - "value": "{{getTerminalPage}}", - "description": "(Required) Number of the requested page of data" - }, - { - "key": "size", - "value": "{{getTerminalPageSize}}", - "description": "(Required) Size of the requested page of data" - } + "{{terminalUuid}}", + "updateWorkstations" ] }, - "description": "Returns the list of terminals linked to a cash desk" + "description": "Updates the list of cash desks linked to the terminal" }, "response": [] - } - ] - }, - { - "name": "3. Update Terminal", - "item": [ + }, { - "name": "Update Workstations", + "name": "Find By Workstation", "event": [ { "listen": "test", "script": { "exec": [ - "pm.test(\"Status code is 204\", function () {", - " pm.response.to.have.status(204);", + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", "});", "" ], @@ -741,7 +911,7 @@ } ] }, - "method": "PATCH", + "method": "GET", "header": [ { "key": "RequestId", @@ -749,27 +919,39 @@ "description": "(Required) Request Id that will be logged by services" } ], - "body": { - "mode": "raw", - "raw": "{\r\n \"workstations\": [\"cassa-1-ufficio-1\",\"cassa-3-ufficio-1\"]\r\n}", - "options": { - "raw": { - "language": "json" - } - } - }, "url": { - "raw": "{{MIL_PAPOS_BASE_URL}}/terminals/{{terminalUuid}}/updateWorkstations", + "raw": "{{MIL_PAPOS_BASE_URL}}/terminals/findByWorkstation?workstation={{workstation}}&page={{getTerminalPage}}&size={{getTerminalPageSize}}&payeeCode={{locationCode}}", "host": [ "{{MIL_PAPOS_BASE_URL}}" ], "path": [ "terminals", - "{{terminalUuid}}", - "updateWorkstations" + "findByWorkstation" + ], + "query": [ + { + "key": "workstation", + "value": "{{workstation}}", + "description": "(Required) Cash desk label" + }, + { + "key": "page", + "value": "{{getTerminalPage}}", + "description": "(Required) Number of the requested page of data" + }, + { + "key": "size", + "value": "{{getTerminalPageSize}}", + "description": "(Required) Size of the requested page of data" + }, + { + "key": "payeeCode", + "value": "{{locationCode}}", + "description": "(Required) Fiscal code of the subject that receives the payment" + } ] }, - "description": "Updates the list of cash desks linked to the terminal" + "description": "Returns the list of terminals linked to a cash desk" }, "response": [] }, @@ -811,7 +993,7 @@ ], "body": { "mode": "raw", - "raw": "{\r\n \"terminalId\": \"67899876\",\r\n \"enabled\": false,\r\n \"payeeCode\": \"06534340721\",\r\n \"pspId\": \"pspspId\"\r\n}", + "raw": "{\r\n \"solutionId\": {{solutionId}},\r\n \"terminalId\": \"67899876\",\r\n \"enabled\": false\r\n}", "options": { "raw": { "language": "json" @@ -1505,6 +1687,11 @@ "key": "transactionAmount", "value": "40", "type": "string" + }, + { + "key": "solutionId", + "value": "", + "type": "string" } ] } \ No newline at end of file