diff --git a/helm/Chart.yaml b/helm/Chart.yaml index 281fd205..52c4a578 100644 --- a/helm/Chart.yaml +++ b/helm/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: pagopa-wisp-converter description: A service that permits to handle nodoInviaRPT and nodoInviaCarrelloRPT request from WISP, interfacing them with GPD system type: application -version: 0.202.0 -appVersion: 0.3.4 +version: 0.203.0 +appVersion: 0.3.4-1-PAGOPA-2104-new-api-recover-by-iuv dependencies: - name: microservice-chart version: 3.0.0 diff --git a/helm/values-dev.yaml b/helm/values-dev.yaml index 2fa6fd63..98305d66 100644 --- a/helm/values-dev.yaml +++ b/helm/values-dev.yaml @@ -4,7 +4,7 @@ microservice-chart: fullnameOverride: "" image: repository: ghcr.io/pagopa/pagopa-wisp-converter - tag: "0.3.4" + tag: "0.3.4-1-PAGOPA-2104-new-api-recover-by-iuv" pullPolicy: Always livenessProbe: httpGet: diff --git a/helm/values-prod.yaml b/helm/values-prod.yaml index 6c1fcec7..a7444f18 100644 --- a/helm/values-prod.yaml +++ b/helm/values-prod.yaml @@ -4,7 +4,7 @@ microservice-chart: fullnameOverride: "" image: repository: ghcr.io/pagopa/pagopa-wisp-converter - tag: "0.3.4" + tag: "0.3.4-1-PAGOPA-2104-new-api-recover-by-iuv" pullPolicy: Always livenessProbe: httpGet: diff --git a/helm/values-uat.yaml b/helm/values-uat.yaml index 42bb7ff7..c51d2cfc 100644 --- a/helm/values-uat.yaml +++ b/helm/values-uat.yaml @@ -4,7 +4,7 @@ microservice-chart: fullnameOverride: "" image: repository: ghcr.io/pagopa/pagopa-wisp-converter - tag: "0.3.4" + tag: "0.3.4-1-PAGOPA-2104-new-api-recover-by-iuv" pullPolicy: Always livenessProbe: httpGet: diff --git a/openapi/openapi.json b/openapi/openapi.json index 1ba93621..2189a116 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -4,7 +4,7 @@ "description": "A service that permits to handle nodoInviaRPT and nodoInviaCarrelloRPT request from WISP, converting them in NMU payments.\n\n# OPERATIVE INFO\n\n\n## EVENT MAPPING IN RE\n\n
Details\nFIELD | SCOPE | DESCRIPTION\n- | - | -\n**requestId** | BOTH | The identifier, set by X-Request-ID, from which the events can be grouped.\n**operationId** | BOTH | The identifier associated to a request identifier\n**clientOperationId** | BOTH | The identifier that associate a client to an operation identifier.\n**component** | BOTH | The applicative component from which the event is generated.
In NDP it is mapped with field 'componente'.
Values:
_WISP_SOAP_CONVERTER_
_WISP_CONVERTER_\n**insertedTimestamp** | BOTH | The time on which the event is inserted in RE storage\n**eventCategory** | BOTH | The category on which the event can be grouped.
In NDP it is mapped with field 'categoriaEvento'.
Values:
_INTERFACE_
_INTERNAL_\n**eventSubcategory** | BOTH | The subcategory related to the specific nature of the event.
In NDP it is mapped with field 'sottoTipoEvento'.
Values:
_REQ_
_RESP_
_INTERN_\n**callType** | INTERFACE | The type of role that the application has in the communication with the remote endpoint.
Values:
_SERVER_
_CLIENT_\n**outcome** | INTERFACE | The outcome of the operation described by the event.
In NDP it is mapped with field 'esito'.
Values:
_SEND_: Correctly sent request to HTTP endpoint. In NDP it is mapped with value 'INVIATA'.
_SEND_FAILURE_: Failed to send request to HTTP endpoint. In NDP it is mapped with value 'INVIATA_KO'
_RECEIVED_: Received an OK response from HTTP endpoint. In NDP it is mapped with value 'RICEVUTA_KO'
_RECEIVED_FAILURE_: Received a failure response from endpoint. In NDP it is mapped with value 'RICEVUTA_KO'
_NEVER_RECEIVED_: Failed to receive response at all from endpoint. In NDP it is mapped with value 'NO_RICEVUTA'
_EXECUTED_INTERNAL_STEP_: Executed internal step on execution. In NDP it is mapped with value 'CAMBIO_STATO'\n**httpMethod** | INTERFACE | The HTTP method of the endpoint related to the event.
This field is set only if the events that describe an HTTP communication with an external service.\n**httpUri** | INTERFACE | The URI related to the called endpoint.
This field is set only if the events that describe an HTTP communication with an external service.\n**httpHeaders** | INTERFACE | The list of HTTP headers extracted from the request/response analyzed by the event.
This field is set only if the events that describe an HTTP communication with an external service.\n**httpCallRemoteAddress** | INTERFACE | The remote IP address extracted from the called endpoint.
This field is set only if the events that describe an HTTP communication with an external service.\n**httpStatusCode** | INTERFACE | The status code extracted from the called endpoint.
This field is set only if the events that describe an HTTP communication with an external service.\n**executionTimeMs** | INTERFACE | The duration time of the invocation of the endpoint related to the event.
This field is set only if the events that describe an HTTP communication with an external service.\n**compressedPayload** | INTERFACE | The payload of the request/response analyzed by the event.
This value is zipped using GZip compression algorithm.\n**compressedPayloadLength** | INTERFACE | The length (in number of characters) of the compressed payload.\n**businessProcess** | INTERFACE | The descriptive label associated to the endpoint called by user and related to the whole process.\n**operationStatus** | INTERFACE | The final status of the whole operation.
This is set only in the events that describe the response in output to user.\n**operationErrorTitle** | INTERFACE | The error title extracted from the computation that refers to the error occurred during computation.
This is set only in the events that describe the response in output to user if there is an error.\n**operationErrorDetail** | INTERFACE | The error detail message extracted from the computation that refers to the error occurred during computation.
This is set only in the events that describe the response in output to user if there is an error.\n**operationErrorCode** | INTERFACE | The error code extracted from the computation that refers to the error occurred during computation.
This is set only in the events that describe the response in output to user if there is an error.\n**primitive** | INTERNAL | The typology of primitive analyzed and tracked by the event.
In NDP it is mapped with field 'eventType'.\n**sessionId** | INTERNAL | The session identifier generated by WISP SOAP Converter and used in the request.\n**cartId** | INTERNAL | The cart identifier used in the request.\n**iuv** | INTERNAL | The 'identificativo univoco pagamento' used in the request.\n**noticeNumber** | INTERNAL | The notice number (aka NAV code) used in the request.\n**domainId** | INTERNAL | The creditor institution identifier used in the request.\n**ccp** | INTERNAL | The 'codice contesto pagamento' used in the request.\n**psp** | INTERNAL | The payment service provider used in the request.\n**station** | INTERNAL | The station used in the request.\n**channel** | INTERNAL | The channel used in the request.\n**status** | INTERNAL | The state of the internal step executed.
Values:
_FOUND_RPT_IN_STORAGE_
_FOUND_RT_IN_STORAGE_
_EXTRACTED_DATA_FROM_RPT_
_CREATED_NEW_PAYMENT_POSITION_IN_GPD_
_GENERATED_NAV_FOR_NEW_PAYMENT_POSITION_
_UPDATED_EXISTING_PAYMENT_POSITION_IN_GPD_
_GENERATING_RT_FOR_INVALID_PAYMENT_POSITION_IN_GPD_
_GENERATING_RT_FOR_REDIRECT_ERROR_
_GENERATED_CACHE_ABOUT_RPT_FOR_DECOUPLER_
_GENERATED_CACHE_ABOUT_RPT_FOR_CARTSESSION_CACHING_
_GENERATED_CACHE_ABOUT_RPT_FOR_RT_GENERATION_
_SAVED_RPT_IN_CART_RECEIVED_REDIRECT_URL_FROM_CHECKOUT_
_RT_NOT_GENERABLE_FOR_GPD_STATION_
_RT_NOT_GENERABLE_FOR_NOT_EXISTING_PAYMENT_POSITION_
_NEGATIVE_RT_TRY_TO_SEND_TO_CREDITOR_INSTITUTION_
_POSITIVE_RT_TRY_TO_SEND_TO_CREDITOR_INSTITUTION_
_RT_SEND_SUCCESS_
_RT_SEND_FAILURE_
_RT_ALREADY_SENT_
_RT_SEND_SCHEDULING_SUCCESS_
_RT_SEND_SCHEDULING_FAILURE_
_RT_SCHEDULED_SEND_SUCCESS_
_RT_SCHEDULED_SEND_FAILURE_
_RT_SEND_RESCHEDULING_FAILURE_
_RT_SEND_RESCHEDULING_REACHED_MAX_RETRIES_
_RT_SEND_RESCHEDULING_SUCCESS_
_RT_START_RECONCILIATION_PROCESS_
_RT_END_RECONCILIATION_PROCESS_
_RECEIPT_TIMER_GENERATION_CREATED_SCHEDULED_SEND_
_RECEIPT_TIMER_GENERATION_CACHED_SEQUENCE_NUMBER_
_RECEIPT_TIMER_GENERATION_DELETED_SCHEDULED_SEND_
_RECEIPT_TIMER_GENERATION_SKIP_DELETE_SCHEDULED_SEND_
_RECEIPT_TIMER_PAYMENT_TOKEN_TIMEOUT_TRIGGER_
_ECOMMERCE_HANG_TIMER_TRIGGER_
_ECOMMERCE_HANG_TIMER_CREATED_
_ECOMMERCE_HANG_TIMER_DELETED_
_RPT_TIMER_TRIGGER_
_RPT_TIMER_CREATED_
_RPT_TIMER_DELETED_
_COMMUNICATING_WITH_GPD_REQUEST_
_COMMUNICATING_WITH_GPD_RESPONSE_
_COMMUNICATING_WITH_IUV_GENERATOR_REQUEST_
_COMMUNICATING_WITH_IUV_GENERATOR_RESPONSE_
_COMMUNICATING_WITH_CHECKOUT_REQUEST_
_COMMUNICATING_WITH_CHECKOUT_RESPONSE_
_COMMUNICATING_WITH_DECOUPLER_CACHING_REQUEST_
_COMMUNICATING_WITH_DECOUPLER_CACHING_RESPONSE_
_COMMUNICATING_WITH_CREDITOR_INSTITUTION_REQUEST_
_COMMUNICATING_WITH_CREDITOR_INSTITUTION_RESPONSE_\n**info** | INTERNAL | The other information that can be inserted for the tracing.\n**paymentToken** | INTERNAL | The payment token.\n\n
\n\n\n## OPERATIONAL ERROR CODES\n\n
Details\nNAME | CODE | DESCRIPTION\n- | - | -\n**WIC-500** | *ERROR* | A not documented generic error occurred while execution. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1000** | *GENERIC_ERROR* | A generic error occurred while executing conversion flow. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1001** | *PARSING_GENERIC_ERROR* | A generic error occurred while parsing of the content associated to the SOAP request related to nodoInviaRPT or nodoInviaCarrelloRPT. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1002** | *PARSING_INVALID_HEADER* | An error occurred while parsing of the content header, associated to the SOAP request related to nodoInviaRPT or nodoInviaCarrelloRPT.\n**WIC-1003** | *PARSING_INVALID_BODY* | An error occurred while parsing of the content payload, associated to the SOAP request related to nodoInviaRPT or nodoInviaCarrelloRPT.\n**WIC-1004** | *PARSING_INVALID_XML_NODES* | An error occurred while parsing of the of the content associated to the SOAP request related to nodoInviaRPT or nodoInviaCarrelloRPT. The XML content extracted, either from payload or from header, is invalid because it is not possible to extract tag nodes from document. So, the document is probably empty.\n**WIC-1005** | *PARSING_INVALID_ZIPPED_PAYLOAD* | An error occurred while parsing of the content associated to the SOAP request related to nodoInviaRPT or nodoInviaCarrelloRPT. The SOAP request analyzed and stored in dedicated storage is not usable for convert the debt positions in GPD system. This is probably due to an invalid conversion of the SOAP request via GZip algorithm executed before the same is stored in its storage.\n**WIC-1006** | *PARSING_RPT_PRIMITIVE_NOT_VALID* | An error occurred while parsing of the content associated to the SOAP request related to nodoInviaRPT or nodoInviaCarrelloRPT. The primitive (the content related to header 'soapaction') cannot be handled by WISP Converter application in redirect process: only one of nodoInviaRPT and nodoInviaCarrelloRPT can be accepted.\n**WIC-1100** | *VALIDATION_INVALID_MULTIBENEFICIARY_CART* | An error occurred while analyzing the RPTs extracted from SOAP request. In particular, the request is arrived as nodoInviaCarrelloRPT as multi-beneficiary cart, but the number of RPTs in the request is lower than two, so it cannot be correctly handled as multi-beneficiary.\n**WIC-1101** | *VALIDATION_INVALID_IBANS* | An error occurred while analyzing the RPTs extracted from SOAP request. An IBAN must always be set in RPT transfers if they aren't related to digital stamps (which don't require an IBAN, because they will be reported to specific subject). In this case, in one or more RPT transfers not related to digital stamp, the IBAN is not correctly set.\n**WIC-1102** | *VALIDATION_INVALID_DEBTOR* | An error occurred while analyzing the RPTs extracted from SOAP request. In particular, in a cart there are different debtor subjects and this is not permitted for this flow. So, the whole cart is discarded.\n**WIC-1200** | *CONFIGURATION_INVALID_CACHE* | An error occurred while trying to access data from cached configuration. It is possible that the cache is not retrieved yet by this service or a corrupted configuration was returned from APIConfig Cache internal service. If this problem still occurs, please check the connectivity with APIConfig Cache.\n**WIC-1201** | *CONFIGURATION_INVALID_STATION* | An error occurred while retrieving data from local cached configuration. In particular, it is not possible to retrieve the configuration about the station because it does not exists in cache, and maybe also in general configuration. So, a change in whole configuration and/or a refresh on cache is required.\n**WIC-1202** | *CONFIGURATION_INVALID_CREDITOR_INSTITUTION_STATION* | An error occurred while checking the station that will be used for the payment process. In particular, analyzing the station that is related to the segregation code extracted from a payment option's notice number, it turns out that the required station does not exists in cached configuration. So, a change in whole configuration and/or a refresh on cache is required.\n**WIC-1203** | *CONFIGURATION_INVALID_STATION_REDIRECT_URL* | An error occurred while checking the station that will be used for the payment process. In particular, analyzing the station that is related to the segregation code extracted from a payment option's notice number, it turns out that the configuration about redirection in error cases is not correctly set to points towards some creditor institution's endpoint. So, a change in configuration is required.\n**WIC-1204** | *CONFIGURATION_INVALID_STATION_SERVICE_URL* | An error occurred while checking the station that will be used for the payment process. In particular, analyzing the station that is related to the segregation code extracted from a payment option's notice number, it turns out that the configuration is not correctly set to points towards GPD service endpoint for RT generator. So, a change in configuration is required.\n**WIC-1205** | *CONFIGURATION_NOT_GPD_STATION* | An error occurred while checking the station that will be used for the payment process. In particular, analyzing the station that is related to the segregation code extracted from a payment option's notice number, it turns out that the configuration is not correctly set to points towards GPD service endpoint. So, a change in configuration is required.\n**WIC-1206** | *CONFIGURATION_INVALID_GPD_STATION* | An error occurred while checking the station that will be used for the payment process. In particular, analyzing the station that is related to the segregation code extracted from a payment option's notice number, it turns out that the configuration is correctly set to points towards GPD service endpoint but uses the 'v1' primitive version (and it must use the 'v2' version). So, a change in configuration is required.\n**WIC-1300** | *PAYMENT_POSITION_NOT_IN_PAYABLE_STATE* | An error occurred while checking an existing payment position. One or more RPTs extracted from the request refers to existing payment positions in GPD that have a state from which it is impossible to execute a payment flow. If the execution of this flow is related to a RPT cart, all the payments that can be retrieved or generated ex novo from those RPTs are declared as atomically invalid (if one RPT in cart is bad, all RPTs in cart are bad) and not payable with this flow.\n**WIC-1301** | *PAYMENT_POSITION_IN_INCONSISTENT_STATE* | An error occurred while checking an existing payment position in GPD system. The retrieved payment position, previously inserted in GPD by this same flow or by other procedures, is in an invalid state, not mappable to an existing value. This can be related to a wrong setting in GPD or a corruption of the retrieved data.\n**WIC-1302** | *PAYMENT_POSITION_NOT_VALID* | An error occurred while generating a payment position. In particular, something during the generation of a new payment position or the analysis of an existing payment position went wrong and the operation cannot be completed. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1303** | *PAYMENT_OPTION_NOT_EXTRACTABLE* | An error occurred while extracting a payment option from a payment position. This can be caused by a malformed payment position that does not have a payment option. Remember that a payment position in this flow must have one and only one payment option.\n**WIC-1400** | *RECEIPT_GENERATION_GENERIC_ERROR* | An error occurred while generating an RT (aka a receipt). An unhandled error occurred and it is impossible to complete the process. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1401** | *RECEIPT_GENERATION_WRONG_RESPONSE_FROM_CREDITOR_INSTITUTION* | An error occurred while generating an RT (aka a receipt). Specifically, the RT request is sent to creditor institution but this one responded with an invalid response from which is impossible to continue the analysis. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1402** | *RECEIPT_GENERATION_ERROR_RESPONSE_FROM_CREDITOR_INSTITUTION* | An error occurred while generating an RT (aka a receipt). Specifically, the RT request is sent to creditor institution but this one responded with an error response that explicit the occurred problem. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1403** | *RECEIPT_KO_NOT_SENT* | An error occurred while sending a negative RT (aka a KO receipt). So, no receipt can be sent lately to creditor institution and probably the process must be executed manually. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1404** | *RECEIPT_OK_NOT_SENT* | An error occurred while sending a positive RT (aka a OK receipt). So, no receipt can be sent lately to creditor institution and probably the process must be executed manually. For better understanding the cause, please use the Technical Support's APIs.\n**WIC-1405** | *RECEIPT_GENERATION_IDEMPOTENCY_LOCKED_BY_ANOTHER_PROCESS* | An error occurred while generating an RT (aka a receipt). Two or more generation processes are concurrently trying to execute the same operation on the same receipt but only one of them is currently 'authorized' to do so.\n**WIC-1406** | *RECEIPT_GENERATION_NOT_PROCESSABLE* | An error occurred while generating an RT (aka a receipt). The process of receipt generation cannot be started correctly because it is trying to lock the idempotency key that is already in a locked state. Probably the process is in execution by another thread.\n**WIC-1407** | *RECEIPT_GENERATION_ALREADY_PROCESSED* | An error occurred while generating an RT (aka a receipt). The process of receipt generation cannot be completed correctly because it is trying to unlock the idempotency key that is not in a locked state. Probably the process was already completed.\n**WIC-1408** | *RECEIPT_GENERATION_ANOMALY_ON_PROCESSING* | An error occurred while generating an RT (aka a receipt). The process of receipt generation cannot be completed correctly because there is a mismatch between the type of the cached receipt and the kind of request made for generate the same receipt. For example, the cached receipt is defined as negative paaInviaRT but the request was made to 'receipt/ok' endpoint. This is an anomaly that should never happens in a correct NMU flow execution but must be traced in case of error.\n**WIC-1409** | *RECEIPT_KO_NOT_GENERATED_BUT_MAYBE_RESCHEDULED* | An error occurred while generating a negative RT (aka a KO receipt). The receipt could be sent lately to creditor institution but for better understanding the cause, please use the Technical Support's APIs.\n**WIC-1410** | *RECEIPT_OK_NOT_GENERATED_BUT_MAYBE_RESCHEDULED* | An error occurred while generating a positive RT (aka a OK receipt). The receipt could be sent lately to creditor institution but for better understanding the cause, please use the Technical Support's APIs.\n**WIC-2000** | *PERSISTENCE_SAVING_RE_ERROR* | An error occurred wile trying to store a new event in the Registro Eventi storage. The error is somewhat related to a persistence problem of the used storage and in the majority of the cases is temporary (maybe a 429 HTTP code). This error currently blocks the entire flow because that can lead to untraceable requests. For better understanding the cause, please execute a search in the log provider (Application Insights, Kibana, etc).\n**WIC-2001** | *PERSISTENCE_RPT_NOT_FOUND* | An error occurred while trying to retrieve the RPT content saved in storage by WISP SOAP Converter. This can be related either with the use of a wrong sessionId or a missed persistence from WISP SOAP Converter, so it is better to analyze the entire flow using Technical Support's APIs. This block totally the conversion of the RPTs in GPD's payment positions, so the whole process is discarded.\n**WIC-2002** | *PERSISTENCE_RT_NOT_FOUND* | An error occurred while trying to retrieve the RT content saved in storage by WISP Converter. This can be related either with the use of a wrong identifier, a missed persistence or an expired object, so it is better to analyze the entire flow using Technical Support's APIs.\n**WIC-2003** | *PERSISTENCE_REQUESTID_CACHING_ERROR* | An error occurred while trying to retrieve data from internal cache. Specifically, the cached key, defined in format wisp_nav2iuv__
\n", "termsOfService": "https://www.pagopa.gov.it/", "title": "WISP Converter", - "version": "0.3.4" + "version": "0.3.4-1-PAGOPA-2104-new-api-recover-by-iuv" }, "servers": [ { diff --git a/openapi/openapi_redirect.json b/openapi/openapi_redirect.json index 6692df0e..b29a484f 100644 --- a/openapi/openapi_redirect.json +++ b/openapi/openapi_redirect.json @@ -2,7 +2,7 @@ "openapi": "3.0.1", "info": { "title": "WISP-Converter-redirect", - "version": "0.3.4" + "version": "0.3.4-1-PAGOPA-2104-new-api-recover-by-iuv" }, "servers": [ { diff --git a/pom.xml b/pom.xml index b42f0bd1..66002465 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ it.gov.pagopa wisp-converter - 0.3.4 + 0.3.4-1-PAGOPA-2104-new-api-recover-by-iuv pagoPA WISP Converter A service that permits to handle nodoInviaRPT and nodoInviaCarrelloRPT request from WISP, converting them in NMU payments. diff --git a/src/main/java/it/gov/pagopa/wispconverter/controller/RecoveryController.java b/src/main/java/it/gov/pagopa/wispconverter/controller/RecoveryController.java index 267a7ba2..e4e8392a 100644 --- a/src/main/java/it/gov/pagopa/wispconverter/controller/RecoveryController.java +++ b/src/main/java/it/gov/pagopa/wispconverter/controller/RecoveryController.java @@ -12,6 +12,7 @@ import it.gov.pagopa.wispconverter.service.RecoveryService; import it.gov.pagopa.wispconverter.util.Constants; import it.gov.pagopa.wispconverter.util.ErrorUtil; +import jakarta.validation.constraints.Pattern; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; @@ -57,4 +58,33 @@ public ResponseEntity recoverReceiptKOForCreditorInstit } } + + @Operation(summary = "Execute IUV reconciliation for certain creditor institution.", description = "Execute reconciliation of all IUVs for certain creditor institution, sending RT for close payment.", security = {@SecurityRequirement(name = "ApiKey")}, tags = {"Recovery"}) + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Started reconciling IUV with explicit RT send") + }) + @PostMapping(value = "/{creditor_institution}/rpt/{iuv}/receipt-ko") + public ResponseEntity recoverReceiptKOForCreditorInstitutionAndIUV(@Pattern(regexp = "[a-zA-Z0-9_-]{1,100}") @PathVariable("creditor_institution") String ci, + @Pattern(regexp = "[a-zA-Z0-9_-]{1,100}") @PathVariable("iuv") String iuv, + @Pattern(regexp = "[a-zA-Z0-9_-]{1,10}") @QueryParam("date_from") String dateFrom, + @Pattern(regexp = "[a-zA-Z0-9_-]{1,10}") @QueryParam("date_to") String dateTo) { + try { + log.info("Invoking API operation recoverReceiptKOForCreditorInstitution - args: {} {} {} {}", ci, iuv, dateFrom, dateTo); + + boolean recovered = recoveryService.recoverReceiptKO(ci, iuv, dateFrom, dateTo); + if(recovered) + return ResponseEntity.ok(String.format("RPT with CI %s and IUV %s recovered via API", ci, iuv)); + else return ResponseEntity.ok(String.format("RPT with CI %s and IUV %s could not be recovered via API", ci, iuv)); + } catch (Exception ex) { + String operationId = MDC.get(Constants.MDC_OPERATION_ID); + log.error(String.format("GenericException: operation-id=[%s]", operationId != null ? operationId : "n/a"), ex); + AppException appException = new AppException(ex, AppErrorCodeMessageEnum.ERROR, ex.getMessage()); + ErrorResponse errorResponse = errorUtil.forAppException(appException); + log.error("Failed API operation recoverReceiptKOForCreditorInstitution - error: {}", errorResponse); + throw ex; + } finally { + log.info("Successful API operation recoverReceiptKOForCreditorInstitution"); + } + } + } diff --git a/src/main/java/it/gov/pagopa/wispconverter/controller/model/RecoveryReceiptPaymentResponse.java b/src/main/java/it/gov/pagopa/wispconverter/controller/model/RecoveryReceiptPaymentResponse.java index a135ffe1..eaaf1a1f 100644 --- a/src/main/java/it/gov/pagopa/wispconverter/controller/model/RecoveryReceiptPaymentResponse.java +++ b/src/main/java/it/gov/pagopa/wispconverter/controller/model/RecoveryReceiptPaymentResponse.java @@ -13,4 +13,5 @@ public class RecoveryReceiptPaymentResponse { private String iuv; private String ccp; -} + private String ci; +} \ No newline at end of file diff --git a/src/main/java/it/gov/pagopa/wispconverter/service/RecoveryService.java b/src/main/java/it/gov/pagopa/wispconverter/service/RecoveryService.java index 21b53501..44683473 100644 --- a/src/main/java/it/gov/pagopa/wispconverter/service/RecoveryService.java +++ b/src/main/java/it/gov/pagopa/wispconverter/service/RecoveryService.java @@ -1,17 +1,14 @@ package it.gov.pagopa.wispconverter.service; -import it.gov.pagopa.wispconverter.controller.ReceiptController; import it.gov.pagopa.wispconverter.controller.model.RecoveryReceiptPaymentResponse; import it.gov.pagopa.wispconverter.controller.model.RecoveryReceiptResponse; import it.gov.pagopa.wispconverter.exception.AppErrorCodeMessageEnum; import it.gov.pagopa.wispconverter.exception.AppException; -import it.gov.pagopa.wispconverter.repository.CacheRepository; import it.gov.pagopa.wispconverter.repository.RTRepository; import it.gov.pagopa.wispconverter.repository.ReEventRepository; import it.gov.pagopa.wispconverter.repository.model.RTEntity; import it.gov.pagopa.wispconverter.repository.model.ReEventEntity; import it.gov.pagopa.wispconverter.repository.model.enumz.InternalStepStatus; -import it.gov.pagopa.wispconverter.service.model.ReceiptDto; import it.gov.pagopa.wispconverter.service.model.re.ReEventDto; import it.gov.pagopa.wispconverter.util.Constants; import it.gov.pagopa.wispconverter.util.MDCUtil; @@ -28,6 +25,7 @@ import java.time.format.DateTimeFormatter; import java.util.Comparator; import java.util.List; +import java.util.Set; import java.util.concurrent.CompletableFuture; @Service @@ -35,48 +33,66 @@ @RequiredArgsConstructor public class RecoveryService { - private static final String EVENT_TYPE_FOR_RECEIPTKO_SEARCH = "GENERATED_CACHE_ABOUT_RPT_FOR_RT_GENERATION"; + public static final String EVENT_TYPE_FOR_RECEIPTKO_SEARCH = "GENERATED_CACHE_ABOUT_RPT_FOR_RT_GENERATION"; + + private static final String RPT_ACCETTATA_NODO = "RPT_ACCETTATA_NODO"; + + public static final String RPT_PARCHEGGIATA_NODO = "RPT_PARCHEGGIATA_NODO"; private static final String STATUS_RT_SEND_SUCCESS = "RT_SEND_SUCCESS"; private static final String RECOVERY_VALID_START_DATE = "2024-09-03"; - private static final List BUSINESS_PROCESSES = List.of("receipt-ok", "receipt-ko", "ecommerce-hang-timeout-trigger"); - - private final ReceiptController receiptController; + private final ReceiptService receiptService; private final RTRepository rtRepository; private final ReEventRepository reEventRepository; - private final CacheRepository cacheRepository; - private final ReService reService; - @Value("${wisp-converter.cached-requestid-mapping.ttl.minutes}") - private Long requestIDMappingTTL; + private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + private static final String DATE_FORMAT_DAY = "yyyy-MM-dd"; + + @Value("${wisp-converter.cached-requestid-mapping.ttl.minutes:1440}") + public Long requestIDMappingTTL; @Value("${wisp-converter.recovery.receipt-generation.wait-time.minutes:60}") - private Long receiptGenerationWaitTime; + public Long receiptGenerationWaitTime; + + public boolean recoverReceiptKO(String creditorInstitution, String iuv, String dateFrom, String dateTo) { + checkDateValidity(dateFrom, dateTo); + List reEvents = reEventRepository.findByIuvAndOrganizationId(dateFrom, dateTo, iuv, creditorInstitution) + .stream() + .sorted(Comparator.comparing(ReEventEntity::getInsertedTimestamp)) + .toList(); + + Set interruptStatusSet = getWISPInterruptStatusSet(); + + if(!reEvents.isEmpty()) { + ReEventEntity lastEvent = reEvents.get(0); + String status = lastEvent.getStatus(); + if(status != null && interruptStatusSet.contains(status)) { + this.recoverReceiptKO(creditorInstitution, iuv, lastEvent.getSessionId(), lastEvent.getCcp(), dateFrom, dateTo); + return true; + } + } - public RecoveryReceiptResponse recoverReceiptKOForCreditorInstitution(String creditorInstitution, String dateFrom, String dateTo) { + return false; + } + public RecoveryReceiptResponse recoverReceiptKOForCreditorInstitution(String creditorInstitution, String dateFrom, String dateTo) { MDCUtil.setSessionDataInfo("recovery-receipt-ko"); - LocalDate lowerLimit = LocalDate.parse(RECOVERY_VALID_START_DATE, DateTimeFormatter.ISO_LOCAL_DATE); - if (LocalDate.parse(dateFrom, DateTimeFormatter.ISO_LOCAL_DATE).isBefore(lowerLimit)) { - throw new AppException(AppErrorCodeMessageEnum.ERROR, String.format("The lower bound cannot be lower than [%s]", RECOVERY_VALID_START_DATE)); - } - LocalDate now = LocalDate.now(); - LocalDate parse = LocalDate.parse(dateTo, DateTimeFormatter.ISO_LOCAL_DATE); - if (parse.isAfter(now)) { - throw new AppException(AppErrorCodeMessageEnum.ERROR, String.format("The upper bound cannot be higher than [%s]", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))); - } + checkDateValidity(dateFrom, dateTo); + LocalDate parse = LocalDate.parse(dateTo, DateTimeFormatter.ISO_LOCAL_DATE); String dateToRefactored; - if (now.isEqual(parse)) { + + if (LocalDate.now().isEqual(parse)) { ZonedDateTime nowMinusMinutes = ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(receiptGenerationWaitTime); - dateToRefactored = nowMinusMinutes.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + dateToRefactored = nowMinusMinutes.format(DateTimeFormatter.ofPattern(DATE_FORMAT)); log.info("Upper bound forced to {}", dateToRefactored); } else { dateToRefactored = dateTo + " 23:59:59"; @@ -85,12 +101,13 @@ public RecoveryReceiptResponse recoverReceiptKOForCreditorInstitution(String cre List receiptRTs = rtRepository.findByOrganizationId(creditorInstitution, dateFrom, dateToRefactored); List paymentsToReconcile = receiptRTs.stream().map(entity -> RecoveryReceiptPaymentResponse.builder() - .iuv(entity.getIuv()) - .ccp(entity.getCcp()) - .build()) - .toList(); + .iuv(entity.getIuv()) + .ccp(entity.getCcp()) + .ci(entity.getIdDominio()) + .build()) + .toList(); - CompletableFuture executeRecovery = recoverReceiptKOAsync(dateFrom, dateTo, creditorInstitution, paymentsToReconcile); + CompletableFuture executeRecovery = recoverReceiptKOAsync(dateFrom, dateTo, paymentsToReconcile); executeRecovery .thenAccept(value -> log.debug("Reconciliation for creditor institution [{}] in date range [{}-{}] completed!", creditorInstitution, dateFrom, dateTo)) .exceptionally(e -> { @@ -99,68 +116,82 @@ public RecoveryReceiptResponse recoverReceiptKOForCreditorInstitution(String cre }); return RecoveryReceiptResponse.builder() - .payments(paymentsToReconcile) - .build(); + .payments(paymentsToReconcile) + .build(); } - private CompletableFuture recoverReceiptKOAsync(String dateFrom, String dateTo, String creditorInstitution, List paymentsToReconcile) { + private CompletableFuture recoverReceiptKOAsync(String dateFrom, String dateTo, List paymentsToReconcile) { + return CompletableFuture.supplyAsync(() -> recoverReceiptKOByRecoveryPayment(dateFrom, dateTo, paymentsToReconcile)); + } - return CompletableFuture.supplyAsync(() -> { + private boolean recoverReceiptKOByRecoveryPayment(String dateFrom, String dateTo, List paymentsToReconcile) { - for (RecoveryReceiptPaymentResponse payment : paymentsToReconcile) { + for (RecoveryReceiptPaymentResponse payment : paymentsToReconcile) { + String iuv = payment.getIuv(); + String ccp = payment.getCcp(); + String ci = payment.getCi(); - String iuv = payment.getIuv(); - String ccp = payment.getCcp(); + try { + List reEvents = reEventRepository.findByIuvAndOrganizationId(dateFrom, dateTo, iuv, ci); - try { - List reEvents = reEventRepository.findByIuvAndOrganizationId(dateFrom, dateTo, iuv, creditorInstitution); + List filteredEvents = reEvents.stream() + .filter(event -> EVENT_TYPE_FOR_RECEIPTKO_SEARCH.equals(event.getStatus())) + .filter(event -> ccp.equals(event.getCcp())) + .sorted(Comparator.comparing(ReEventEntity::getInsertedTimestamp)) + .toList(); - List filteredEvents = reEvents.stream() - .filter(event -> EVENT_TYPE_FOR_RECEIPTKO_SEARCH.equals(event.getStatus())) - .filter(event -> ccp.equals(event.getCcp())) - .sorted(Comparator.comparing(ReEventEntity::getInsertedTimestamp)) - .toList(); + int numberOfEvents = filteredEvents.size(); + if (numberOfEvents > 0) { + ReEventEntity event = filteredEvents.get(numberOfEvents - 1); + String sessionId = event.getSessionId(); - int numberOfEvents = filteredEvents.size(); - if (numberOfEvents > 0) { + log.info("[RECOVERY-MISSING-RT] Recovery with receipt-ko for ci = {}, iuv = {}, ccp = {}, sessionId = {}", ci, iuv, ccp, sessionId); + this.recoverReceiptKO(ci, iuv, ccp, sessionId, dateFrom, dateTo); + } + } catch (Exception e) { + generateRE(Constants.PAA_INVIA_RT, "Failure", InternalStepStatus.RT_END_RECONCILIATION_PROCESS, ci, iuv, ccp, null); + throw new AppException(e, AppErrorCodeMessageEnum.ERROR, e.getMessage()); + } + } - ReEventEntity event = filteredEvents.get(numberOfEvents - 1); - String noticeNumber = event.getNoticeNumber(); - String sessionId = event.getSessionId(); + return true; + } - // search by sessionId, then filter by status=RT_SEND_SUCCESS. If there is zero, then proceed - List reEventsRT = reEventRepository.findBySessionIdAndStatus(dateFrom, dateTo, sessionId, STATUS_RT_SEND_SUCCESS); + // check if there is a successful RT submission, if there isn't prepare cached data and send receipt-ko + public void recoverReceiptKO(String ci, String iuv, String ccp, String sessionId, String dateFrom, String dateTo) { + // search by sessionId, then filter by status=RT_SEND_SUCCESS. If there is zero, then proceed + List reEventsRT = reEventRepository.findBySessionIdAndStatus(dateFrom, dateTo, sessionId, STATUS_RT_SEND_SUCCESS); - if (reEventsRT.isEmpty()) { - String navToIuvMapping = String.format(DecouplerService.MAP_CACHING_KEY_TEMPLATE, creditorInstitution, noticeNumber); - String iuvToSessionIdMapping = String.format(DecouplerService.CACHING_KEY_TEMPLATE, creditorInstitution, iuv); - this.cacheRepository.insert(navToIuvMapping, iuvToSessionIdMapping, this.requestIDMappingTTL); - this.cacheRepository.insert(iuvToSessionIdMapping, sessionId, this.requestIDMappingTTL); + if (reEventsRT.isEmpty()) { + MDC.put(Constants.MDC_BUSINESS_PROCESS, "receipt-ko"); - MDC.put(Constants.MDC_BUSINESS_PROCESS, "receipt-ko"); - generateRE(Constants.PAA_INVIA_RT, null, InternalStepStatus.RT_START_RECONCILIATION_PROCESS, creditorInstitution, iuv, noticeNumber, ccp, sessionId); - String receiptKoRequest = ReceiptDto.builder() - .fiscalCode(creditorInstitution) - .noticeNumber(noticeNumber) - .build() - .toString(); - this.receiptController.receiptKo(receiptKoRequest); - generateRE(Constants.PAA_INVIA_RT, "Success", InternalStepStatus.RT_END_RECONCILIATION_PROCESS, creditorInstitution, iuv, noticeNumber, ccp, sessionId); - MDC.remove(Constants.MDC_BUSINESS_PROCESS); - } - } + generateRE(Constants.PAA_INVIA_RT, null, InternalStepStatus.RT_START_RECONCILIATION_PROCESS, ci, iuv, ccp, sessionId); - } catch (Exception e) { - generateRE(Constants.PAA_INVIA_RT, "Failure", InternalStepStatus.RT_END_RECONCILIATION_PROCESS, creditorInstitution, iuv, null, ccp, null); - throw new AppException(e, AppErrorCodeMessageEnum.ERROR, e.getMessage()); - } + try { + this.receiptService.sendRTKoFromSessionId(sessionId, InternalStepStatus.NEGATIVE_RT_TRY_TO_SEND_TO_CREDITOR_INSTITUTION); + } catch (Exception e) { + generateRE(Constants.PAA_INVIA_RT, "Failure", InternalStepStatus.RT_END_RECONCILIATION_PROCESS, ci, iuv, ccp, sessionId); + throw new AppException(e, AppErrorCodeMessageEnum.ERROR, e.getMessage()); } + generateRE(Constants.PAA_INVIA_RT, "Success", InternalStepStatus.RT_END_RECONCILIATION_PROCESS, ci, iuv, ccp, sessionId); + MDC.remove(Constants.MDC_BUSINESS_PROCESS); + } + } - return true; - }); + private void checkDateValidity(String dateFrom, String dateTo) { + LocalDate lowerLimit = LocalDate.parse(RECOVERY_VALID_START_DATE, DateTimeFormatter.ISO_LOCAL_DATE); + if (LocalDate.parse(dateFrom, DateTimeFormatter.ISO_LOCAL_DATE).isBefore(lowerLimit)) { + throw new AppException(AppErrorCodeMessageEnum.ERROR, String.format("The lower bound cannot be lower than [%s]", RECOVERY_VALID_START_DATE)); + } + + LocalDate today = LocalDate.now(); + LocalDate parse = LocalDate.parse(dateTo, DateTimeFormatter.ISO_LOCAL_DATE); + if (parse.isAfter(today)) { + throw new AppException(AppErrorCodeMessageEnum.ERROR, String.format("The upper bound cannot be higher than [%s]", today.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DAY)))); + } } - private void generateRE(String primitive, String operationStatus, InternalStepStatus status, String domainId, String iuv, String noticeNumber, String ccp, String sessionId) { + private void generateRE(String primitive, String operationStatus, InternalStepStatus status, String domainId, String iuv, String ccp, String sessionId) { // setting data in MDC for next use ReEventDto reEvent = ReUtil.getREBuilder() @@ -171,8 +202,21 @@ private void generateRE(String primitive, String operationStatus, InternalStepSt .domainId(domainId) .iuv(iuv) .ccp(ccp) - .noticeNumber(noticeNumber) + .noticeNumber(null) .build(); reService.addRe(reEvent); } -} + + private static Set getWISPInterruptStatusSet() { + return Set.of( + RPT_ACCETTATA_NODO, + RPT_PARCHEGGIATA_NODO, + "GENERATED_NAV_FOR_NEW_PAYMENT_POSITION", + "CREATED_NEW_PAYMENT_POSITION_IN_GPD", + "GENERATED_CACHE_ABOUT_RPT_FOR_DECOUPLER", + EVENT_TYPE_FOR_RECEIPTKO_SEARCH, + "SAVED_RPT_IN_CART_RECEIVED_REDIRECT_URL_FROM_CHECKOUT", + "GENERATED_CACHE_ABOUT_RPT_FOR_CARTSESSION_CACHING" + ); + } +} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/wispconverter/endpoint/RecoveryTest.java b/src/test/java/it/gov/pagopa/wispconverter/endpoint/RecoveryTest.java index df2fb21e..b9f49d85 100644 --- a/src/test/java/it/gov/pagopa/wispconverter/endpoint/RecoveryTest.java +++ b/src/test/java/it/gov/pagopa/wispconverter/endpoint/RecoveryTest.java @@ -71,4 +71,37 @@ void testRecoverReceiptKOForCreditorInstitution_500() throws Exception { Mockito.verify(recoveryService, times(1)).recoverReceiptKOForCreditorInstitution(eq(ci), any(), any()); } + + @Test + void testRecoverReceiptKOForCreditorInstitutionAndIUV() throws Exception { + String ci = "77777777777"; + String iuv = "00000000000000000"; + String dateFrom = "2024-09-03"; + String dateTo = "2024-09-09"; + + mockMvc.perform(post("/recovery/{ci}/rpt/{iuv}/receipt-ko", ci, iuv) + .queryParam("date_from", dateFrom) + .queryParam("date_to", dateTo)) + .andExpect(status().isOk()); + + Mockito.verify(recoveryService, times(1)).recoverReceiptKO(eq(ci), eq(iuv), any(), any()); + } + + @Test + void testRecoverReceiptKOForCreditorInstitutionAndIUV_500() throws Exception { + String ci = "77777777777"; + String iuv = "00000000000000000"; + String dateFrom = "2024-09-03"; + String dateTo = "2024-09-09"; + + Mockito.when(recoveryService.recoverReceiptKO(anyString(), anyString(), any(), any())) + .thenThrow(new RuntimeException("Test exception")); + + mockMvc.perform(post("/recovery/{ci}/rpt/{iuv}/receipt-ko", ci, iuv) + .queryParam("date_from", dateFrom) + .queryParam("date_to", dateTo)) + .andExpect(status().isInternalServerError()); + + Mockito.verify(recoveryService, times(1)).recoverReceiptKO(eq(ci), eq(iuv), any(), any()); + } } diff --git a/src/test/java/it/gov/pagopa/wispconverter/repository/CacheRepositoryTest.java b/src/test/java/it/gov/pagopa/wispconverter/repository/CacheRepositoryTest.java index dbdd0279..40b707f0 100644 --- a/src/test/java/it/gov/pagopa/wispconverter/repository/CacheRepositoryTest.java +++ b/src/test/java/it/gov/pagopa/wispconverter/repository/CacheRepositoryTest.java @@ -8,7 +8,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.redis.core.RedisTemplate; -import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/src/test/java/it/gov/pagopa/wispconverter/service/RecoveryServiceTest.java b/src/test/java/it/gov/pagopa/wispconverter/service/RecoveryServiceTest.java new file mode 100644 index 00000000..d278df7a --- /dev/null +++ b/src/test/java/it/gov/pagopa/wispconverter/service/RecoveryServiceTest.java @@ -0,0 +1,218 @@ +package it.gov.pagopa.wispconverter.service; + +import it.gov.pagopa.wispconverter.controller.model.RecoveryReceiptResponse; +import it.gov.pagopa.wispconverter.exception.AppException; +import it.gov.pagopa.wispconverter.repository.RTRepository; +import it.gov.pagopa.wispconverter.repository.ReEventRepository; +import it.gov.pagopa.wispconverter.repository.model.RTEntity; +import it.gov.pagopa.wispconverter.repository.model.ReEventEntity; +import it.gov.pagopa.wispconverter.service.model.re.ReEventDto; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.*; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import static it.gov.pagopa.wispconverter.service.RecoveryService.EVENT_TYPE_FOR_RECEIPTKO_SEARCH; +import static it.gov.pagopa.wispconverter.service.RecoveryService.RPT_PARCHEGGIATA_NODO; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +public class RecoveryServiceTest { + + @Mock + private RTRepository rtRepository; + + @Mock + private ReEventRepository reRepository; + + @Mock + private ReceiptService receiptService; + + @Mock + private ReService reService; + + @InjectMocks + private RecoveryService recoveryService; + + @BeforeEach + public void setup() { + MockitoAnnotations.openMocks(this); + recoveryService.receiptGenerationWaitTime = 60L; + recoveryService.requestIDMappingTTL = 1440L; + } + + @Test + void testRecoverReceiptKO() { + // Arrange + String dateFrom = "2024-09-05"; + String dateTo = "2024-09-09"; + String ci = "ci"; + String iuv = "iuv"; + String ccp = "cpp"; + String session = "sessionId"; + List rtSuccessReEventEntity = List.of(); + + when(reRepository.findBySessionIdAndStatus(anyString(), anyString(), anyString(), anyString())).thenReturn(rtSuccessReEventEntity); + doNothing().when(receiptService) + .sendRTKoFromSessionId(anyString(), any()); + doNothing().when(reService).addRe(any(ReEventDto.class)); + + // Act + recoveryService.recoverReceiptKO(ci, iuv, ccp, session, dateFrom, dateTo); + + // Assert + verify(reRepository, times(1)).findBySessionIdAndStatus(anyString(), anyString(), anyString(), anyString()); + } + + @Test + void testRecoverReceiptKOForCreditorInstitution_Success_Empty() { + // Arrange + String creditorInstitution = "77777777777"; + String dateFrom = "2024-09-05"; + String dateTo = "2024-09-09"; + List mockRTEntities = List.of(); + + when(rtRepository.findByOrganizationId(anyString(), anyString(), anyString())).thenReturn(mockRTEntities); + + // Act + RecoveryReceiptResponse response = recoveryService.recoverReceiptKOForCreditorInstitution(creditorInstitution, dateFrom, dateTo); + + // Assert + assertNotNull(response); + assertEquals(0, response.getPayments().size()); + } + + @Test + void testRecoverReceiptKOForCreditorInstitution_Success_NotEmpty() { + // Arrange + String creditorInstitution = "77777777777"; + String dateFrom = "2024-09-05"; + String dateTo = "2024-09-09"; + List mockRTEntities = List.of(RTEntity.builder() + .idDominio("ci") + .iuv("iuv") + .ccp("ccp") + .build()); + List mockReEntities = List.of(ReEventEntity.builder() + .status(EVENT_TYPE_FOR_RECEIPTKO_SEARCH) + .ccp("ccp") + .sessionId("sessionId") + .build()); + List rtSuccessReEventEntity = List.of(); + + when(rtRepository.findByOrganizationId(anyString(), anyString(), anyString())).thenReturn(mockRTEntities); + when(reRepository.findByIuvAndOrganizationId(anyString(), anyString(), anyString(), anyString())).thenReturn(mockReEntities); + when(reRepository.findBySessionIdAndStatus(anyString(), anyString(), anyString(), anyString())).thenReturn(rtSuccessReEventEntity); + doNothing().when(receiptService) + .sendRTKoFromSessionId(anyString(), any()); + doNothing().when(reService).addRe(any(ReEventDto.class)); + + // Act + RecoveryReceiptResponse response = recoveryService.recoverReceiptKOForCreditorInstitution(creditorInstitution, dateFrom, dateTo); + + // Assert + assertNotNull(response); + assertEquals(1, response.getPayments().size()); + } + + @Test + void testRecoverReceiptKOForCreditorInstitution_Success_Today() { + // Arrange + String creditorInstitution = "77777777777"; + String dateFrom = "2024-09-05"; + String dateTo = LocalDate.now().toString(); + List mockRTEntities = List.of(); + + when(rtRepository.findByOrganizationId(anyString(), anyString(), anyString())).thenReturn(mockRTEntities); + + // Act + RecoveryReceiptResponse response = recoveryService.recoverReceiptKOForCreditorInstitution(creditorInstitution, dateFrom, dateTo); + + // Assert + assertNotNull(response); + assertEquals(0, response.getPayments().size()); + } + + @Test + void testRecoverReceiptKOForCreditorInstitution_LowerBoundFailure() { + // Arrange + String creditorInstitution = "77777777777"; + String dateFrom = "2024-09-01"; // Date earlier than valid start date + String dateTo = "2024-09-09"; + + // Act and Assert + AppException exception = assertThrows( + AppException.class, () -> recoveryService.recoverReceiptKOForCreditorInstitution(creditorInstitution, dateFrom, dateTo) + ); + assertEquals("The lower bound cannot be lower than [2024-09-03]", exception.getMessage()); + } + + @Test + void testRecoverReceiptKOForCreditorInstitution_UpperBoundFailure() { + // Arrange + String creditorInstitution = "77777777777"; + String dateFrom = "2024-09-05"; + String dateTo = LocalDate.now().plusDays(1).toString(); // Future date, should fail + + // Act and Assert + AppException exception = assertThrows( + AppException.class, () -> recoveryService.recoverReceiptKOForCreditorInstitution(creditorInstitution, dateFrom, dateTo) + ); + String expectedMessage = String.format("The upper bound cannot be higher than [%s]", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); + assertEquals(expectedMessage, exception.getMessage()); + } + + @Test + void testRecoverReceiptKOByIUV() { + // Arrange + String dateFrom = "2024-09-05"; + String dateTo = "2024-09-09"; + String ci = "ci"; + String iuv = "iuv"; + List rtSuccessReEventEntity = List.of(); + + when(reRepository.findByIuvAndOrganizationId(anyString(), anyString(), anyString(), anyString())).thenReturn(rtSuccessReEventEntity); + doNothing().when(receiptService).sendRTKoFromSessionId(anyString(), any()); + doNothing().when(reService).addRe(any(ReEventDto.class)); + + // Act + recoveryService.recoverReceiptKO(ci, iuv, dateFrom, dateTo); + + // Assert + verify(reRepository, times(1)).findByIuvAndOrganizationId(anyString(), anyString(), anyString(), anyString()); + } + + @Test + void testRecoverReceiptKOByIUV_NotEmpty() { + // Arrange + String dateFrom = "2024-09-05"; + String dateTo = "2024-09-09"; + String ci = "ci"; + String iuv = "iuv"; + List rtSuccessReEventEntity = List.of(); + List interruptedRPTEvents = List.of(ReEventEntity.builder() + .insertedTimestamp(Instant.now()) + .status(RPT_PARCHEGGIATA_NODO) + .sessionId("sessionId") + .ccp("ccp") + .build()); + + when(reRepository.findByIuvAndOrganizationId(anyString(), anyString(), anyString(), anyString())).thenReturn(interruptedRPTEvents); + doNothing().when(receiptService).sendRTKoFromSessionId(anyString(), any()); + doNothing().when(reService).addRe(any(ReEventDto.class)); + when(reRepository.findBySessionIdAndStatus(anyString(), anyString(), anyString(), anyString())).thenReturn(rtSuccessReEventEntity); + doNothing().when(receiptService).sendRTKoFromSessionId(anyString(), any()); + doNothing().when(reService).addRe(any(ReEventDto.class)); + + // Act + recoveryService.recoverReceiptKO(ci, iuv, dateFrom, dateTo); + + // Assert + verify(reRepository, times(1)).findByIuvAndOrganizationId(anyString(), anyString(), anyString(), anyString()); + } +} \ No newline at end of file