From d1c872aae61bac61c18167f5eff574834369e842 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 21 Jun 2023 11:45:10 +0200 Subject: [PATCH 01/29] wip --- .gitignore | 3 + pom.xml | 116 ++++++++++---- .../nodetsworker/exceptions/AppError.java | 26 ++++ .../nodetsworker/exceptions/AppException.java | 23 +++ .../models/AppInfo.java | 2 +- .../models/BasePaymentAttemptInfo.java | 25 +++ .../nodetsworker/models/BasePaymentInfo.java | 29 ++++ .../nodetsworker/models/DateRequest.java | 21 +++ .../models/PaymentAttemptInfo.java | 33 ++++ .../nodetsworker/models/PaymentInfo.java | 21 +++ .../nodetsworker/models/ProblemJson.java | 38 +++++ .../nodetsworker/models/RPTAttemptInfo.java | 29 ++++ .../models/TransactionResponse.java | 20 +++ .../repository/CosmosBizEventClient.java | 36 +++++ .../nodetsworker/repository/Creditor.java | 14 ++ .../repository/DebtorPosition.java | 16 ++ .../nodetsworker/repository/EventEntity.java | 57 +++++++ .../repository/NegativeBizEvent.java | 37 +++++ .../repository/NegativePaymentInfo.java | 21 +++ .../repository/NegativeTransfer.java | 19 +++ .../nodetsworker/repository/PaymentInfo.java | 29 ++++ .../repository/PositiveBizEvent.java | 41 +++++ .../pagopa/nodetsworker/repository/Psp.java | 16 ++ .../nodetsworker/repository/Subject.java | 19 +++ .../nodetsworker/repository/Transfer.java | 19 +++ .../resources/Generic.java | 22 +-- .../resources/WorkerResource.java | 114 ++++++++++++++ .../resources/model/Metadata.java | 23 +++ .../response/FindEventsResponse.java | 25 +++ .../nodetsworker/service/WorkerService.java | 143 ++++++++++++++++++ .../nodetsworker/service/dto/EventDto.java | 44 ++++++ .../service/mapper/EventMapper.java | 19 +++ src/main/resources/application.properties | 126 +++++++++++---- .../resources/GenericTest.java | 4 +- 34 files changed, 1150 insertions(+), 80 deletions(-) create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java rename src/main/java/it/gov/pagopa/{quarkustemplate => nodetsworker}/models/AppInfo.java (87%) create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/DebtorPosition.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java rename src/main/java/it/gov/pagopa/{quarkustemplate => nodetsworker}/resources/Generic.java (72%) create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/model/Metadata.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java rename src/test/java/it/gov/pagopa/{quarkustemplate => nodetsworker}/resources/GenericTest.java (81%) diff --git a/.gitignore b/.gitignore index a68cd72..80d8684 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +#apps +.idea + # Compiled class file *.class diff --git a/pom.xml b/pom.xml index 37d7ec4..b1293e3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,23 +1,23 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - it.gov.pagopa - quarkus-template - 0.0.1 - + node-techical-support-worker + 1.0.0-SNAPSHOT - 3.8.1 - 11 + 3.11.0 + 1.18.26 + 17 + 1.5.3.Final UTF-8 UTF-8 quarkus-bom io.quarkus.platform - 2.13.0.Final - 3.0.0-M7 + 3.0.1.Final + true + 3.0.0 - @@ -36,37 +36,40 @@ io.quarkus - quarkus-resteasy-reactive + quarkus-logging-json io.quarkus - quarkus-smallrye-openapi + quarkus-micrometer-registry-prometheus - org.projectlombok - lombok - 1.18.24 - provided + io.quarkus + quarkus-smallrye-health io.quarkus - quarkus-resteasy-reactive-jackson + quarkus-opentelemetry io.quarkus - quarkus-hibernate-orm + quarkus-smallrye-openapi io.quarkus - quarkus-spring-data-jpa + quarkus-hibernate-validator io.quarkus - quarkus-jdbc-h2 + quarkus-rest-client-reactive-jackson io.quarkus - quarkus-hibernate-validator + quarkus-resteasy-reactive-jackson + + + io.quarkiverse.openapi.generator + quarkus-openapi-generator + 2.2.2 io.quarkus @@ -74,35 +77,60 @@ test - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - 2.13.1 + io.rest-assured + rest-assured + test + + + io.quarkus + quarkus-junit5-mockito + test + + + org.projectlombok + lombok + ${lombok.version} + provided org.mapstruct mapstruct - 1.3.1.Final + ${org.mapstruct.version} org.mapstruct mapstruct-processor - 1.3.1.Final + ${org.mapstruct.version} provided - org.mockito - mockito-core - 2.10.0 - test + io.quarkus + quarkus-mongodb-panache + + + com.azure + azure-cosmos + 4.46.0 io.quarkus - quarkus-junit5-mockito + quarkus-scheduler + + + io.quarkiverse.mockserver + quarkus-mockserver-test + 1.0.0 + + + org.testcontainers + junit-jupiter + 1.16.0 test - io.rest-assured - rest-assured + org.testcontainers + mongodb + 1.18.1 test @@ -130,6 +158,28 @@ -parameters + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.projectlombok + lombok-mapstruct-binding + 0.2.0 + + + io.quarkus + quarkus-panache-common + ${quarkus.platform.version} + + diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java new file mode 100644 index 0000000..92442bd --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java @@ -0,0 +1,26 @@ +package it.gov.pagopa.nodetsworker.exceptions; + +import lombok.Getter; + + +@Getter +public enum AppError { + + POSITION_SERVICE_NOT_FOUND(404, "Not found", "Position service with organization %s and %s not found"), + POSITION_SERVICE_DATE_BAD_REQUEST(400, "Bad Request", "%s"), + WORKER_CONFLICT(409, "Conflict", "A worker with the nodeId %s already exists"), + INTERNAL_ERROR(500, "Internal error", "Processing error"), + UNKNOWN(520, null, null); + + + public final int httpStatus; + public final String title; + public final String details; + + + AppError(int httpStatus, String title, String details) { + this.httpStatus = httpStatus; + this.title = title; + this.details = details; + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java new file mode 100644 index 0000000..040b4e5 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java @@ -0,0 +1,23 @@ +package it.gov.pagopa.nodetsworker.exceptions; + +import lombok.Getter; + +import jakarta.validation.constraints.NotNull; + +@Getter +public class AppException extends RuntimeException{ + + String title; + + int httpStatus; + + public AppException(@NotNull AppError appError, Object... args) { + super(formatDetails(appError, args)); + this.httpStatus = appError.httpStatus; + this.title = appError.title; + } + + private static String formatDetails(AppError appError, Object[] args) { + return String.format(appError.details, args); + } +} diff --git a/src/main/java/it/gov/pagopa/quarkustemplate/models/AppInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/AppInfo.java similarity index 87% rename from src/main/java/it/gov/pagopa/quarkustemplate/models/AppInfo.java rename to src/main/java/it/gov/pagopa/nodetsworker/models/AppInfo.java index 7eb4d62..2153efe 100644 --- a/src/main/java/it/gov/pagopa/quarkustemplate/models/AppInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/AppInfo.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.quarkustemplate.models; +package it.gov.pagopa.nodetsworker.models; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java new file mode 100644 index 0000000..57279a0 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java @@ -0,0 +1,25 @@ +package it.gov.pagopa.nodetsworker.models; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class BasePaymentAttemptInfo extends BasePaymentInfo { + + private String brokerOrganizationId; + private String stationId; + private String paymentMethod; + private Double amount; + private Boolean flagIO; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java new file mode 100644 index 0000000..2c3dac0 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java @@ -0,0 +1,29 @@ +package it.gov.pagopa.nodetsworker.models; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +import java.time.LocalDateTime; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class BasePaymentInfo { + + private String organizationFiscalCode; + private String noticeNumber; + private String pspId; + private String brokerPspId; + private String channelId; + private String outcome; + private String status; + private LocalDateTime insertedTimestamp; + private LocalDateTime updatedTimestamp; + private Boolean isOldPaymentModel; + private String nodeId; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java b/src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java new file mode 100644 index 0000000..8dc3ad0 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java @@ -0,0 +1,21 @@ +package it.gov.pagopa.nodetsworker.models; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.LocalDate; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class DateRequest { + + private LocalDate from; + private LocalDate to; + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java new file mode 100644 index 0000000..c989406 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java @@ -0,0 +1,33 @@ +package it.gov.pagopa.nodetsworker.models; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +import java.time.LocalDate; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class PaymentAttemptInfo extends BasePaymentAttemptInfo { + + private String paymentToken; + private Boolean isOldPaymentModel = false; + + private Boolean pmReceipt; + private String paymentMethod; + private String paymentChannel; + private Boolean flagPayPal; + private Long stationVersion; + private Long fee; + private Long feeSpo; + private Long feeOrganization; + private String bundleId; + private String bundleOrganizationId; + private LocalDate applicationDate; + private LocalDate transferDate; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java new file mode 100644 index 0000000..209042d --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java @@ -0,0 +1,21 @@ +package it.gov.pagopa.nodetsworker.models; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +import java.time.LocalDateTime; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class PaymentInfo extends BasePaymentInfo { + + private String paymentToken; // for new payment model is payment token and for old payment model is ccp + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java b/src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java new file mode 100644 index 0000000..ac6543d --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java @@ -0,0 +1,38 @@ +package it.gov.pagopa.nodetsworker.models; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; +import org.eclipse.microprofile.openapi.annotations.media.Schema; + +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; + +@Data +@Builder(toBuilder = true) +@NoArgsConstructor +@AllArgsConstructor +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class ProblemJson { + + @JsonProperty("title") + @Schema(description = "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable") + private String title; + + @JsonProperty("status") + @Schema(example = "200", description = "The HTTP status code generated by the origin server for this occurrence of the problem.") + @Min(100) + @Max(600) + private Integer status; + + @JsonProperty("details") + @Schema(example = "There was an error processing the request", description = "A human readable explanation specific to this occurrence of the problem.") + private String details; + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java new file mode 100644 index 0000000..79da60a --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java @@ -0,0 +1,29 @@ +package it.gov.pagopa.nodetsworker.models; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class RPTAttemptInfo extends BasePaymentAttemptInfo { + + private String ccp; + private Long numberOfPayments; + private Boolean retriedRPT; + private Boolean isOldPaymentModel = true; + private Boolean wispInitialization; + private Boolean pmReceipt; + @JsonProperty("iuv") + private String noticeNumber; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java new file mode 100644 index 0000000..ccb95d8 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java @@ -0,0 +1,20 @@ +package it.gov.pagopa.nodetsworker.models; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +import java.time.LocalDate; +import java.util.List; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class TransactionResponse { + + private LocalDate dateFrom; + private LocalDate dateTo; + @JsonProperty("data") + private List payments; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java new file mode 100644 index 0000000..61d9d5b --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -0,0 +1,36 @@ +package it.gov.pagopa.nodetsworker.repository; + +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosContainer; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.SqlQuerySpec; +import com.azure.cosmos.util.CosmosPagedIterable; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; + +@ApplicationScoped +public class CosmosBizEventClient { + + @ConfigProperty(name = "biz.endpoint") + private String endpoint; + + @ConfigProperty(name = "biz.key") + private String key; + + @Inject + Logger log; + + + + public CosmosPagedIterable query(SqlQuerySpec query){ + log.info("executing query:"+query.getQueryText()); + CosmosClient client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); + CosmosContainer container = client.getDatabase("db").getContainer("biz-events"); + return container.queryItems(query, new CosmosQueryRequestOptions(), PositiveBizEvent.class); + } + + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java new file mode 100644 index 0000000..713df9e --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java @@ -0,0 +1,14 @@ +package it.gov.pagopa.nodetsworker.repository; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +class Creditor { + private String idPA; + private String idBrokerPA; + private String idStation; + private String companyName; + private String officeName; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/DebtorPosition.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/DebtorPosition.java new file mode 100644 index 0000000..b3600fd --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/DebtorPosition.java @@ -0,0 +1,16 @@ +package it.gov.pagopa.nodetsworker.repository; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class DebtorPosition { + private String modelType; + private String noticeNumber; + private String iuv; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java new file mode 100644 index 0000000..2a098f8 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java @@ -0,0 +1,57 @@ +package it.gov.pagopa.nodetsworker.repository; + +import io.quarkus.mongodb.panache.PanacheMongoEntity; +import io.quarkus.mongodb.panache.PanacheQuery; +import io.quarkus.mongodb.panache.common.MongoEntity; +import java.time.LocalDate; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@MongoEntity(collection = "events", clientName = "events") +public class EventEntity extends PanacheMongoEntity { + + private String insertedTimestamp; + private String componente; + private String categoriaEvento; + private String sottoTipoEvento; + private String idDominio; + private String iuv; + private String ccp; + private String psp; + private String tipoVersamento; + private String tipoEvento; + private String fruitore; + private String erogatore; + private String stazione; + private String canale; + private String parametriSpecificiInterfaccia; + private String esito; + private String sessionId; + private String status; + private String payload; + private String info; + private String businessProcess; + private String fruitoreDescr; + private String erogatoreDescr; + private String pspDescr; + private String noticeNumber; + private String creditorReferenceId; + private String paymentToken; + private String sessionIdOriginal; + private String dataOraEvento; + private String uniqueId; + private String version; + private Long timestamp; + private String serviceIdentifier; + + public static PanacheQuery findByCIAndNAV( + String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio", creditorInstitution).project(EventEntity.class); + } + public static PanacheQuery findByCIAndIUV( + String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio", creditorInstitution).project(EventEntity.class); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java new file mode 100644 index 0000000..e509a7d --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java @@ -0,0 +1,37 @@ +package it.gov.pagopa.nodetsworker.repository; + +import io.quarkus.mongodb.panache.PanacheMongoEntity; +import io.quarkus.mongodb.panache.PanacheQuery; +import io.quarkus.mongodb.panache.common.MongoEntity; +import lombok.Builder; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +@Data +@Builder +@MongoEntity(collection = "negative-biz-events", clientName = "bizneg") +public class NegativeBizEvent extends PanacheMongoEntity { + private String version; + private String id; + private String useCase; + private String businessProcess; + private Boolean reAwakable; + private DebtorPosition debtorPosition; + private Creditor creditor; + private Psp psp; + private Subject debtor; + private NegativePaymentInfo paymentInfo; + private List transferList; + private Object transactionDetails; + + public static PanacheQuery findByCIAndNAV( + String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio", creditorInstitution).project(NegativeBizEvent.class); + } + public static PanacheQuery findByCIAndIUV( + String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio", creditorInstitution).project(NegativeBizEvent.class); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java new file mode 100644 index 0000000..8628650 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java @@ -0,0 +1,21 @@ +package it.gov.pagopa.nodetsworker.repository; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +class NegativePaymentInfo { + private LocalDateTime paymentDateTime; + private LocalDate dueDate; + private String paymentToken; + private BigDecimal amount; + private Long totalNotice; + private String paymentMethod; + private String touchpoint; + private String remittanceInformation; + private Object metadata; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java new file mode 100644 index 0000000..8b5998a --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java @@ -0,0 +1,19 @@ +package it.gov.pagopa.nodetsworker.repository; + +import java.math.BigDecimal; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class NegativeTransfer { + private String idTransfer; + private String fiscalCodePA; + private String companyName; + private BigDecimal amount; + private String transferCategory; + private String remittanceInformation; + private String IBAN; + private Boolean MBD; + private Object metadata; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java new file mode 100644 index 0000000..8558889 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java @@ -0,0 +1,29 @@ +package it.gov.pagopa.nodetsworker.repository; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class PaymentInfo { + private String description; + private LocalDateTime paymentDateTime; + private LocalDate applicationDate; + private LocalDate transferDate; + private LocalDate dueDate; + private String paymentToken; + private BigDecimal amount; + private BigDecimal fee; + private BigDecimal primaryCiIncurredFee; + private String idBundle; + private String idCiBundle; + private Long totalNotice; + private String paymentMethod; + private String touchpoint; + private String remittanceInformation; + private Object metadata; + private String IUR; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java new file mode 100644 index 0000000..652279d --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java @@ -0,0 +1,41 @@ +package it.gov.pagopa.nodetsworker.repository; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.mongodb.panache.PanacheMongoEntity; +import io.quarkus.mongodb.panache.PanacheQuery; +import io.quarkus.mongodb.panache.common.MongoEntity; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +@Data +@Builder +@MongoEntity(collection = "biz-events", clientName = "biz") +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class PositiveBizEvent extends PanacheMongoEntity { + private String version; + private String id; +// private String idPaymentManager; +// private String receiptId; + private DebtorPosition debtorPosition; +// private Creditor creditor; +// private Psp psp; +// private Subject debtor; +// private Subject payer; +// private PaymentInfo paymentInfo; +// private Transfer transferList; +// private Object transactionDetails; + + + public static PanacheQuery findByCIAndNAV(String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio", creditorInstitution).project(PositiveBizEvent.class); + } + public static PanacheQuery findByCIAndIUV(String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio", creditorInstitution).project(PositiveBizEvent.class); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java new file mode 100644 index 0000000..1aa506b --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java @@ -0,0 +1,16 @@ +package it.gov.pagopa.nodetsworker.repository; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class Psp { + private String idBrokerPsp; + private String idChannel; + private String idPsp; + private String psp; + private String pspPartitaIVA; + private String pspFiscalCode; + private String channelDescription; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java new file mode 100644 index 0000000..564b7b9 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java @@ -0,0 +1,19 @@ +package it.gov.pagopa.nodetsworker.repository; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class Subject { + private String fullName; + private String entityUniqueIdentifierType; + private String entityUniqueIdentifierValue; + private String streetName; + private String civicNumber; + private String postalCode; + private String city; + private String stateProvinceRegion; + private String country; + private String eMail; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java new file mode 100644 index 0000000..ea715bb --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java @@ -0,0 +1,19 @@ +package it.gov.pagopa.nodetsworker.repository; + +import java.math.BigDecimal; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class Transfer { + private String idTransfer; + private String fiscalCodePA; + private String companyName; + private BigDecimal amount; + private String transferCategory; + private String remittanceInformation; + private String IBAN; + private String MBDAttachment; + private Object metadata; +} diff --git a/src/main/java/it/gov/pagopa/quarkustemplate/resources/Generic.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/Generic.java similarity index 72% rename from src/main/java/it/gov/pagopa/quarkustemplate/resources/Generic.java rename to src/main/java/it/gov/pagopa/nodetsworker/resources/Generic.java index a7f124d..6ae8371 100644 --- a/src/main/java/it/gov/pagopa/quarkustemplate/resources/Generic.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/Generic.java @@ -1,6 +1,6 @@ -package it.gov.pagopa.quarkustemplate.resources; +package it.gov.pagopa.nodetsworker.resources; -import it.gov.pagopa.quarkustemplate.models.AppInfo; +import it.gov.pagopa.nodetsworker.models.AppInfo; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.media.Content; @@ -8,23 +8,23 @@ import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; @Path("") @Produces(value = MediaType.APPLICATION_JSON) public class Generic { - @ConfigProperty(name = "quarkus.application.name", defaultValue = "") + @ConfigProperty(name = "app.name", defaultValue = "") private String name; - @ConfigProperty(name = "quarkus.application.version", defaultValue = "") + @ConfigProperty(name = "app.version", defaultValue = "") private String version; - @ConfigProperty(name = "quarkus.application.environment", defaultValue = "") + @ConfigProperty(name = "app.environment", defaultValue = "") private String environment; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java new file mode 100644 index 0000000..9713811 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java @@ -0,0 +1,114 @@ +package it.gov.pagopa.nodetsworker.resources; + +import it.gov.pagopa.nodetsworker.models.ProblemJson; +import it.gov.pagopa.nodetsworker.models.TransactionResponse; +import it.gov.pagopa.nodetsworker.service.WorkerService; +import org.eclipse.microprofile.openapi.annotations.media.Content; +import org.eclipse.microprofile.openapi.annotations.media.Schema; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; + +import jakarta.inject.Inject; +import jakarta.validation.constraints.NotNull; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import java.io.Serializable; +import java.time.LocalDate; + +@Path("/organizations") +@Produces(value = MediaType.APPLICATION_JSON) +public class WorkerResource implements Serializable { + + @Inject + WorkerService workerService; + + /** + * ###### ######## ##### ####### + * ## ## ## ## ## ## ## ## + * ## ## ## ## ## ## + * ###### ######## ## ## ####### + * ## ## ## ## ## + * ## ## ## ## ## ## ## + * ###### ## ##### ####### + */ + @APIResponses(value = { + @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), + @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/noticeNumber/{noticeNumber}") + public Response useCaseSP03_byNoticeNumber( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("noticeNumber") @NotNull String noticeNumber, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo + ) { + return Response.ok(workerService.getInfoByNoticeNumber(organizationFiscalCode, noticeNumber, dateFrom, dateTo)).build(); + } + + @APIResponses(value = { + @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), + @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/iuv/{iuv}") + public Response useCaseSP03_byIUV( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("iuv") @NotNull String iuv, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo + ) { + return Response.ok(workerService.getInfoByIUV(organizationFiscalCode, iuv, dateFrom, dateTo)).build(); + } + + /** + * ###### ######## ##### ## + * ## ## ## ## ## ## ## ## + * ## ## ## ## ## ## ## + * ###### ######## ## ## ## ## + * ## ## ## ## ######### + * ## ## ## ## ## ## + * ###### ## ##### ## + */ + + @APIResponses(value = { + @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), + @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}") + public Response useCaseSP04_byIUV_PaymentToken( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("iuv") @NotNull String iuv, + @PathParam("paymentToken") @NotNull String paymentToken, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo + ) { + return Response.ok(workerService.getAttemptByIUVPaymentToken(organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)).build(); + } + + @APIResponses(value = { + @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), + @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}") + public Response useCaseSP04_byIUV_CCP( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("iuv") @NotNull String iuv, + @PathParam("ccp") @NotNull String ccp, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo + ) { + return Response.ok(workerService.getAttemptByIUVCCP(organizationFiscalCode, iuv, ccp, dateFrom, dateTo)).build(); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/model/Metadata.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/model/Metadata.java new file mode 100644 index 0000000..1675f8e --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/model/Metadata.java @@ -0,0 +1,23 @@ +package it.gov.pagopa.nodetsworker.resources.model; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.eclipse.microprofile.openapi.annotations.media.Schema; + +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Metadata { + + @Schema(example = "25") + private int pageSize; + + @Schema(example = "1") + private int pageNumber; + + @Schema(example = "3") + private int totPage; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java new file mode 100644 index 0000000..eaaf2e9 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java @@ -0,0 +1,25 @@ +package it.gov.pagopa.nodetsworker.resources.response; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import it.gov.pagopa.nodetsworker.resources.model.Metadata; +import it.gov.pagopa.nodetsworker.service.dto.EventDto; +import lombok.Builder; +import lombok.Getter; +import lombok.extern.jackson.Jacksonized; +import org.eclipse.microprofile.openapi.annotations.media.Schema; + +import java.util.List; + +@Getter +@Builder +@Jacksonized +@JsonPropertyOrder({"metadata", "count", "data"}) +public class FindEventsResponse { + + private Metadata metadata; + + @Schema(example = "100") + private Long count; + + private List data; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java new file mode 100644 index 0000000..4d52f42 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -0,0 +1,143 @@ +package it.gov.pagopa.nodetsworker.service; + +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.models.SqlParameter; +import com.azure.cosmos.models.SqlQuerySpec; +import com.azure.cosmos.util.CosmosPagedIterable; +import it.gov.pagopa.nodetsworker.exceptions.AppError; +import it.gov.pagopa.nodetsworker.exceptions.AppException; +import it.gov.pagopa.nodetsworker.models.BasePaymentInfo; +import it.gov.pagopa.nodetsworker.models.DateRequest; +import it.gov.pagopa.nodetsworker.models.TransactionResponse; +import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; +import it.gov.pagopa.nodetsworker.repository.EventEntity; +import it.gov.pagopa.nodetsworker.repository.NegativeBizEvent; +import it.gov.pagopa.nodetsworker.repository.PositiveBizEvent; +import it.gov.pagopa.nodetsworker.service.mapper.EventMapper; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@ApplicationScoped +public class WorkerService { + + @Inject + Logger log; + + @Inject + EventMapper eventsMapper; + + @Inject + CosmosBizEventClient positiveBizClient; + + + public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, + String noticeNumber, + LocalDate dateFrom, + LocalDate dateTo){ + + List list = EventEntity.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); +// List biz = PositiveBizEvent.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); +// List neg = NegativeBizEvent.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); + + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where " + + "c.creditor.idPA = @organizationFiscalCode " //+ +// "and c.debtorPosition.noticeNumber = @noticeNumber"// + +// "and c.paymentInfo.paymentDateTime > @from " + +// "and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + + CosmosPagedIterable ax = positiveBizClient.query(q); + List collect = ax.stream().map(s->{ + return BasePaymentInfo.builder() +// .brokerPspId() +// .pspId() +// .nodeId() +// .channelId() +// .brokerPspId() + .noticeNumber(s.getDebtorPosition()!=null?s.getDebtorPosition().getNoticeNumber():"").build(); +// .organizationFiscalCode(); + }).collect(Collectors.toList()); + return TransactionResponse.builder() + .payments(collect) + .build(); + + } + + public TransactionResponse getInfoByIUV(String organizationFiscalCode, + String noticeNumber, + LocalDate dateFrom, + LocalDate dateTo){ + + List list = EventEntity.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); + List biz = PositiveBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); + List neg = NegativeBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); + + return TransactionResponse.builder() + .build(); + + } + + public TransactionResponse getAttemptByIUVPaymentToken(String organizationFiscalCode, String iuv, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + +// List payments = getPaymentPositionListByIUVPaymentToken(organizationFiscalCode, iuv, paymentToken, dateRequest.getFrom(), dateRequest.getTo()); +// List paymentAttemptInfoList = enrichPaymentAttemptPositionList(payments, dateRequest.getFrom(), dateRequest.getTo()); + + return TransactionResponse.builder() + .dateFrom(dateRequest.getFrom()) + .dateTo(dateRequest.getTo()) +// .payments(paymentAttemptInfoList) + .build(); + } + public TransactionResponse getAttemptByIUVCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + +// List rptList = getRPTListByIUVCCP(organizationFiscalCode, iuv, ccp, dateRequest.getFrom(), dateRequest.getTo()); +// List rptAttemptInfoList = enrichRPTAttemptList(rptList, dateRequest.getFrom(), dateRequest.getTo()); + + return TransactionResponse.builder() + .dateFrom(dateRequest.getFrom()) + .dateTo(dateRequest.getTo()) +// .payments(rptAttemptInfoList) + .build(); + } + + /** + * Check dates validity + * @param dateFrom + * @param dateTo + */ + private DateRequest verifyDate(LocalDate dateFrom, LocalDate dateTo) { + if (dateFrom == null && dateTo != null || dateFrom != null && dateTo == null) { + throw new AppException(AppError.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from and date to must be both defined"); + } + else if (dateFrom != null && dateTo != null && dateFrom.isAfter(dateTo)) { + throw new AppException(AppError.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from must be before date to"); + } + if (dateFrom == null && dateTo == null) { + dateFrom = LocalDate.now(); + dateTo = dateFrom.minusDays(10); + } + return DateRequest.builder() + .from(dateFrom) + .to(dateTo) + .build(); + } + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java b/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java new file mode 100644 index 0000000..0b9c077 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java @@ -0,0 +1,44 @@ +package it.gov.pagopa.nodetsworker.service.dto; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode +public class EventDto { + + private String insertedTimestamp; + private String componente; + private String categoriaEvento; + private String sottoTipoEvento; + private String idDominio; + private String iuv; + private String ccp; + private String psp; + private String tipoVersamento; + private String tipoEvento; + private String fruitore; + private String erogatore; + private String stazione; + private String canale; + private String parametriSpecificiInterfaccia; + private String esito; + private String sessionId; + private String status; + private String payload; + private String info; + private String businessProcess; + private String fruitoreDescr; + private String erogatoreDescr; + private String pspDescr; + private String noticeNumber; + private String creditorReferenceId; + private String paymentToken; + private String sessionIdOriginal; + private String dataOraEvento; + private String uniqueId; + private String version; + private Long timestamp; + private String serviceIdentifier; + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java new file mode 100644 index 0000000..f99caff --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java @@ -0,0 +1,19 @@ +package it.gov.pagopa.nodetsworker.service.mapper; + +import it.gov.pagopa.nodetsworker.repository.EventEntity; +import it.gov.pagopa.nodetsworker.service.dto.EventDto; +import org.mapstruct.Mapper; +import org.mapstruct.MappingConstants.ComponentModel; +import org.mapstruct.factory.Mappers; + +import java.util.List; + +@Mapper(componentModel = ComponentModel.JAKARTA) +public interface EventMapper { + + EventMapper INSTANCE = Mappers.getMapper(EventMapper.class); + + EventDto map(EventEntity entity); + List map(List entities); + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index d85843a..36d0a38 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,62 +1,122 @@ ################### ## CUSTOM ################### -quarkus.application.environment=${ENV:local} -quarkus.application.title=${APP_TITLE:Quarkus Template} +app.name=${APP_NAME:node-techincal-support-worker} +app.version=${APP_VERSION:0.0.0-SNAPSHOT} +app.environment=${APP_ENVIRONMENT:local} ################### ## COMMON OVERRIDE ################### +quarkus.native.additional-build-args=-H:ResourceConfigurationFiles=resources-config.json quarkus.default-locale=it-IT quarkus.locales=it-IT -quarkus.native.additional-build-args=-H:ResourceConfigurationFiles=resources-config.json ################### ## LOG ################### -quarkus.log.level=${LOG_LEVEL:INFO} +quarkus.log.file.json=false + +quarkus.log.level=INFO +#quarkus.log.category."io.quarkus.mongodb".level=DEBUG +#quarkus.log.category."org.mongodb.driver.protocol.command".level=DEBUG +#quarkus.log.category."org.jboss".level=DEBUG +#quarkus.log.category."it.gov.pagopa.fdr".level=DEBUG -quarkus.log.category."org.jboss".level=${JBOSS_LOG_LEVEL:DEBUG} -quarkus.log.category."it.gov.pagopa.quarkustemplate".level=${APP_LOG_LEVEL:DEBUG} %dev.quarkus.log.console.json=false %test.quarkus.log.console.json=false -quarkus.log.console.json.additional-field."app_name".value=${quarkus.application.name} -quarkus.log.console.json.additional-field."app_version".value=${quarkus.application.version} -quarkus.log.console.json.additional-field."app_environment".value=${quarkus.application.environment} +%openapi.quarkus.log.console.json=false +quarkus.log.console.json.additional-field."app_name".value=${app.name} +quarkus.log.console.json.additional-field."app_version".value=${app.version} +quarkus.log.console.json.additional-field."app_environment".value=${app.environment} ################### ## OPENTELEMETRY ################### -quarkus.opentelemetry.enabled=true -%dev.quarkus.opentelemetry.enabled=false -%test.quarkus.opentelemetry.enabled=false -%openapi.quarkus.opentelemetry.enabled=false -quarkus.opentelemetry.tracer.exporter.otlp.endpoint=http://otel-collector.elastic-system.svc.cluster.local:4317 -quarkus.opentelemetry.tracer.exporter.otlp.headers=Authorization=Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjA0VlBnYVNzNGVsdDExY21KLXNZc2FFS1k5ZW4wb3htRklHNUR2UW10Z1UifQ -%dev.quarkus.opentelemetry.tracer.exporter.otlp.endpoint=http://localhost:4317 -%dev.quarkus.opentelemetry.tracer.exporter.otlp.headers=Authorization=Bearer my-token -%test.quarkus.opentelemetry.tracer.exporter.otlp.endpoint=http://localhost:4317 -%test.quarkus.opentelemetry.tracer.exporter.otlp.headers=Authorization=Bearer my-token -%docker.quarkus.opentelemetry.tracer.exporter.otlp.endpoint=http://otel-collector:4317 -%docker.quarkus.opentelemetry.tracer.exporter.otlp.headers=Authorization=Bearer my-token +quarkus.otel.enabled=false +%dev.quarkus.otel.enabled=false +%test.quarkus.otel.enabled=false +%openapi.quarkus.otel.enabled=false +%openapi_internal.quarkus.otel.enabled=false +quarkus.otel.exporter.otlp.traces.endpoint=${OTEL_ENDPOINT} +quarkus.otel.exporter.otlp.traces.headers=${OTEL_AUTH_BEARER} +%dev.quarkus.otel.exporter.otlp.traces.endpoint=http://localhost:4317 +%dev.quarkus.otel.exporter.otlp.traces.headers=Authorization=Bearer my-token +%test.quarkus.otel.exporter.otlp.traces.endpoint=http://localhost:4317 +%test.quarkus.otel.exporter.otlp.traces.headers=Authorization=Bearer my-token +%docker.quarkus.otel.exporter.otlp.traces.endpoint=http://otel-collector:4317 +%docker.quarkus.otel.exporter.otlp.traces.headers=Authorization=Bearer my-token #quarkus.log.console.format=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p traceId=%X{traceId}, parentId=%X{parentId}, spanId=%X{spanId}, sampled=%X{sampled} [%c{3.}] (%t) %s%e%n -#################### +################### ## OPENAPI - SWAGGER -#################### -quarkus.smallrye-openapi.info-title=${quarkus.application.title} (${quarkus.application.environment}) ${service} -%dev.quarkus.smallrye-openapi.info-title=${quarkus.application.title} (DEV) -%test.quarkus.smallrye-openapi.info-title=${quarkus.application.title} (TEST) -%docker.quarkus.smallrye-openapi.info-title=${quarkus.application.title} (DOCKER) -quarkus.smallrye-openapi.info-description=${quarkus.application.title} description +################### +quarkus.smallrye-openapi.info-title=Node technical support - Api (${app.environment}) \\$\{service\} +%dev.quarkus.smallrye-openapi.info-title=Node technical support - Api (DEV) +%test.quarkus.smallrye-openapi.info-title=Node technical support - Api (TEST) +%docker.quarkus.smallrye-openapi.info-title=Node technical support - Api (DOCKER) quarkus.smallrye-openapi.info-terms-of-service=https://www.pagopa.gov.it/ -# TODO modify project -quarkus.smallrye-openapi.servers=\\$\{host\}/quarkus-template/api/v1 - APIM -# Path for the Swagger endpoint and file -quarkus.swagger-ui.path=/swagger -quarkus.smallrye-openapi.path=/openapi.json +quarkus.smallrye-openapi.servers=\\$\{host\}/tenchinal-support/api/v1 - APIM + +################### +## DATABASE +################### + +%test.quarkus.mongodb.connection-string=${mockserver.mongodb.connection-string} + +quarkus.mongodb.events.connection-string=${MONGODB_EVENTS_CONNECTION_STRING} +%dev.quarkus.mongodb.events.connection-string = ${DEV_MONGODB_EVENTS_CONNECTION_STRING} +quarkus.mongodb.events.database=nodo_re + +biz.endpoint=${MONGODB_BIZ_CONNECTION_STRING} +biz.key=${MONGODB_BIZ_ACCOUNT_KEY} +%dev.biz.endpoint=https://pagopa-d-weu-bizevents-ds-cosmos-account.documents.azure.com:443/ +%dev.biz.key=${DEV_BIZ_KEY} +bizneg.endpoint=${MONGODB_NEG_BIZ_CONNECTION_STRING} +bizneg.key=${MONGODB_NEG_BIZ_ACCOUNT_KEY} +%dev.bizneg.endpoint=https://pagopa-d-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/ +%dev.bizneg.key=${DEV_BIZNEG_KEY} + +################### +## ADAPTER API CONFIG CACHE +################### +#quarkus.rest-client.logging.scope=request-response +#quarkus.rest-client.logging.body-limit=1024 +#quarkus.log.category."org.jboss.resteasy.reactive.client.logging".level=DEBUG + +adapter.api_config_cache.api-key-name=Ocp-Apim-Subscription-Key +adapter.api_config_cache.api-key-value=${ADAPTER_API_CONFIG_CACHE_API_KEY:12345} +#adapter.api_config_cache.url=https://api.dev.platform.pagopa.it/api-config-cache/pr/v1 +#adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:http://localhost:9091/} + +################### +## SCHEDULER +################### +%test.quarkus.scheduler.enabled=false +%openapi.quarkus.scheduler.enabled=false +%openapi_internal.quarkus.scheduler.enabled=false +# By default, the syntax used for cron expressions is based on Quartz - https://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html +# You can change the syntax using the following property: +# quarkus.scheduler.cron-type=unix +api_config_cache.cron.expr=*/15 * * * * ? +startconfig.enabled=true +%openapi.startconfig.enabled=false +%openapi_internal.startconfig.enabled=false +operations.filter=".*" +############## +# MOCK SERVER +############## +%dev.quarkus.mockserver.devservices.config-file=src/test/resources/mockserver.properties +%dev.quarkus.mockserver.devservices.config-dir=src/test/resources/mockserver +%dev.quarkus.mockserver.devservices.log=false +%test.quarkus.mockserver.devservices.config-file=src/test/resources/mockserver.properties +%test.quarkus.mockserver.devservices.config-dir=src/test/resources/mockserver +%test.quarkus.mockserver.devservices.log=false +%dev.adapter.api_config_cache.url=${quarkus.mockserver.endpoint} +%test.adapter.api_config_cache.url=${quarkus.mockserver.endpoint} +adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:${quarkus.mockserver.endpoint}} diff --git a/src/test/java/it/gov/pagopa/quarkustemplate/resources/GenericTest.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/GenericTest.java similarity index 81% rename from src/test/java/it/gov/pagopa/quarkustemplate/resources/GenericTest.java rename to src/test/java/it/gov/pagopa/nodetsworker/resources/GenericTest.java index debf465..da063f2 100644 --- a/src/test/java/it/gov/pagopa/quarkustemplate/resources/GenericTest.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/GenericTest.java @@ -1,10 +1,10 @@ -package it.gov.pagopa.quarkustemplate.resources; +package it.gov.pagopa.nodetsworker.resources; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import static io.restassured.RestAssured.given; From b18ceadf1dcd0ffa90967e9219d72017bddaf747 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Thu, 29 Jun 2023 15:11:18 +0200 Subject: [PATCH 02/29] wip --- .../nodetsworker/exceptions/AppError.java | 26 ------ .../exceptions/AppErrorCodeMessageEnum.java | 75 +++++++++++++++++ .../AppErrorCodeMessageInterface.java | 11 +++ .../nodetsworker/exceptions/AppException.java | 40 ++++++--- .../repository/CosmosBizEventClient.java | 35 +++++++- .../repository/CosmosNegBizEventClient.java | 64 +++++++++++++++ .../nodetsworker/repository/Creditor.java | 6 +- .../nodetsworker/repository/EventEntity.java | 8 +- .../repository/NegativeBizEvent.java | 11 +-- .../repository/NegativePaymentInfo.java | 5 ++ .../repository/NegativeTransfer.java | 5 ++ .../nodetsworker/repository/PaymentInfo.java | 13 ++- .../repository/PositiveBizEvent.java | 32 +++----- .../pagopa/nodetsworker/repository/Psp.java | 4 + .../nodetsworker/repository/Subject.java | 4 + .../nodetsworker/repository/Transfer.java | 7 ++ .../nodetsworker/resources/Generic.java | 52 ------------ .../nodetsworker/resources/InfoResource.java | 70 ++++++++++++++++ .../resources/response/InfoResponse.java | 43 ++++++++++ .../nodetsworker/service/WorkerService.java | 81 +++++++++---------- .../pagopa/nodetsworker/util/AppConstant.java | 16 ++++ .../nodetsworker/util/AppMessageUtil.java | 41 ++++++++++ src/main/resources/application.properties | 13 +-- 23 files changed, 480 insertions(+), 182 deletions(-) delete mode 100644 src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageInterface.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java delete mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/Generic.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/util/AppConstant.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/util/AppMessageUtil.java diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java deleted file mode 100644 index 92442bd..0000000 --- a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppError.java +++ /dev/null @@ -1,26 +0,0 @@ -package it.gov.pagopa.nodetsworker.exceptions; - -import lombok.Getter; - - -@Getter -public enum AppError { - - POSITION_SERVICE_NOT_FOUND(404, "Not found", "Position service with organization %s and %s not found"), - POSITION_SERVICE_DATE_BAD_REQUEST(400, "Bad Request", "%s"), - WORKER_CONFLICT(409, "Conflict", "A worker with the nodeId %s already exists"), - INTERNAL_ERROR(500, "Internal error", "Processing error"), - UNKNOWN(520, null, null); - - - public final int httpStatus; - public final String title; - public final String details; - - - AppError(int httpStatus, String title, String details) { - this.httpStatus = httpStatus; - this.title = title; - this.details = details; - } -} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java new file mode 100644 index 0000000..60a5488 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java @@ -0,0 +1,75 @@ +package it.gov.pagopa.nodetsworker.exceptions; + +import it.gov.pagopa.nodetsworker.util.AppConstant; +import it.gov.pagopa.nodetsworker.util.AppMessageUtil; +import org.jboss.resteasy.reactive.RestResponse; + +public enum AppErrorCodeMessageEnum implements AppErrorCodeMessageInterface { + POSITION_SERVICE_DATE_BAD_REQUEST("0400","bad.request", RestResponse.Status.BAD_REQUEST), + ERROR("0500", "system.error", RestResponse.Status.INTERNAL_SERVER_ERROR), + BAD_REQUEST("0400", "bad.request", RestResponse.Status.BAD_REQUEST), + BAD_REQUEST_INPUT_JSON("0401", "bad.request.inputJson", RestResponse.Status.BAD_REQUEST), + BAD_REQUEST_INPUT_JSON_INSTANT( + "0402", "bad.request.inputJson.instant", RestResponse.Status.BAD_REQUEST), + BAD_REQUEST_INPUT_JSON_ENUM( + "0403", "bad.request.inputJson.enum", RestResponse.Status.BAD_REQUEST), + + BAD_REQUEST_INPUT_JSON_DESERIALIZE_ERROR( + "0404", "bad.request.inputJson.deserialize", RestResponse.Status.BAD_REQUEST), + BAD_REQUEST_INPUT_JSON_NON_VALID_FORMAT( + "0405", "bad.request.inputJson.notValidJsonFormat", RestResponse.Status.BAD_REQUEST), + + REPORTING_FLOW_NOT_FOUND("0701", "reporting-flow.notFound", RestResponse.Status.NOT_FOUND), + REPORTING_FLOW_ALREADY_EXIST( + "0702", "reporting-flow.alreadyExist", RestResponse.Status.BAD_REQUEST), + REPORTING_FLOW_WRONG_ACTION( + "0703", "reporting-flow.wrongAction", RestResponse.Status.BAD_REQUEST), + REPORTING_FLOW_PSP_ID_NOT_MATCH( + "0704", "reporting-flow.pspId.notMatch", RestResponse.Status.BAD_REQUEST), + REPORTING_FLOW_PAYMENT_SAME_INDEX_IN_SAME_REQUEST( + "0705", "reporting-flow.sameIndexInSameRequest", RestResponse.Status.BAD_REQUEST), + REPORTING_FLOW_PAYMENT_DUPLICATE_INDEX( + "0706", "reporting-flow.duplicateIndex", RestResponse.Status.BAD_REQUEST), + REPORTING_FLOW_PAYMENT_NO_MATCH_INDEX( + "0707", "reporting-flow.noMatchIndex", RestResponse.Status.BAD_REQUEST), + PSP_UNKNOWN("0708", "pspId.unknown", RestResponse.Status.BAD_REQUEST), + PSP_NOT_ENABLED("0709", "pspId.notEnabled", RestResponse.Status.BAD_REQUEST), + BROKER_UNKNOWN("0710", "brokerId.unknown", RestResponse.Status.BAD_REQUEST), + BROKER_NOT_ENABLED("0711", "brokerId.notEnabled", RestResponse.Status.BAD_REQUEST), + CHANNEL_UNKNOWN("0712", "channelId.unknown", RestResponse.Status.BAD_REQUEST), + CHANNEL_NOT_ENABLED("0713", "channelId.notEnabled", RestResponse.Status.BAD_REQUEST), + CHANNEL_BROKER_WRONG_CONFIG( + "0714", "channel.broker.wrongConfig", RestResponse.Status.BAD_REQUEST), + CHANNEL_PSP_WRONG_CONFIG("0715", "channel.psp.wrongConfig", RestResponse.Status.BAD_REQUEST), + EC_UNKNOWN("0716", "ecId.unknown", RestResponse.Status.BAD_REQUEST), + EC_NOT_ENABLED("0717", "ecId.notEnabled", RestResponse.Status.BAD_REQUEST), + REPORTING_FLOW_NAME_DATE_WRONG_FORMAT( + "0718", "reporting-flow.name-date.wrongFormat", RestResponse.Status.BAD_REQUEST), + REPORTING_FLOW_NAME_PSP_WRONG_FORMAT( + "0719", "reporting-flow.name-psp.wrongFormat", RestResponse.Status.BAD_REQUEST); + private final String errorCode; + private final String errorMessageKey; + private final RestResponse.Status httpStatus; + + AppErrorCodeMessageEnum( + String errorCode, String errorMessageKey, RestResponse.Status httpStatus) { + this.errorCode = errorCode; + this.errorMessageKey = errorMessageKey; + this.httpStatus = httpStatus; + } + + @Override + public String errorCode() { + return AppConstant.SERVICE_CODE_APP + "-" + errorCode; + } + + @Override + public String message(Object... args) { + return AppMessageUtil.getMessage(errorMessageKey, args); + } + + @Override + public RestResponse.Status httpStatus() { + return httpStatus; + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageInterface.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageInterface.java new file mode 100644 index 0000000..4998e7a --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageInterface.java @@ -0,0 +1,11 @@ +package it.gov.pagopa.nodetsworker.exceptions; + +import org.jboss.resteasy.reactive.RestResponse; + +public interface AppErrorCodeMessageInterface { + String errorCode(); + + String message(Object... args); + + RestResponse.Status httpStatus(); +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java index 040b4e5..70dca33 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java @@ -2,22 +2,36 @@ import lombok.Getter; -import jakarta.validation.constraints.NotNull; +import java.io.Serializable; @Getter -public class AppException extends RuntimeException{ - - String title; +public class AppException extends RuntimeException { - int httpStatus; + private final transient AppErrorCodeMessageInterface codeMessage; - public AppException(@NotNull AppError appError, Object... args) { - super(formatDetails(appError, args)); - this.httpStatus = appError.httpStatus; - this.title = appError.title; - } + private final transient Object[] args; - private static String formatDetails(AppError appError, Object[] args) { - return String.format(appError.details, args); - } + public AppException(Throwable cause, AppErrorCodeMessageInterface codeMessage) { + super(cause); + this.codeMessage = codeMessage; + this.args = null; + } + + public AppException(Throwable cause, AppErrorCodeMessageInterface codeMessage, Object... args) { + super(cause); + this.codeMessage = codeMessage; + this.args = args; + } + + public AppException(AppErrorCodeMessageInterface codeMessage) { + super(); + this.codeMessage = codeMessage; + this.args = null; + } + + public AppException(AppErrorCodeMessageInterface codeMessage, Serializable... args) { + super(); + this.codeMessage = codeMessage; + this.args = args; + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java index 61d9d5b..20bb202 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -4,14 +4,22 @@ import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosContainer; import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.SqlParameter; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; +import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + @ApplicationScoped +@Startup public class CosmosBizEventClient { @ConfigProperty(name = "biz.endpoint") @@ -20,17 +28,36 @@ public class CosmosBizEventClient { @ConfigProperty(name = "biz.key") private String key; + private static String dbname = "db"; + private static String tablename = "biz-events"; + @Inject Logger log; - - - public CosmosPagedIterable query(SqlQuerySpec query){ + private CosmosPagedIterable query(SqlQuerySpec query){ log.info("executing query:"+query.getQueryText()); CosmosClient client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); - CosmosContainer container = client.getDatabase("db").getContainer("biz-events"); + CosmosContainer container = client.getDatabase(dbname).getContainer(tablename); return container.queryItems(query, new CosmosQueryRequestOptions(), PositiveBizEvent.class); } + public CosmosPagedIterable findEvents(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom,LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where " + + "c.creditor.idPA = @organizationFiscalCode " + + "and c.debtorPosition.noticeNumber != null " + + "and c.debtorPosition.noticeNumber = @noticeNumber " + + "and c.paymentInfo != null " + + "and c.paymentInfo.paymentDateTime > @from " + + "and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return query(q); + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java new file mode 100644 index 0000000..bdef946 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java @@ -0,0 +1,64 @@ +package it.gov.pagopa.nodetsworker.repository; + +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosContainer; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.SqlParameter; +import com.azure.cosmos.models.SqlQuerySpec; +import com.azure.cosmos.util.CosmosPagedIterable; +import jakarta.ejb.Startup; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +@ApplicationScoped +@Startup +public class CosmosNegBizEventClient { + + @ConfigProperty(name = "bizneg.endpoint") + private String endpoint; + + @ConfigProperty(name = "bizneg.key") + private String key; + + private static String dbname = "db"; + private static String tablename = "negative-biz-events"; + + @Inject + Logger log; + + private CosmosPagedIterable query(SqlQuerySpec query){ + log.info("executing query:"+query.getQueryText()); + CosmosClient client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); + CosmosContainer container = client.getDatabase(dbname).getContainer(tablename); + return container.queryItems(query, new CosmosQueryRequestOptions(), NegativeBizEvent.class); + } + + public CosmosPagedIterable findEvents(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where " + + "c.creditor.idPA = @organizationFiscalCode " + + "and c.debtorPosition.noticeNumber != null " + + "and c.debtorPosition.noticeNumber = @noticeNumber " + + "and c.paymentInfo != null " + + "and c.paymentInfo.paymentDateTime > @from " + + "and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return query(q); + } + + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java index 713df9e..f36afef 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java @@ -1,11 +1,15 @@ package it.gov.pagopa.nodetsworker.repository; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data @Builder -class Creditor { +@NoArgsConstructor +@AllArgsConstructor +public class Creditor { private String idPA; private String idBrokerPA; private String idStation; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java index 2a098f8..a98c4ba 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java @@ -3,10 +3,12 @@ import io.quarkus.mongodb.panache.PanacheMongoEntity; import io.quarkus.mongodb.panache.PanacheQuery; import io.quarkus.mongodb.panache.common.MongoEntity; -import java.time.LocalDate; +import io.quarkus.panache.common.Parameters; import lombok.Data; import lombok.EqualsAndHashCode; +import java.time.LocalDate; + @Data @EqualsAndHashCode(callSuper = true) @MongoEntity(collection = "events", clientName = "events") @@ -48,7 +50,9 @@ public class EventEntity extends PanacheMongoEntity { public static PanacheQuery findByCIAndNAV( String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio", creditorInstitution).project(EventEntity.class); + return find("idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO'", + Parameters.with("idDominio", creditorInstitution).and("noticeNumber",nav)) + .project(EventEntity.class); } public static PanacheQuery findByCIAndIUV( String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java index e509a7d..b4e2f38 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java @@ -11,8 +11,7 @@ @Data @Builder -@MongoEntity(collection = "negative-biz-events", clientName = "bizneg") -public class NegativeBizEvent extends PanacheMongoEntity { +public class NegativeBizEvent { private String version; private String id; private String useCase; @@ -26,12 +25,4 @@ public class NegativeBizEvent extends PanacheMongoEntity { private List transferList; private Object transactionDetails; - public static PanacheQuery findByCIAndNAV( - String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio", creditorInstitution).project(NegativeBizEvent.class); - } - public static PanacheQuery findByCIAndIUV( - String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio", creditorInstitution).project(NegativeBizEvent.class); - } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java index 8628650..6aae1ef 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java @@ -3,11 +3,16 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; + +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data @Builder +@NoArgsConstructor +@AllArgsConstructor class NegativePaymentInfo { private LocalDateTime paymentDateTime; private LocalDate dueDate; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java index 8b5998a..4250d27 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java @@ -1,11 +1,16 @@ package it.gov.pagopa.nodetsworker.repository; import java.math.BigDecimal; + +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data @Builder +@NoArgsConstructor +@AllArgsConstructor public class NegativeTransfer { private String idTransfer; private String fiscalCodePA; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java index 8558889..6642271 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java @@ -3,17 +3,24 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data @Builder +@JsonIgnoreProperties(ignoreUnknown = true) +@NoArgsConstructor +@AllArgsConstructor public class PaymentInfo { private String description; private LocalDateTime paymentDateTime; - private LocalDate applicationDate; - private LocalDate transferDate; - private LocalDate dueDate; + private String applicationDate; + private String transferDate; + private String dueDate; private String paymentToken; private BigDecimal amount; private BigDecimal fee; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java index 652279d..f5d63a7 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java @@ -1,15 +1,13 @@ package it.gov.pagopa.nodetsworker.repository; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import io.quarkus.mongodb.panache.PanacheMongoEntity; -import io.quarkus.mongodb.panache.PanacheQuery; import io.quarkus.mongodb.panache.common.MongoEntity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.time.LocalDate; +import java.util.List; @Data @Builder @@ -17,25 +15,17 @@ @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) -public class PositiveBizEvent extends PanacheMongoEntity { +public class PositiveBizEvent { private String version; private String id; -// private String idPaymentManager; -// private String receiptId; + private String idPaymentManager; + private String receiptId; private DebtorPosition debtorPosition; -// private Creditor creditor; -// private Psp psp; -// private Subject debtor; -// private Subject payer; -// private PaymentInfo paymentInfo; -// private Transfer transferList; -// private Object transactionDetails; - - - public static PanacheQuery findByCIAndNAV(String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio", creditorInstitution).project(PositiveBizEvent.class); - } - public static PanacheQuery findByCIAndIUV(String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio", creditorInstitution).project(PositiveBizEvent.class); - } + private Creditor creditor; + private Psp psp; + private Subject debtor; + private Subject payer; + private PaymentInfo paymentInfo; + private List transferList; + private Object transactionDetails; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java index 1aa506b..47a9b85 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java @@ -1,10 +1,14 @@ package it.gov.pagopa.nodetsworker.repository; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data @Builder +@NoArgsConstructor +@AllArgsConstructor public class Psp { private String idBrokerPsp; private String idChannel; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java index 564b7b9..ffda48d 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java @@ -1,10 +1,14 @@ package it.gov.pagopa.nodetsworker.repository; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data @Builder +@NoArgsConstructor +@AllArgsConstructor public class Subject { private String fullName; private String entityUniqueIdentifierType; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java index ea715bb..da59142 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java @@ -1,11 +1,18 @@ package it.gov.pagopa.nodetsworker.repository; import java.math.BigDecimal; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data @Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) public class Transfer { private String idTransfer; private String fiscalCodePA; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/Generic.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/Generic.java deleted file mode 100644 index 6ae8371..0000000 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/Generic.java +++ /dev/null @@ -1,52 +0,0 @@ -package it.gov.pagopa.nodetsworker.resources; - -import it.gov.pagopa.nodetsworker.models.AppInfo; -import org.eclipse.microprofile.config.inject.ConfigProperty; -import org.eclipse.microprofile.openapi.annotations.Operation; -import org.eclipse.microprofile.openapi.annotations.media.Content; -import org.eclipse.microprofile.openapi.annotations.media.Schema; -import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; -import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; - -import jakarta.ws.rs.GET; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.UriBuilder; - -@Path("") -@Produces(value = MediaType.APPLICATION_JSON) -public class Generic { - @ConfigProperty(name = "app.name", defaultValue = "") - private String name; - - @ConfigProperty(name = "app.version", defaultValue = "") - private String version; - - @ConfigProperty(name = "app.environment", defaultValue = "") - private String environment; - - - @Operation(hidden = true) - @GET - @Path("") - public Response home(){ - return Response.seeOther(UriBuilder.fromUri("/swagger").build()).build(); - } - - @APIResponses(value = { - @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = AppInfo.class))), - @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON)) - }) - @GET - @Path("/info") - public Response info() { - AppInfo info = AppInfo.builder() - .name(name) - .version(version) - .environment(environment) - .build(); - return Response.ok(info).build(); - } -} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java new file mode 100644 index 0000000..330e5a2 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java @@ -0,0 +1,70 @@ +package it.gov.pagopa.nodetsworker.exceptions; + +import it.gov.pagopa.nodetsworker.resources.response.InfoResponse; +import it.gov.pagopa.nodetsworker.util.AppMessageUtil; +import jakarta.inject.Inject; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.eclipse.microprofile.openapi.annotations.Operation; +import org.eclipse.microprofile.openapi.annotations.media.Content; +import org.eclipse.microprofile.openapi.annotations.media.Schema; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; +import org.eclipse.microprofile.openapi.annotations.tags.Tag; +import org.jboss.logging.Logger; + +import java.util.Arrays; + +@Path("/info") +@Tag(name = "Info", description = "Info operations") +public class InfoResource { + + @Inject Logger log; + + @ConfigProperty(name = "app.name", defaultValue = "app") + String name; + + @ConfigProperty(name = "app.version", defaultValue = "0.0.0") + String version; + + @ConfigProperty(name = "app.environment", defaultValue = "local") + String environment; + + @Operation(summary = "Get info of FDR") + @APIResponses( + value = { + @APIResponse(ref = "#/components/responses/InternalServerError"), + @APIResponse( + responseCode = "200", + description = "Success", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = InfoResponse.class))) + }) + @Produces(MediaType.APPLICATION_JSON) + @GET + public InfoResponse hello() { + log.infof("Info environment: [%s] - name: [%s] - version: [%s]", environment, name, version); + + return InfoResponse.builder() + .name(name) + .version(version) + .environment(environment) + .description(AppMessageUtil.getMessage("app.description")) + .errorCodes( + Arrays.stream(AppErrorCodeMessageEnum.values()) + .map( + errorCode -> + InfoResponse.ErrorCode.builder() + .code(errorCode.errorCode()) + .description(errorCode.message()) + .statusCode(errorCode.httpStatus().getStatusCode()) + .build()) + .toList()) + .build(); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java new file mode 100644 index 0000000..cfb5a63 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java @@ -0,0 +1,43 @@ +package it.gov.pagopa.nodetsworker.resources.response; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.*; +import lombok.extern.jackson.Jacksonized; +import org.eclipse.microprofile.openapi.annotations.media.Schema; + +import java.util.List; + +@Getter +@Builder +@Jacksonized +@JsonPropertyOrder({"name", "version", "environment", "description", "errorCodes"}) +public class InfoResponse { + @Schema(example = "pagopa-fdr") + private String name; + + @Schema(example = "1.2.3") + private String version; + + @Schema(example = "dev") + private String environment; + + @Schema(example = "FDR - Flussi di rendicontazione") + private String description; + + private List errorCodes; + + @Builder + @Data + @AllArgsConstructor + @NoArgsConstructor + public static class ErrorCode { + @Schema(example = "FDR-0500") + private String code; + + @Schema(example = "An unexpected error has occurred. Please contact support.") + private String description; + + @Schema(example = "500") + private int statusCode; + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index 4d52f42..80cfc37 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -1,26 +1,22 @@ package it.gov.pagopa.nodetsworker.service; -import com.azure.cosmos.CosmosClient; -import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.models.SqlParameter; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; -import it.gov.pagopa.nodetsworker.exceptions.AppError; +import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageEnum; import it.gov.pagopa.nodetsworker.exceptions.AppException; import it.gov.pagopa.nodetsworker.models.BasePaymentInfo; import it.gov.pagopa.nodetsworker.models.DateRequest; +import it.gov.pagopa.nodetsworker.models.PaymentInfo; import it.gov.pagopa.nodetsworker.models.TransactionResponse; -import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; -import it.gov.pagopa.nodetsworker.repository.EventEntity; -import it.gov.pagopa.nodetsworker.repository.NegativeBizEvent; -import it.gov.pagopa.nodetsworker.repository.PositiveBizEvent; +import it.gov.pagopa.nodetsworker.repository.*; import it.gov.pagopa.nodetsworker.service.mapper.EventMapper; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.time.LocalDate; +import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; @@ -37,43 +33,46 @@ public class WorkerService { @Inject CosmosBizEventClient positiveBizClient; - + @Inject + CosmosNegBizEventClient negativeBizClient; public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ - List list = EventEntity.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); -// List biz = PositiveBizEvent.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); -// List neg = NegativeBizEvent.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); - - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); - - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where " + - "c.creditor.idPA = @organizationFiscalCode " //+ -// "and c.debtorPosition.noticeNumber = @noticeNumber"// + -// "and c.paymentInfo.paymentDateTime > @from " + -// "and c.paymentInfo.paymentDateTime < @to" - ) - .setParameters(paramList); - - CosmosPagedIterable ax = positiveBizClient.query(q); - List collect = ax.stream().map(s->{ - return BasePaymentInfo.builder() -// .brokerPspId() -// .pspId() -// .nodeId() -// .channelId() -// .brokerPspId() - .noticeNumber(s.getDebtorPosition()!=null?s.getDebtorPosition().getNoticeNumber():"").build(); -// .organizationFiscalCode(); + List re = EventEntity.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); + CosmosPagedIterable pos = positiveBizClient.findEvents(organizationFiscalCode, noticeNumber,dateFrom,dateTo); + CosmosPagedIterable neg = negativeBizClient.findEvents(organizationFiscalCode, noticeNumber,dateFrom,dateTo); + + log.infov("found {0} re events\n" + + "found {1} pos biz\n" + + "fount {2} neg biz",re.size(),pos.stream().count(),neg.stream().count()); + + String serviceIdentifier; + if(re.size()>0){ + EventEntity lastRe = re.get(re.size()-1); + serviceIdentifier = lastRe.getServiceIdentifier(); + } else { + serviceIdentifier = null; + } + + List collect = pos.stream().map(s->{ + return PaymentInfo.builder() + .brokerPspId(s.getCreditor().getIdBrokerPA()) + .pspId(s.getPsp().getIdPsp()) + .nodeId(serviceIdentifier) + .channelId(s.getPsp().getIdChannel()) + .brokerPspId(s.getPsp().getIdBrokerPsp()) + .insertedTimestamp(s.getPaymentInfo().getPaymentDateTime()) + .paymentToken(s.getPaymentInfo().getPaymentToken()) + .noticeNumber(s.getDebtorPosition()!=null?s.getDebtorPosition().getNoticeNumber():null) + .organizationFiscalCode(organizationFiscalCode) + .build(); }).collect(Collectors.toList()); return TransactionResponse.builder() + .dateFrom(dateFrom) + .dateTo(dateTo) .payments(collect) .build(); @@ -85,8 +84,8 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, LocalDate dateTo){ List list = EventEntity.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); - List biz = PositiveBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); - List neg = NegativeBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); +// List biz = PositiveBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); +// List neg = NegativeBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); return TransactionResponse.builder() .build(); @@ -125,10 +124,10 @@ public TransactionResponse getAttemptByIUVCCP(String organizationFiscalCode, Str */ private DateRequest verifyDate(LocalDate dateFrom, LocalDate dateTo) { if (dateFrom == null && dateTo != null || dateFrom != null && dateTo == null) { - throw new AppException(AppError.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from and date to must be both defined"); + throw new AppException(AppErrorCodeMessageEnum.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from and date to must be both defined"); } else if (dateFrom != null && dateTo != null && dateFrom.isAfter(dateTo)) { - throw new AppException(AppError.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from must be before date to"); + throw new AppException(AppErrorCodeMessageEnum.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from must be before date to"); } if (dateFrom == null && dateTo == null) { dateFrom = LocalDate.now(); diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/AppConstant.java b/src/main/java/it/gov/pagopa/nodetsworker/util/AppConstant.java new file mode 100644 index 0000000..89b041b --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/AppConstant.java @@ -0,0 +1,16 @@ +package it.gov.pagopa.nodetsworker.util; + +public class AppConstant { + + public static final String SERVICE_CODE_APP = "FDR"; + + public static final String PSP_ID = "pspId"; + public static final String EC_ID = "ecId"; + public static final String FLOW_NAME = "flowName"; + public static final String INDEXES = "indexes"; + public static final String INTERNAL_READ = "internalRead"; + + private AppConstant() { + throw new IllegalStateException("Constants class"); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/AppMessageUtil.java b/src/main/java/it/gov/pagopa/nodetsworker/util/AppMessageUtil.java new file mode 100644 index 0000000..2fd942e --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/AppMessageUtil.java @@ -0,0 +1,41 @@ +package it.gov.pagopa.nodetsworker.util; + +import java.text.MessageFormat; +import java.util.Locale; +import java.util.Optional; +import java.util.ResourceBundle; + +public class AppMessageUtil { + + private static final String MESSAGES = "messages"; + + private AppMessageUtil() { + throw new IllegalStateException("Utility class"); + } + + private static ResourceBundle getBundle(Locale locale) { + return Optional.ofNullable(locale) + .map(localez -> ResourceBundle.getBundle(MESSAGES, localez)) + .orElse(ResourceBundle.getBundle(MESSAGES)); + } + + public static String getMessage(String messageKey, Object... messageArguments) { + return getMessage(messageKey, null, messageArguments); + } + + public static String getMessage(String messageKey, Locale locale, Object... messageArguments) { + return MessageFormat.format(getMessage(messageKey, locale), messageArguments); + } + + public static String getMessage(String messageKey) { + return getMessage(messageKey, (Locale) null); + } + + public static String getMessage(String messageKey, Locale locale) { + try { + return getBundle(locale).getString(messageKey); + } catch (Exception e) { + return messageKey; + } + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 36d0a38..e288c26 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -65,17 +65,12 @@ quarkus.smallrye-openapi.servers=\\$\{host\}/tenchinal-support/api/v1 - APIM %test.quarkus.mongodb.connection-string=${mockserver.mongodb.connection-string} quarkus.mongodb.events.connection-string=${MONGODB_EVENTS_CONNECTION_STRING} -%dev.quarkus.mongodb.events.connection-string = ${DEV_MONGODB_EVENTS_CONNECTION_STRING} quarkus.mongodb.events.database=nodo_re -biz.endpoint=${MONGODB_BIZ_CONNECTION_STRING} -biz.key=${MONGODB_BIZ_ACCOUNT_KEY} -%dev.biz.endpoint=https://pagopa-d-weu-bizevents-ds-cosmos-account.documents.azure.com:443/ -%dev.biz.key=${DEV_BIZ_KEY} -bizneg.endpoint=${MONGODB_NEG_BIZ_CONNECTION_STRING} -bizneg.key=${MONGODB_NEG_BIZ_ACCOUNT_KEY} -%dev.bizneg.endpoint=https://pagopa-d-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/ -%dev.bizneg.key=${DEV_BIZNEG_KEY} +biz.endpoint=${COSMOS_BIZ_ENDPOINT} +biz.key=${COSMOS_BIZ_KEY} +bizneg.endpoint=${COSMOS_NEG_BIZ_ENDPOINT} +bizneg.key=${COSMOS_NEG_BIZ_KEY} ################### ## ADAPTER API CONFIG CACHE From 31d2fc8f6fca6a11c6bdfa8514e02febecae8fd9 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Mon, 3 Jul 2023 16:28:17 +0200 Subject: [PATCH 03/29] wip --- pom.xml | 5 + .../models/BasePaymentAttemptInfo.java | 7 +- .../nodetsworker/models/BasePaymentInfo.java | 7 +- .../models/PaymentAttemptInfo.java | 13 +- .../repository/CosmosBizEventClient.java | 105 ++++++- .../repository/CosmosNegBizEventClient.java | 71 ++++- .../repository/ReTableService.java | 103 +++++++ .../nodetsworker/repository/model/Count.java | 14 + .../repository/{ => model}/Creditor.java | 2 +- .../{ => model}/DebtorPosition.java | 2 +- .../repository/{ => model}/EventEntity.java | 24 +- .../{ => model}/NegativeBizEvent.java | 6 +- .../{ => model}/NegativePaymentInfo.java | 4 +- .../{ => model}/NegativeTransfer.java | 2 +- .../repository/{ => model}/PaymentInfo.java | 2 +- .../{ => model}/PositiveBizEvent.java | 2 +- .../repository/{ => model}/Psp.java | 2 +- .../repository/{ => model}/Subject.java | 2 +- .../repository/{ => model}/Transfer.java | 2 +- .../resources/WorkerResource.java | 4 +- .../nodetsworker/service/WorkerService.java | 283 ++++++++++++++---- .../service/mapper/EventMapper.java | 2 +- .../pagopa/nodetsworker/util/StatusUtil.java | 49 +++ src/main/resources/application.properties | 5 + 24 files changed, 610 insertions(+), 108 deletions(-) create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/Creditor.java (86%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/DebtorPosition.java (84%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/EventEntity.java (59%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/NegativeBizEvent.java (68%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/NegativePaymentInfo.java (86%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/NegativeTransfer.java (90%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/PaymentInfo.java (94%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/PositiveBizEvent.java (93%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/Psp.java (88%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/Subject.java (90%) rename src/main/java/it/gov/pagopa/nodetsworker/repository/{ => model}/Transfer.java (91%) create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java diff --git a/pom.xml b/pom.xml index b1293e3..b150021 100644 --- a/pom.xml +++ b/pom.xml @@ -121,6 +121,11 @@ quarkus-mockserver-test 1.0.0 + + com.azure + azure-data-tables + 12.3.12 + org.testcontainers junit-jupiter diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java index 57279a0..3d43f18 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java @@ -1,14 +1,12 @@ package it.gov.pagopa.nodetsworker.models; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; -import java.time.LocalDate; -import java.time.LocalDateTime; +import java.math.BigDecimal; @Getter @Setter @@ -20,6 +18,5 @@ public class BasePaymentAttemptInfo extends BasePaymentInfo { private String brokerOrganizationId; private String stationId; private String paymentMethod; - private Double amount; - private Boolean flagIO; + private BigDecimal amount; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java index 2c3dac0..db822bb 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java @@ -6,8 +6,6 @@ import lombok.Setter; import lombok.experimental.SuperBuilder; -import java.time.LocalDateTime; - @Getter @Setter @NoArgsConstructor @@ -17,13 +15,14 @@ public class BasePaymentInfo { private String organizationFiscalCode; private String noticeNumber; + private String iuv; private String pspId; private String brokerPspId; private String channelId; private String outcome; private String status; - private LocalDateTime insertedTimestamp; - private LocalDateTime updatedTimestamp; + private String insertedTimestamp; + private String updatedTimestamp; private Boolean isOldPaymentModel; private String nodeId; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java index c989406..098c5b3 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java @@ -6,6 +6,7 @@ import lombok.Setter; import lombok.experimental.SuperBuilder; +import java.math.BigDecimal; import java.time.LocalDate; @Getter @@ -16,18 +17,14 @@ public class PaymentAttemptInfo extends BasePaymentAttemptInfo { private String paymentToken; - private Boolean isOldPaymentModel = false; - private Boolean pmReceipt; private String paymentMethod; private String paymentChannel; - private Boolean flagPayPal; private Long stationVersion; - private Long fee; - private Long feeSpo; - private Long feeOrganization; + private BigDecimal fee; + private BigDecimal feeOrganization; private String bundleId; private String bundleOrganizationId; - private LocalDate applicationDate; - private LocalDate transferDate; + private String applicationDate; + private String transferDate; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java index 20bb202..2186114 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -7,6 +7,9 @@ import com.azure.cosmos.models.SqlParameter; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; +import it.gov.pagopa.nodetsworker.repository.model.Count; +import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; +import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -17,6 +20,7 @@ import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; +import java.util.Optional; @ApplicationScoped @Startup @@ -40,24 +44,109 @@ private CosmosPagedIterable query(SqlQuerySpec query){ CosmosContainer container = client.getDatabase(dbname).getContainer(tablename); return container.queryItems(query, new CosmosQueryRequestOptions(), PositiveBizEvent.class); } + private CosmosPagedIterable queryCount(SqlQuerySpec query){ + log.info("executing query:"+query.getQueryText()); + CosmosClient client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); + CosmosContainer container = client.getDatabase(dbname).getContainer(tablename); + return container.queryItems(query, new CosmosQueryRequestOptions(), Count.class); + } - public CosmosPagedIterable findEvents(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom,LocalDate dateTo){ + public CosmosPagedIterable findEventsByCiAndNNAndToken(String organizationFiscalCode, String noticeNumber,String paymentToken, LocalDate dateFrom, LocalDate dateTo){ List paramList = new ArrayList(); paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@paymentToken", paymentToken)); + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.paymentInfo.paymentToken = @paymentToken" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return query(q); + } + + public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@iuv", iuv)); + paramList.add(new SqlParameter("@ccp", ccp)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where " + - "c.creditor.idPA = @organizationFiscalCode " + - "and c.debtorPosition.noticeNumber != null " + - "and c.debtorPosition.noticeNumber = @noticeNumber " + - "and c.paymentInfo != null " + - "and c.paymentInfo.paymentDateTime > @from " + - "and c.paymentInfo.paymentDateTime < @to" + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.iuv = @iuv" + + " and c.paymentInfo.paymentToken = @ccp" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" ) .setParameters(paramList); return query(q); } + public CosmosPagedIterable findEvents(String organizationFiscalCode, String noticeNumber, Optional paymentToken, Optional iuv, LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + paymentToken.ifPresent(pt->{ + paramList.add(new SqlParameter("@paymentToken", pt)); + }); + iuv.ifPresent(pt->{ + paramList.add(new SqlParameter("@iuv", pt)); + }); + + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" + + (paymentToken.isPresent()? " and c.paymentInfo.paymentToken = @paymentToken" : "") + + (paymentToken.isPresent()? " and c.paymentInfo.iuv = @iuv" : "") + ) + .setParameters(paramList); + return query(q); + } + + public CosmosPagedIterable countEventsByCiAndNN(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + + + SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return queryCount(q); + } + + public CosmosPagedIterable countEventsByCiAndIUV(String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@iuv", iuv)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + + + SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.iuv = @iuv" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return queryCount(q); + } + } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java index bdef946..e03ae15 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java @@ -7,6 +7,7 @@ import com.azure.cosmos.models.SqlParameter; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; +import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -17,6 +18,7 @@ import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; +import java.util.Optional; @ApplicationScoped @Startup @@ -41,24 +43,77 @@ private CosmosPagedIterable query(SqlQuerySpec query){ return container.queryItems(query, new CosmosQueryRequestOptions(), NegativeBizEvent.class); } - public CosmosPagedIterable findEvents(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ + public CosmosPagedIterable findEventsByCiAndNN(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ List paramList = new ArrayList(); paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return query(q); + } + public CosmosPagedIterable findEventsByCiAndNNAndToken(String organizationFiscalCode, String noticeNumber,String paymentToken, LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@paymentToken", paymentToken)); + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.paymentInfo.paymentToken = @paymentToken" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return query(q); + } - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where " + - "c.creditor.idPA = @organizationFiscalCode " + - "and c.debtorPosition.noticeNumber != null " + - "and c.debtorPosition.noticeNumber = @noticeNumber " + - "and c.paymentInfo != null " + - "and c.paymentInfo.paymentDateTime > @from " + - "and c.paymentInfo.paymentDateTime < @to" + public CosmosPagedIterable findEventsByCiAndIUV(String organizationFiscalCode,String iuv, LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@iuv", iuv)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.iuv = @iuv" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" + ) + .setParameters(paramList); + return query(q); + } + + public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String organizationFiscalCode,String iuv, String ccp,LocalDate dateFrom, LocalDate dateTo){ + List paramList = new ArrayList(); + paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); + paramList.add(new SqlParameter("@iuv", iuv)); + paramList.add(new SqlParameter("@ccp", ccp)); + paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); + paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.iuv = @iuv" + + " and c.paymentInfo.paymentToken = @ccp" + + " and c.paymentInfo.paymentDateTime > @from" + + " and c.paymentInfo.paymentDateTime < @to" ) .setParameters(paramList); return query(q); } + public CosmosPagedIterable findEventsByCiAndIUVAndToken(String organizationFiscalCode,String iuv, String paymentToken,LocalDate dateFrom, LocalDate dateTo){ + return findEventsByCiAndIUVAndCCP(organizationFiscalCode,iuv,paymentToken,dateFrom,dateTo); + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java new file mode 100644 index 0000000..1d7e273 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java @@ -0,0 +1,103 @@ +package it.gov.pagopa.nodetsworker.repository; + +import com.azure.data.tables.TableClient; +import com.azure.data.tables.TableServiceClient; +import com.azure.data.tables.TableServiceClientBuilder; +import com.azure.data.tables.models.ListEntitiesOptions; +import com.azure.data.tables.models.TableEntity; +import it.gov.pagopa.nodetsworker.repository.model.EventEntity; +import jakarta.enterprise.context.ApplicationScoped; +import org.eclipse.microprofile.config.inject.ConfigProperty; + +import java.time.LocalDate; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +// @Startup +@ApplicationScoped +// @UnlessBuildProfile("test") +public class ReTableService { + + @ConfigProperty(name = "re-table-storage.connection-string") + String connString; + + @ConfigProperty(name = "re-table-storage.table-name") + String tableName; + + private TableServiceClient tableServiceClient = null; + + public TableClient getTableClient(){ + if(tableServiceClient==null){ + tableServiceClient = new TableServiceClientBuilder().connectionString(connString).buildClient(); + } + return tableServiceClient.getTableClient(tableName); + } + + private List propertiesToSelect = Arrays.asList( + "serviceIdentifier", + "status", + "psp", + "canale", + "noticeNumber", + "paymentToken", + "idDominio", + "iuv", + "ccp", + "insertedTimestamp" + ); + + + private EventEntity tableEntityToEventEntity(TableEntity e){ + return EventEntity.builder() + .canale(getString(e.getProperty("canale"))) + .iuv(getString(e.getProperty("iuv"))) + .ccp(getString(e.getProperty("ccp"))) + .noticeNumber(getString(e.getProperty("noticeNumber"))) + .paymentToken(getString(e.getProperty("paymentToken"))) + .idDominio(getString(e.getProperty("idDominio"))) + .serviceIdentifier(getString(e.getProperty("serviceIdentifier"))) + .insertedTimestamp(getString(e.getProperty("insertedTimestamp"))) + .psp(getString(e.getProperty("psp"))) + .status(getString(e.getProperty("status"))) + .uniqueId(getString(e.getProperty("uniqueId"))) + .build(); + } + + public List findReByCiAndNN(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber){ + ListEntitiesOptions options = new ListEntitiesOptions() + .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and noticeNumber eq '%s' and esito eq 'CAMBIO_STATO'", + datefrom,dateTo, creditorInstitution, noticeNumber)) + .setSelect(propertiesToSelect); + return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + } + public List findReByCiAndIUV(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv){ + ListEntitiesOptions options = new ListEntitiesOptions() + .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and iuv eq '%s' and esito eq 'CAMBIO_STATO'", + datefrom,dateTo, creditorInstitution, iuv)) + .setSelect(propertiesToSelect); + return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + } + + public List findReByCiAndNNAndToken(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber, String paymentToken){ + ListEntitiesOptions options = new ListEntitiesOptions() + .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and noticeNumber eq '%s' and paymentToken eq '%s' and esito eq 'CAMBIO_STATO'", + datefrom,dateTo, creditorInstitution, noticeNumber,paymentToken)) + .setSelect(propertiesToSelect); + return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + } + + public List findReByCiAndIUVAndCCP(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv,String ccp){ + ListEntitiesOptions options = new ListEntitiesOptions() + .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and iuv eq '%s' and ccp eq '%s' and esito eq 'CAMBIO_STATO'", + datefrom,dateTo, creditorInstitution, iuv,ccp)) + .setSelect(propertiesToSelect); + return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + } + + private String getString(Object o){ + if(o==null) return null; + return (String)o; + } + +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java new file mode 100644 index 0000000..2272212 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java @@ -0,0 +1,14 @@ +package it.gov.pagopa.nodetsworker.repository.model; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Count { + Long count; +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Creditor.java similarity index 86% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/Creditor.java index f36afef..8513da2 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Creditor.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Creditor.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/DebtorPosition.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/DebtorPosition.java similarity index 84% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/DebtorPosition.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/DebtorPosition.java index b3600fd..7492077 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/DebtorPosition.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/DebtorPosition.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java similarity index 59% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java index a98c4ba..11800d3 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/EventEntity.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java @@ -1,9 +1,10 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import io.quarkus.mongodb.panache.PanacheMongoEntity; import io.quarkus.mongodb.panache.PanacheQuery; import io.quarkus.mongodb.panache.common.MongoEntity; import io.quarkus.panache.common.Parameters; +import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; @@ -11,6 +12,7 @@ @Data @EqualsAndHashCode(callSuper = true) +@Builder @MongoEntity(collection = "events", clientName = "events") public class EventEntity extends PanacheMongoEntity { @@ -50,12 +52,26 @@ public class EventEntity extends PanacheMongoEntity { public static PanacheQuery findByCIAndNAV( String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO'", + return find("idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and status like 'payment_'", + Parameters.with("idDominio", creditorInstitution).and("noticeNumber",nav)) + .project(EventEntity.class); + } + public static PanacheQuery findByCIAndNAVAndToken( + String creditorInstitution, String nav,String paymentToken, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and status like 'payment_'", Parameters.with("idDominio", creditorInstitution).and("noticeNumber",nav)) .project(EventEntity.class); } public static PanacheQuery findByCIAndIUV( - String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio", creditorInstitution).project(EventEntity.class); + String creditorInstitution, String iuv, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like 'payment_'", + Parameters.with("idDominio", creditorInstitution).and("iuv",iuv)) + .project(EventEntity.class); + } + public static PanacheQuery findByCIAndIUVAndCCP( + String creditorInstitution, String iuv,String ccp, LocalDate dateFrom, LocalDate dateTo) { + return find("idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like 'payment_'", + Parameters.with("idDominio", creditorInstitution).and("iuv",iuv)) + .project(EventEntity.class); } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java similarity index 68% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java index b4e2f38..64f2176 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java @@ -1,12 +1,8 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; -import io.quarkus.mongodb.panache.PanacheMongoEntity; -import io.quarkus.mongodb.panache.PanacheQuery; -import io.quarkus.mongodb.panache.common.MongoEntity; import lombok.Builder; import lombok.Data; -import java.time.LocalDate; import java.util.List; @Data diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativePaymentInfo.java similarity index 86% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativePaymentInfo.java index 6aae1ef..ff2821d 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativePaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativePaymentInfo.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import java.math.BigDecimal; import java.time.LocalDate; @@ -13,7 +13,7 @@ @Builder @NoArgsConstructor @AllArgsConstructor -class NegativePaymentInfo { +public class NegativePaymentInfo { private LocalDateTime paymentDateTime; private LocalDate dueDate; private String paymentToken; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeTransfer.java similarity index 90% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeTransfer.java index 4250d27..73b830f 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/NegativeTransfer.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeTransfer.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import java.math.BigDecimal; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PaymentInfo.java similarity index 94% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/PaymentInfo.java index 6642271..13e0c92 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/PaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PaymentInfo.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import java.math.BigDecimal; import java.time.LocalDate; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java similarity index 93% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java index f5d63a7..93162a6 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/PositiveBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.quarkus.mongodb.panache.common.MongoEntity; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Psp.java similarity index 88% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/Psp.java index 47a9b85..e883209 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Psp.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Psp.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Subject.java similarity index 90% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/Subject.java index ffda48d..68b07b8 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Subject.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Subject.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Transfer.java similarity index 91% rename from src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java rename to src/main/java/it/gov/pagopa/nodetsworker/repository/model/Transfer.java index da59142..24c5c53 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/Transfer.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Transfer.java @@ -1,4 +1,4 @@ -package it.gov.pagopa.nodetsworker.repository; +package it.gov.pagopa.nodetsworker.repository.model; import java.math.BigDecimal; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java index 9713811..92c9fb8 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java @@ -92,7 +92,7 @@ public Response useCaseSP04_byIUV_PaymentToken( @QueryParam("dateFrom") LocalDate dateFrom, @QueryParam("dateTo") LocalDate dateTo ) { - return Response.ok(workerService.getAttemptByIUVPaymentToken(organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)).build(); + return Response.ok(workerService.getInfoByNoticeNumberAndPaymentToken(organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)).build(); } @APIResponses(value = { @@ -109,6 +109,6 @@ public Response useCaseSP04_byIUV_CCP( @QueryParam("dateFrom") LocalDate dateFrom, @QueryParam("dateTo") LocalDate dateTo ) { - return Response.ok(workerService.getAttemptByIUVCCP(organizationFiscalCode, iuv, ccp, dateFrom, dateTo)).build(); + return Response.ok(workerService.getAttemptByIUVAndCCP(organizationFiscalCode, iuv, ccp, dateFrom, dateTo)).build(); } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index 80cfc37..dddb821 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -1,30 +1,33 @@ package it.gov.pagopa.nodetsworker.service; -import com.azure.cosmos.models.SqlParameter; -import com.azure.cosmos.models.SqlQuerySpec; -import com.azure.cosmos.util.CosmosPagedIterable; import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageEnum; import it.gov.pagopa.nodetsworker.exceptions.AppException; -import it.gov.pagopa.nodetsworker.models.BasePaymentInfo; -import it.gov.pagopa.nodetsworker.models.DateRequest; -import it.gov.pagopa.nodetsworker.models.PaymentInfo; -import it.gov.pagopa.nodetsworker.models.TransactionResponse; -import it.gov.pagopa.nodetsworker.repository.*; +import it.gov.pagopa.nodetsworker.models.*; +import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; +import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; +import it.gov.pagopa.nodetsworker.repository.ReTableService; +import it.gov.pagopa.nodetsworker.repository.model.Count; +import it.gov.pagopa.nodetsworker.repository.model.EventEntity; +import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; +import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; import it.gov.pagopa.nodetsworker.service.mapper.EventMapper; +import it.gov.pagopa.nodetsworker.util.StatusUtil; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; @ApplicationScoped public class WorkerService { + private static String outcomeOK = "OK"; + private static String outcomeKO = "KO"; + @Inject Logger log; @@ -36,40 +39,107 @@ public class WorkerService { @Inject CosmosNegBizEventClient negativeBizClient; + @Inject + ReTableService reTableService; + + private PaymentInfo eventToPaymentInfo(EventEntity ee){ + return PaymentInfo.builder() + .pspId(ee.getPsp()) + .nodeId(ee.getServiceIdentifier()) + .channelId(ee.getCanale()) + .brokerPspId(null)//todo recuperare da configurazione + .insertedTimestamp(ee.getInsertedTimestamp()) + .paymentToken(ee.getPaymentToken()) + .noticeNumber(ee.getNoticeNumber()) + .iuv(ee.getIuv()) + .organizationFiscalCode(ee.getIdDominio()) + .status(StatusUtil.statoByReStatus(ee.getStatus())) + .build(); + } + + private PaymentAttemptInfo eventToPaymentAttemptInfo(EventEntity ee){ + return PaymentAttemptInfo.builder() + .pspId(ee.getPsp()) + .nodeId(ee.getServiceIdentifier()) + .channelId(ee.getCanale()) + .brokerPspId(null)//todo recuperare da configurazione + .insertedTimestamp(ee.getInsertedTimestamp()) + .paymentToken(ee.getPaymentToken()) + .noticeNumber(ee.getNoticeNumber()) + .iuv(ee.getIuv()) + .organizationFiscalCode(ee.getIdDominio()) + .status(StatusUtil.statoByReStatus(ee.getStatus())) + .stationId(ee.getStazione()) + .build(); + } + + private void enrichPaymentAttemptInfo(PaymentAttemptInfo pai, PositiveBizEvent pbe){ + pai.setPaymentToken(pbe.getPaymentInfo().getPaymentToken()); + pai.setIsOldPaymentModel(pbe.getDebtorPosition().getModelType().equals("1")); + pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); + pai.setStationVersion(null);//todo recuperare da configurazione + pai.setAmount(pbe.getPaymentInfo().getAmount()); + pai.setFee(pbe.getPaymentInfo().getFee()); + pai.setFeeOrganization(pbe.getPaymentInfo().getPrimaryCiIncurredFee()); + pai.setPaymentMethod(pbe.getPaymentInfo().getPaymentMethod()); + pai.setPmReceipt(pbe.getTransactionDetails()!=null); + pai.setPaymentChannel(pbe.getPaymentInfo().getTouchpoint()); + pai.setBundleId(pbe.getPaymentInfo().getIdBundle()); + pai.setBundleOrganizationId(pbe.getPaymentInfo().getIdCiBundle()); + pai.setApplicationDate(pbe.getPaymentInfo().getApplicationDate()); + pai.setTransferDate(pbe.getPaymentInfo().getTransferDate()); + } + + private void enrichPaymentAttemptInfo(PaymentAttemptInfo pai, NegativeBizEvent nbe){ + pai.setIsOldPaymentModel(nbe.getDebtorPosition().getModelType().equals("1")); + pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); + pai.setStationVersion(null);//todo recuperare da configurazione + pai.setAmount(nbe.getPaymentInfo().getAmount()); + pai.setPaymentMethod(nbe.getPaymentInfo().getPaymentMethod()); + pai.setPmReceipt(nbe.getTransactionDetails()!=null); + pai.setPaymentChannel(nbe.getPaymentInfo().getTouchpoint()); + } + public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + List reStorageEvents = reTableService.findReByCiAndNN(dateFrom, dateTo, organizationFiscalCode, noticeNumber); - List re = EventEntity.findByCIAndNAV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); - CosmosPagedIterable pos = positiveBizClient.findEvents(organizationFiscalCode, noticeNumber,dateFrom,dateTo); - CosmosPagedIterable neg = negativeBizClient.findEvents(organizationFiscalCode, noticeNumber,dateFrom,dateTo); - - log.infov("found {0} re events\n" + - "found {1} pos biz\n" + - "fount {2} neg biz",re.size(),pos.stream().count(),neg.stream().count()); + Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); - String serviceIdentifier; - if(re.size()>0){ - EventEntity lastRe = re.get(re.size()-1); - serviceIdentifier = lastRe.getServiceIdentifier(); - } else { - serviceIdentifier = null; - } + List collect = reGroups.keySet().stream().map(gkey->{ + List events = reGroups.get(gkey); + EventEntity lastEvent = events.get(events.size()-1); + String outcome = null; - List collect = pos.stream().map(s->{ - return PaymentInfo.builder() - .brokerPspId(s.getCreditor().getIdBrokerPA()) - .pspId(s.getPsp().getIdPsp()) - .nodeId(serviceIdentifier) - .channelId(s.getPsp().getIdChannel()) - .brokerPspId(s.getPsp().getIdBrokerPsp()) - .insertedTimestamp(s.getPaymentInfo().getPaymentDateTime()) - .paymentToken(s.getPaymentInfo().getPaymentToken()) - .noticeNumber(s.getDebtorPosition()!=null?s.getDebtorPosition().getNoticeNumber():null) - .organizationFiscalCode(organizationFiscalCode) - .build(); + Optional pos = positiveBizClient.countEventsByCiAndNN( + lastEvent.getIdDominio(), + lastEvent.getNoticeNumber(), + dateFrom, + dateTo + ).stream().findFirst(); + if(pos.isPresent() && pos.get().getCount()>0){ + outcome = outcomeOK; + }else{ + Optional neg = negativeBizClient.findEventsByCiAndNN( + lastEvent.getIdDominio(), + lastEvent.getNoticeNumber(), + dateFrom, + dateTo + ).stream().findFirst(); + if(neg.isPresent()){ + if(!neg.get().getReAwakable()){ + outcome = outcomeKO; + } + } + } + PaymentInfo pi = eventToPaymentInfo(lastEvent); + pi.setOutcome(outcome); + return pi; }).collect(Collectors.toList()); + return TransactionResponse.builder() .dateFrom(dateFrom) .dateTo(dateTo) @@ -79,41 +149,148 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, } public TransactionResponse getInfoByIUV(String organizationFiscalCode, - String noticeNumber, + String iuv, LocalDate dateFrom, LocalDate dateTo){ + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + List reStorageEvents = reTableService.findReByCiAndIUV(dateFrom, dateTo, organizationFiscalCode, iuv); + + Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); + + List collect = reGroups.keySet().stream().map(gkey->{ + List events = reGroups.get(gkey); + EventEntity lastEvent = events.get(events.size()-1); + String outcome = null; - List list = EventEntity.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); -// List biz = PositiveBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); -// List neg = NegativeBizEvent.findByCIAndIUV(organizationFiscalCode, noticeNumber,dateFrom,dateTo).list(); + Optional pos = positiveBizClient.countEventsByCiAndIUV( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + dateFrom, + dateTo + ).stream().findFirst(); + if(pos.isPresent() && pos.get().getCount()>0){ + outcome = outcomeOK; + }else{ + Optional neg = negativeBizClient.findEventsByCiAndIUV( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + dateFrom, + dateTo + ).stream().findFirst(); + if(neg.isPresent()){ + if(!neg.get().getReAwakable()){ + outcome = outcomeKO; + } + } + } + + PaymentInfo pi = eventToPaymentInfo(lastEvent); + pi.setOutcome(outcome); + return pi; + }).collect(Collectors.toList()); return TransactionResponse.builder() + .dateFrom(dateFrom) + .dateTo(dateTo) + .payments(collect) .build(); } - public TransactionResponse getAttemptByIUVPaymentToken(String organizationFiscalCode, String iuv, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { + public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizationFiscalCode, String noticeNumber, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); + List reStorageEvents = reTableService.findReByCiAndNNAndToken(dateFrom, dateTo, organizationFiscalCode, noticeNumber,paymentToken); -// List payments = getPaymentPositionListByIUVPaymentToken(organizationFiscalCode, iuv, paymentToken, dateRequest.getFrom(), dateRequest.getTo()); -// List paymentAttemptInfoList = enrichPaymentAttemptPositionList(payments, dateRequest.getFrom(), dateRequest.getTo()); + Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); + List collect = reGroups.keySet().stream().map(gkey->{ + List events = reGroups.get(gkey); + EventEntity lastEvent = events.get(events.size()-1); + PaymentAttemptInfo pi = eventToPaymentAttemptInfo(lastEvent); + String outcome = null; + + Optional pos = positiveBizClient.findEventsByCiAndIUVAndCCP( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + lastEvent.getCcp(), + dateFrom, + dateTo + ).stream().findFirst(); + if(pos.isPresent()){ + outcome = outcomeOK; + pi.setOutcome(outcome); + enrichPaymentAttemptInfo(pi,pos.get()); + }else{ + Optional neg = negativeBizClient.findEventsByCiAndNNAndToken( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + lastEvent.getPaymentToken(), + dateFrom, + dateTo + ).stream().findFirst(); + if(neg.isPresent()){ + if(!neg.get().getReAwakable()){ + outcome = outcomeKO; + } + enrichPaymentAttemptInfo(pi,neg.get()); + } + } + return pi; + }).collect(Collectors.toList()); return TransactionResponse.builder() - .dateFrom(dateRequest.getFrom()) - .dateTo(dateRequest.getTo()) -// .payments(paymentAttemptInfoList) + .dateFrom(dateFrom) + .dateTo(dateTo) + .payments(collect) .build(); } - public TransactionResponse getAttemptByIUVCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { + + + + public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); + List reStorageEvents = reTableService.findReByCiAndIUVAndCCP(dateFrom, dateTo, organizationFiscalCode, iuv,ccp); -// List rptList = getRPTListByIUVCCP(organizationFiscalCode, iuv, ccp, dateRequest.getFrom(), dateRequest.getTo()); -// List rptAttemptInfoList = enrichRPTAttemptList(rptList, dateRequest.getFrom(), dateRequest.getTo()); + Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); + + List collect = reGroups.keySet().stream().map(gkey->{ + List events = reGroups.get(gkey); + EventEntity lastEvent = events.get(events.size()-1); + PaymentAttemptInfo pi = eventToPaymentAttemptInfo(lastEvent); + String outcome = null; + + Optional pos = positiveBizClient.findEventsByCiAndIUVAndCCP( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + lastEvent.getCcp(), + dateFrom, + dateTo + ).stream().findFirst(); + if(pos.isPresent()){ + outcome = outcomeOK; + pi.setOutcome(outcome); + enrichPaymentAttemptInfo(pi,pos.get()); + }else{ + Optional neg = negativeBizClient.findEventsByCiAndIUVAndCCP( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + lastEvent.getPaymentToken(), + dateFrom, + dateTo + ).stream().findFirst(); + if(neg.isPresent()){ + if(!neg.get().getReAwakable()){ + outcome = outcomeKO; + } + enrichPaymentAttemptInfo(pi,neg.get()); + } + } + return pi; + }).collect(Collectors.toList()); return TransactionResponse.builder() - .dateFrom(dateRequest.getFrom()) - .dateTo(dateRequest.getTo()) -// .payments(rptAttemptInfoList) + .dateFrom(dateFrom) + .dateTo(dateTo) + .payments(collect) .build(); } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java index f99caff..1398274 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java @@ -1,6 +1,6 @@ package it.gov.pagopa.nodetsworker.service.mapper; -import it.gov.pagopa.nodetsworker.repository.EventEntity; +import it.gov.pagopa.nodetsworker.repository.model.EventEntity; import it.gov.pagopa.nodetsworker.service.dto.EventDto; import org.mapstruct.Mapper; import org.mapstruct.MappingConstants.ComponentModel; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java b/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java new file mode 100644 index 0000000..989366d --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java @@ -0,0 +1,49 @@ +package it.gov.pagopa.nodetsworker.util; + +public class StatusUtil { + + public static String statoByReStatus(String reStatus){ + switch (reStatus) { + case "payment_PAID": + case "payment_PAID_NORPT": + case "payment_NOTICE_GENERATED": + case "payment_NOTICE_STORED": + case "payment_NOTICE_SENT": + case "payment_NOTIFIED": + case "RT_ACCETTATA_PA": + return "completed"; + case "payment_CANCELLED": + case "payment_CANCELLED_NORPT": + case "payment_PAYING": + case "payment_PAYING_RPT": + case "RPT_RISOLTA_OK": + case "RPT_RISOLTA_KO": + case "RPT_RICEVUTA_NODO": + case "RPT_ACCETTATA_NODO": + case "RPT_ERRORE_INVIO_A_PSP": + case "RPT_INVIATA_A_PSP": + case "RPT_ACCETTATA_PSP": + case "RT_GENERATA_NODO": + case "RT_RICEVUTA_NODO": + case "RT_RIFIUTATA_NODO": + case "RT_ACCETTATA_NODO": + case "RT_ESITO_SCONOSCIUTO_PA": + case "RT_INVIATA_PA": + case "RPT_ESITO_SCONOSCIUTO_PSP": + case "RPT_PARCHEGGIATA_NODO": + case "RPT_PARCHEGGIATA_NODO_MOD3": + case "RT_ERRORE_INVIO_A_PA": + return "in progress"; + case "RPT_RIFIUTATA_PSP": + case "RT_RIFIUTATA_PA": + case "RPT_RIFIUTATA_NODO": + case "payment_FAILED": + case "payment_FAILED_NORPT": + return "failed"; + + + + } + return null; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e288c26..5b964a3 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -71,6 +71,8 @@ biz.endpoint=${COSMOS_BIZ_ENDPOINT} biz.key=${COSMOS_BIZ_KEY} bizneg.endpoint=${COSMOS_NEG_BIZ_ENDPOINT} bizneg.key=${COSMOS_NEG_BIZ_KEY} +re-table-storage.table-name=events +re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING} ################### ## ADAPTER API CONFIG CACHE @@ -115,3 +117,6 @@ operations.filter=".*" %test.adapter.api_config_cache.url=${quarkus.mockserver.endpoint} adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:${quarkus.mockserver.endpoint}} + + +quarkus.test.continuous-testing=disabled From d8595e06a47caf50ff94b70731a268d5eedcff87 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Mon, 3 Jul 2023 17:05:06 +0200 Subject: [PATCH 04/29] wip --- .../gov/pagopa/nodetsworker/AppStartup.java | 30 + .../it/gov/pagopa/nodetsworker/Config.java | 85 + .../nodetsworker/service/WorkerService.java | 46 +- src/main/openapi/api_config_cache.json | 1221 ++++++++++++ src/main/resources/application.properties | 16 +- src/test/resources/mockserver.properties | 3 + src/test/resources/mockserver/cache.json | 1701 +++++++++++++++++ 7 files changed, 3074 insertions(+), 28 deletions(-) create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/Config.java create mode 100644 src/main/openapi/api_config_cache.json create mode 100644 src/test/resources/mockserver.properties create mode 100644 src/test/resources/mockserver/cache.json diff --git a/src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java b/src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java new file mode 100644 index 0000000..e597bc4 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java @@ -0,0 +1,30 @@ +package it.gov.pagopa.nodetsworker; + +import io.quarkus.runtime.Startup; +import jakarta.annotation.PostConstruct; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; + +@Startup +@ApplicationScoped +public class AppStartup { + + @ConfigProperty(name = "startconfig.enabled") + boolean startconfig; + + @Inject Logger log; + + @Inject Config config; + + @PostConstruct + public void init() { + if (startconfig) { + log.info("Start Cache ENABLED"); + config.init(); + } else { + log.info("Start Cache DISABLED"); + } + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/Config.java b/src/main/java/it/gov/pagopa/nodetsworker/Config.java new file mode 100644 index 0000000..c5fd9f3 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/Config.java @@ -0,0 +1,85 @@ +package it.gov.pagopa.nodetsworker; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.scheduler.Scheduled; +import io.quarkus.scheduler.ScheduledExecution; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.client.ClientRequestFilter; +import lombok.SneakyThrows; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.eclipse.microprofile.rest.client.RestClientBuilder; +import org.jboss.logging.Logger; +import org.openapi.quarkus.api_config_cache_json.api.NodeCacheApi; +import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; + +import java.net.URI; +import java.util.Collections; + +@ApplicationScoped +public class Config { + + @ConfigProperty(name = "adapter.api_config_cache.url") + String url; + + @ConfigProperty(name = "adapter.api_config_cache.api-key-name") + String apiKeyName; + + @ConfigProperty(name = "adapter.api_config_cache.api-key-value") + String apiKeyValue; + + private NodeCacheApi nodeCacheApi; + + // @PostConstruct + @SneakyThrows + public void init() { + nodeCacheApi = + RestClientBuilder.newBuilder() + .baseUri(new URI(url)) + .register( + (ClientRequestFilter) + context -> + context + .getHeaders() + .put(apiKeyName, Collections.singletonList(apiKeyValue))) + .build(NodeCacheApi.class); + + ConfigDataV1 newCache = nodeCacheApi.cache(null); + log.debugf("Cache init. Version [%s]", newCache.getVersion()); + this.cache = newCache; + } + + @Inject ObjectMapper objectMapper; + + ConfigDataV1 cache; + + @SneakyThrows + public ConfigDataV1 getClonedCache() { + if (this.cache == null) { + log.debug("Api config cache NOT INITIALIZED"); + return null; + } else { + return objectMapper.readValue( + objectMapper.writeValueAsString(this.cache), ConfigDataV1.class); + } + } + + @Inject Logger log; + + @Scheduled(cron = "{api_config_cache.cron.expr}") + void cronJobApiconfigCache(ScheduledExecution execution) { + if (this.cache == null) { + log.debug("Api config cache NOT INITIALIZED"); + } else { + log.debugf("Schedule api-config-cache %s", execution.getScheduledFireTime()); + String version = cache.getVersion(); + String newVersion = nodeCacheApi.idV1().getVersion(); + if (version.equals(newVersion)) { + log.debugf("Cache NOT updated. Version [%s]", cache.getVersion()); + } else { + log.debugf("Cache updated. Version [%s] -> [%s]", version, newVersion); + this.cache = nodeCacheApi.cache(null); + } + } + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index dddb821..f6bbfad 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -1,5 +1,6 @@ package it.gov.pagopa.nodetsworker.service; +import it.gov.pagopa.nodetsworker.Config; import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageEnum; import it.gov.pagopa.nodetsworker.exceptions.AppException; import it.gov.pagopa.nodetsworker.models.*; @@ -15,6 +16,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; import java.time.LocalDate; import java.util.List; @@ -31,6 +33,9 @@ public class WorkerService { @Inject Logger log; + @Inject + Config configObject; + @Inject EventMapper eventsMapper; @@ -42,12 +47,13 @@ public class WorkerService { @Inject ReTableService reTableService; - private PaymentInfo eventToPaymentInfo(EventEntity ee){ + private PaymentInfo eventToPaymentInfo(ConfigDataV1 config,EventEntity ee){ + String brokerid = config.getChannels().get(ee.getCanale()).getBrokerPspCode(); return PaymentInfo.builder() .pspId(ee.getPsp()) .nodeId(ee.getServiceIdentifier()) .channelId(ee.getCanale()) - .brokerPspId(null)//todo recuperare da configurazione + .brokerPspId(brokerid) .insertedTimestamp(ee.getInsertedTimestamp()) .paymentToken(ee.getPaymentToken()) .noticeNumber(ee.getNoticeNumber()) @@ -57,12 +63,13 @@ private PaymentInfo eventToPaymentInfo(EventEntity ee){ .build(); } - private PaymentAttemptInfo eventToPaymentAttemptInfo(EventEntity ee){ + private PaymentAttemptInfo eventToPaymentAttemptInfo(ConfigDataV1 config,EventEntity ee){ + String brokerid = Optional.ofNullable(config.getChannels().get(ee.getCanale())).map(s->s.getBrokerPspCode()).orElse(null); return PaymentAttemptInfo.builder() .pspId(ee.getPsp()) .nodeId(ee.getServiceIdentifier()) .channelId(ee.getCanale()) - .brokerPspId(null)//todo recuperare da configurazione + .brokerPspId(brokerid) .insertedTimestamp(ee.getInsertedTimestamp()) .paymentToken(ee.getPaymentToken()) .noticeNumber(ee.getNoticeNumber()) @@ -73,11 +80,12 @@ private PaymentAttemptInfo eventToPaymentAttemptInfo(EventEntity ee){ .build(); } - private void enrichPaymentAttemptInfo(PaymentAttemptInfo pai, PositiveBizEvent pbe){ + private void enrichPaymentAttemptInfo(ConfigDataV1 config,PaymentAttemptInfo pai, PositiveBizEvent pbe){ + Long stationVersion = Optional.ofNullable(config.getStations().get(pai.getStationId())).map(s->s.getVersion()).orElse(null); pai.setPaymentToken(pbe.getPaymentInfo().getPaymentToken()); pai.setIsOldPaymentModel(pbe.getDebtorPosition().getModelType().equals("1")); pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); - pai.setStationVersion(null);//todo recuperare da configurazione + pai.setStationVersion(stationVersion); pai.setAmount(pbe.getPaymentInfo().getAmount()); pai.setFee(pbe.getPaymentInfo().getFee()); pai.setFeeOrganization(pbe.getPaymentInfo().getPrimaryCiIncurredFee()); @@ -90,10 +98,11 @@ private void enrichPaymentAttemptInfo(PaymentAttemptInfo pai, PositiveBizEvent p pai.setTransferDate(pbe.getPaymentInfo().getTransferDate()); } - private void enrichPaymentAttemptInfo(PaymentAttemptInfo pai, NegativeBizEvent nbe){ + private void enrichPaymentAttemptInfo(ConfigDataV1 config,PaymentAttemptInfo pai, NegativeBizEvent nbe){ + Long stationVersion = Optional.ofNullable(config.getStations().get(pai.getStationId())).map(s->s.getVersion()).orElse(null); pai.setIsOldPaymentModel(nbe.getDebtorPosition().getModelType().equals("1")); pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); - pai.setStationVersion(null);//todo recuperare da configurazione + pai.setStationVersion(stationVersion); pai.setAmount(nbe.getPaymentInfo().getAmount()); pai.setPaymentMethod(nbe.getPaymentInfo().getPaymentMethod()); pai.setPmReceipt(nbe.getTransactionDetails()!=null); @@ -104,7 +113,9 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndNN(dateFrom, dateTo, organizationFiscalCode, noticeNumber); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); @@ -135,7 +146,7 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, } } } - PaymentInfo pi = eventToPaymentInfo(lastEvent); + PaymentInfo pi = eventToPaymentInfo(config,lastEvent); pi.setOutcome(outcome); return pi; }).collect(Collectors.toList()); @@ -153,6 +164,7 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, LocalDate dateFrom, LocalDate dateTo){ DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndIUV(dateFrom, dateTo, organizationFiscalCode, iuv); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); @@ -184,7 +196,7 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, } } - PaymentInfo pi = eventToPaymentInfo(lastEvent); + PaymentInfo pi = eventToPaymentInfo(config,lastEvent); pi.setOutcome(outcome); return pi; }).collect(Collectors.toList()); @@ -199,13 +211,14 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizationFiscalCode, String noticeNumber, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndNNAndToken(dateFrom, dateTo, organizationFiscalCode, noticeNumber,paymentToken); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); List collect = reGroups.keySet().stream().map(gkey->{ List events = reGroups.get(gkey); EventEntity lastEvent = events.get(events.size()-1); - PaymentAttemptInfo pi = eventToPaymentAttemptInfo(lastEvent); + PaymentAttemptInfo pi = eventToPaymentAttemptInfo(config,lastEvent); String outcome = null; Optional pos = positiveBizClient.findEventsByCiAndIUVAndCCP( @@ -218,7 +231,7 @@ public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizat if(pos.isPresent()){ outcome = outcomeOK; pi.setOutcome(outcome); - enrichPaymentAttemptInfo(pi,pos.get()); + enrichPaymentAttemptInfo(config,pi,pos.get()); }else{ Optional neg = negativeBizClient.findEventsByCiAndNNAndToken( lastEvent.getIdDominio(), @@ -231,7 +244,7 @@ public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizat if(!neg.get().getReAwakable()){ outcome = outcomeKO; } - enrichPaymentAttemptInfo(pi,neg.get()); + enrichPaymentAttemptInfo(config,pi,neg.get()); } } return pi; @@ -248,6 +261,7 @@ public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizat public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndIUVAndCCP(dateFrom, dateTo, organizationFiscalCode, iuv,ccp); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); @@ -255,7 +269,7 @@ public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, List collect = reGroups.keySet().stream().map(gkey->{ List events = reGroups.get(gkey); EventEntity lastEvent = events.get(events.size()-1); - PaymentAttemptInfo pi = eventToPaymentAttemptInfo(lastEvent); + PaymentAttemptInfo pi = eventToPaymentAttemptInfo(config,lastEvent); String outcome = null; Optional pos = positiveBizClient.findEventsByCiAndIUVAndCCP( @@ -268,7 +282,7 @@ public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, if(pos.isPresent()){ outcome = outcomeOK; pi.setOutcome(outcome); - enrichPaymentAttemptInfo(pi,pos.get()); + enrichPaymentAttemptInfo(config,pi,pos.get()); }else{ Optional neg = negativeBizClient.findEventsByCiAndIUVAndCCP( lastEvent.getIdDominio(), @@ -281,7 +295,7 @@ public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, if(!neg.get().getReAwakable()){ outcome = outcomeKO; } - enrichPaymentAttemptInfo(pi,neg.get()); + enrichPaymentAttemptInfo(config,pi,neg.get()); } } return pi; diff --git a/src/main/openapi/api_config_cache.json b/src/main/openapi/api_config_cache.json new file mode 100644 index 0000000..3bcd4c9 --- /dev/null +++ b/src/main/openapi/api_config_cache.json @@ -0,0 +1,1221 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "API-Config Cacher", + "description": "Generate cache for regarding Nodo dei Pagamenti configuration", + "termsOfService": "https://www.pagopa.gov.it/", + "version": "0.4.0" + }, + "servers" : [ { + "url" : "https://api.dev.platform.pagopa.it/api-config-cache/p/v1/node", + "description" : "Api config cache oracle" + }], + "paths": { + "/stakeholders/node/cache/schemas/v1": { + "get": { + "tags": [ + "NodeCache" + ], + "summary": "Get selected key of node v1 config", + "operationId": "cache", + "parameters": [ + { + "name": "keys", + "in": "query", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "creditorInstitutions", + "creditorInstitutionBrokers", + "stations", + "creditorInstitutionStations", + "encodings", + "creditorInstitutionEncodings", + "ibans", + "creditorInstitutionInformations", + "psps", + "pspBrokers", + "paymentTypes", + "pspChannelPaymentTypes", + "plugins", + "pspInformationTemplates", + "pspInformations", + "channels", + "cdsServices", + "cdsSubjects", + "cdsSubjectServices", + "cdsCategories", + "configurations", + "ftpServers", + "languages", + "gdeConfigurations", + "metadataDict" + ] + } + } + } + ], + "responses": { + "403": { + "description": "Forbidden" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigDataV1" + } + } + } + }, + "500": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" + } + } + } + }, + "429": { + "description": "Too many requests" + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "ApiKey": [] + } + ] + } + }, + "/stakeholders/node/cache/schemas/v1/id": { + "get": { + "tags": [ + "NodeCache" + ], + "summary": "Get last node v1 cache version", + "operationId": "idV1", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CacheVersion" + } + } + } + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Not Found" + }, + "500": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" + } + } + } + }, + "429": { + "description": "Too many requests" + }, + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "ApiKey": [] + } + ] + } + } + }, + "components": { + "schemas": { + "BrokerCreditorInstitution": { + "required": [ + "broker_code", + "enabled", + "extended_fault_bean" + ], + "type": "object", + "properties": { + "broker_code": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "extended_fault_bean": { + "type": "boolean" + } + } + }, + "BrokerPsp": { + "required": [ + "broker_psp_code", + "enabled", + "extended_fault_bean" + ], + "type": "object", + "properties": { + "broker_psp_code": { + "type": "string" + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "extended_fault_bean": { + "type": "boolean" + } + } + }, + "CdsCategory": { + "required": [ + "description" + ], + "type": "object", + "properties": { + "description": { + "type": "string" + } + } + }, + "CdsService": { + "required": [ + "category", + "description", + "id", + "reference_xsd", + "version" + ], + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "description": { + "type": "string" + }, + "reference_xsd": { + "type": "string" + }, + "version": { + "type": "integer", + "format": "int64" + }, + "category": { + "type": "string" + } + } + }, + "CdsSubject": { + "required": [ + "creditor_institution_code", + "creditor_institution_description" + ], + "type": "object", + "properties": { + "creditor_institution_code": { + "type": "string" + }, + "creditor_institution_description": { + "type": "string" + } + } + }, + "CdsSubjectService": { + "required": [ + "fee", + "service", + "start_date", + "subject", + "subject_service_id" + ], + "type": "object", + "properties": { + "subject": { + "type": "string" + }, + "service": { + "type": "string" + }, + "subject_service_id": { + "type": "string" + }, + "start_date": { + "type": "string", + "format": "date-time" + }, + "end_date": { + "type": "string", + "format": "date-time" + }, + "fee": { + "type": "boolean" + }, + "station_code": { + "type": "string" + }, + "service_description": { + "type": "string" + } + } + }, + "Channel": { + "required": [ + "agid", + "broker_psp_code", + "channel_code", + "connection", + "digital_stamp", + "enabled", + "flag_io", + "flag_psp_cp", + "new_fault_code", + "password", + "payment_model", + "primitive_version", + "recovery", + "redirect", + "rt_push", + "thread_number", + "timeouts" + ], + "type": "object", + "properties": { + "channel_code": { + "type": "string" + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "password": { + "type": "string" + }, + "connection": { + "$ref": "#/components/schemas/Connection" + }, + "broker_psp_code": { + "type": "string" + }, + "proxy": { + "$ref": "#/components/schemas/Proxy" + }, + "service": { + "$ref": "#/components/schemas/Service" + }, + "service_nmp": { + "$ref": "#/components/schemas/Service" + }, + "thread_number": { + "type": "integer", + "format": "int64" + }, + "timeouts": { + "$ref": "#/components/schemas/Timeouts" + }, + "new_fault_code": { + "type": "boolean" + }, + "redirect": { + "$ref": "#/components/schemas/Redirect" + }, + "payment_model": { + "type": "string" + }, + "serv_plugin": { + "type": "string" + }, + "rt_push": { + "type": "boolean" + }, + "recovery": { + "type": "boolean" + }, + "digital_stamp": { + "type": "boolean" + }, + "flag_io": { + "type": "boolean" + }, + "agid": { + "type": "boolean" + }, + "primitive_version": { + "type": "integer", + "format": "int32" + }, + "flag_psp_cp": { + "type": "boolean" + } + } + }, + "ConfigDataV1": { + "required": [ + "cdsCategories", + "cdsServices", + "cdsSubjectServices", + "cdsSubjects", + "channels", + "configurations", + "creditorInstitutionBrokers", + "creditorInstitutionEncodings", + "creditorInstitutionInformations", + "creditorInstitutionStations", + "creditorInstitutions", + "encodings", + "ftpServers", + "gdeConfigurations", + "ibans", + "languages", + "metadataDict", + "paymentTypes", + "plugins", + "pspBrokers", + "pspChannelPaymentTypes", + "pspInformationTemplates", + "pspInformations", + "psps", + "stations", + "version" + ], + "type": "object", + "properties": { + "version": { + "type": "string" + }, + "creditorInstitutions": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CreditorInstitution" + } + }, + "creditorInstitutionBrokers": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/BrokerCreditorInstitution" + } + }, + "stations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Station" + } + }, + "creditorInstitutionStations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/StationCreditorInstitution" + } + }, + "encodings": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Encoding" + } + }, + "creditorInstitutionEncodings": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CreditorInstitutionEncoding" + } + }, + "ibans": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Iban" + } + }, + "creditorInstitutionInformations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CreditorInstitutionInformation" + } + }, + "psps": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PaymentServiceProvider" + } + }, + "pspBrokers": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/BrokerPsp" + } + }, + "paymentTypes": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PaymentType" + } + }, + "pspChannelPaymentTypes": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PspChannelPaymentType" + } + }, + "plugins": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Plugin" + } + }, + "pspInformationTemplates": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PspInformation" + } + }, + "pspInformations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PspInformation" + } + }, + "channels": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Channel" + } + }, + "cdsServices": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CdsService" + } + }, + "cdsSubjects": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CdsSubject" + } + }, + "cdsSubjectServices": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CdsSubjectService" + } + }, + "cdsCategories": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CdsCategory" + } + }, + "configurations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ConfigurationKey" + } + }, + "ftpServers": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/FtpServer" + } + }, + "languages": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "gdeConfigurations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/GdeConfiguration" + } + }, + "metadataDict": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/MetadataDict" + } + } + } + }, + "ConfigurationKey": { + "required": [ + "category", + "key", + "value" + ], + "type": "object", + "properties": { + "category": { + "type": "string" + }, + "key": { + "type": "string" + }, + "value": { + "type": "string" + }, + "description": { + "type": "string" + } + } + }, + "Connection": { + "required": [ + "ip", + "port", + "protocol" + ], + "type": "object", + "properties": { + "protocol": { + "type": "string", + "enum": [ + "HTTPS", + "HTTP" + ] + }, + "ip": { + "type": "string" + }, + "port": { + "type": "integer", + "format": "int64" + } + } + }, + "CreditorInstitution": { + "required": [ + "creditor_institution_code", + "enabled", + "psp_payment", + "reporting_ftp", + "reporting_zip" + ], + "type": "object", + "properties": { + "creditor_institution_code": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "business_name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "address": { + "$ref": "#/components/schemas/CreditorInstitutionAddress" + }, + "psp_payment": { + "type": "boolean" + }, + "reporting_ftp": { + "type": "boolean" + }, + "reporting_zip": { + "type": "boolean" + } + } + }, + "CreditorInstitutionAddress": { + "type": "object", + "properties": { + "location": { + "type": "string" + }, + "city": { + "type": "string" + }, + "zip_code": { + "type": "string" + }, + "country_code": { + "type": "string" + }, + "tax_domicile": { + "type": "string" + } + } + }, + "CreditorInstitutionEncoding": { + "required": [ + "code_type", + "creditor_institution_code", + "encoding_code" + ], + "type": "object", + "properties": { + "code_type": { + "type": "string" + }, + "encoding_code": { + "type": "string" + }, + "creditor_institution_code": { + "type": "string" + } + } + }, + "CreditorInstitutionInformation": { + "required": [ + "informativa" + ], + "type": "object", + "properties": { + "informativa": { + "type": "string" + } + } + }, + "Encoding": { + "required": [ + "code_type", + "description" + ], + "type": "object", + "properties": { + "code_type": { + "type": "string" + }, + "description": { + "type": "string" + } + } + }, + "FtpServer": { + "required": [ + "enabled", + "history_path", + "host", + "id", + "in_path", + "out_path", + "password", + "port", + "root_path", + "service", + "type", + "username" + ], + "type": "object", + "properties": { + "host": { + "type": "string" + }, + "port": { + "type": "integer", + "format": "int32" + }, + "enabled": { + "type": "boolean" + }, + "username": { + "type": "string" + }, + "password": { + "type": "string" + }, + "root_path": { + "type": "string" + }, + "service": { + "type": "string" + }, + "type": { + "type": "string" + }, + "in_path": { + "type": "string" + }, + "out_path": { + "type": "string" + }, + "history_path": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64" + } + } + }, + "GdeConfiguration": { + "required": [ + "event_hub_enabled", + "event_hub_payload_enabled", + "primitive", + "type" + ], + "type": "object", + "properties": { + "primitive": { + "type": "string" + }, + "type": { + "type": "string" + }, + "event_hub_enabled": { + "type": "boolean" + }, + "event_hub_payload_enabled": { + "type": "boolean" + } + } + }, + "Iban": { + "required": [ + "creditor_institution_code", + "iban", + "publication_date", + "validity_date" + ], + "type": "object", + "properties": { + "iban": { + "type": "string" + }, + "creditor_institution_code": { + "type": "string" + }, + "validity_date": { + "type": "string", + "format": "date-time" + }, + "publication_date": { + "type": "string", + "format": "date-time" + }, + "shop_id": { + "type": "string" + }, + "seller_bank_id": { + "type": "string" + }, + "avvio_key": { + "type": "string" + }, + "esito_key": { + "type": "string" + } + } + }, + "MetadataDict": { + "required": [ + "key", + "start_date" + ], + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "description": { + "type": "string" + }, + "start_date": { + "type": "string", + "format": "date-time" + }, + "end_date": { + "type": "string", + "format": "date-time" + } + } + }, + "PaymentServiceProvider": { + "required": [ + "agid_psp", + "digital_stamp", + "enabled", + "psp_code" + ], + "type": "object", + "properties": { + "psp_code": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "business_name": { + "type": "string" + }, + "abi": { + "type": "string" + }, + "bic": { + "type": "string" + }, + "my_bank_code": { + "type": "string" + }, + "digital_stamp": { + "type": "boolean" + }, + "agid_psp": { + "type": "boolean" + }, + "tax_code": { + "type": "string" + }, + "vat_number": { + "type": "string" + } + } + }, + "PaymentType": { + "required": [ + "payment_type" + ], + "type": "object", + "properties": { + "payment_type": { + "type": "string" + }, + "description": { + "type": "string" + } + } + }, + "Plugin": { + "required": [ + "id_serv_plugin" + ], + "type": "object", + "properties": { + "id_serv_plugin": { + "type": "string" + }, + "pag_const_string_profile": { + "type": "string" + }, + "pag_soap_rule_profile": { + "type": "string" + }, + "pag_rpt_xpath_profile": { + "type": "string" + }, + "id_bean": { + "type": "string" + } + } + }, + "Proxy": { + "type": "object", + "properties": { + "proxy_host": { + "type": "string" + }, + "proxy_port": { + "type": "integer", + "format": "int64" + }, + "proxy_username": { + "type": "string" + }, + "proxy_password": { + "type": "string" + } + } + }, + "PspChannelPaymentType": { + "required": [ + "channel_code", + "payment_type", + "psp_code" + ], + "type": "object", + "properties": { + "psp_code": { + "type": "string" + }, + "channel_code": { + "type": "string" + }, + "payment_type": { + "type": "string" + } + } + }, + "PspInformation": { + "required": [ + "informativa" + ], + "type": "object", + "properties": { + "informativa": { + "type": "string" + } + } + }, + "Redirect": { + "type": "object", + "properties": { + "protocol": { + "type": "string", + "enum": [ + "HTTPS", + "HTTP" + ] + }, + "ip": { + "type": "string" + }, + "path": { + "type": "string" + }, + "port": { + "type": "integer", + "format": "int64" + }, + "query_string": { + "type": "string" + } + } + }, + "Service": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "target_host": { + "type": "string" + }, + "target_port": { + "type": "integer", + "format": "int64" + }, + "target_path": { + "type": "string" + } + } + }, + "Station": { + "required": [ + "broker_code", + "connection", + "enabled", + "invio_rt_istantaneo", + "password", + "primitive_version", + "redirect", + "station_code", + "thread_number", + "timeouts", + "version" + ], + "type": "object", + "properties": { + "station_code": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "version": { + "type": "integer", + "format": "int64" + }, + "connection": { + "$ref": "#/components/schemas/Connection" + }, + "connection_mod4": { + "$ref": "#/components/schemas/Connection" + }, + "password": { + "type": "string" + }, + "redirect": { + "$ref": "#/components/schemas/Redirect" + }, + "service": { + "$ref": "#/components/schemas/Service" + }, + "service_pof": { + "$ref": "#/components/schemas/Service" + }, + "service_mod4": { + "$ref": "#/components/schemas/Service" + }, + "broker_code": { + "type": "string" + }, + "proxy": { + "$ref": "#/components/schemas/Proxy" + }, + "thread_number": { + "type": "integer", + "format": "int64" + }, + "timeouts": { + "$ref": "#/components/schemas/Timeouts" + }, + "invio_rt_istantaneo": { + "type": "boolean" + }, + "primitive_version": { + "type": "integer", + "format": "int32" + } + } + }, + "StationCreditorInstitution": { + "required": [ + "broadcast", + "creditor_institution_code", + "mod4", + "primitive_version", + "spontaneous_payment", + "station_code" + ], + "type": "object", + "properties": { + "creditor_institution_code": { + "type": "string" + }, + "station_code": { + "type": "string" + }, + "application_code": { + "type": "integer", + "format": "int64" + }, + "aux_digit": { + "type": "integer", + "format": "int64" + }, + "segregation_code": { + "type": "integer", + "format": "int64" + }, + "mod4": { + "type": "boolean" + }, + "broadcast": { + "type": "boolean" + }, + "primitive_version": { + "type": "integer", + "format": "int32" + }, + "spontaneous_payment": { + "type": "boolean" + } + } + }, + "Timeouts": { + "required": [ + "timeout_a", + "timeout_b", + "timeout_c" + ], + "type": "object", + "properties": { + "timeout_a": { + "type": "integer", + "format": "int64" + }, + "timeout_b": { + "type": "integer", + "format": "int64" + }, + "timeout_c": { + "type": "integer", + "format": "int64" + } + } + }, + "ProblemJson": { + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable" + }, + "status": { + "maximum": 600, + "minimum": 100, + "type": "integer", + "description": "The HTTP status code generated by the origin server for this occurrence of the problem.", + "format": "int32", + "example": 200 + }, + "detail": { + "type": "string", + "description": "A human readable explanation specific to this occurrence of the problem.", + "example": "There was an error processing the request" + } + } + }, + "CacheVersion": { + "required": [ + "version" + ], + "type": "object", + "properties": { + "version": { + "type": "string" + } + } + } + }, + "securitySchemes": { + "ApiKey": { + "type": "apiKey", + "description": "The API key to access this function app.", + "name": "Ocp-Apim-Subscription-Key", + "in": "header" + } + } + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 5b964a3..11d154b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -77,15 +77,10 @@ re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING} ################### ## ADAPTER API CONFIG CACHE ################### -#quarkus.rest-client.logging.scope=request-response +quarkus.rest-client.logging.scope=request-response #quarkus.rest-client.logging.body-limit=1024 #quarkus.log.category."org.jboss.resteasy.reactive.client.logging".level=DEBUG -adapter.api_config_cache.api-key-name=Ocp-Apim-Subscription-Key -adapter.api_config_cache.api-key-value=${ADAPTER_API_CONFIG_CACHE_API_KEY:12345} -#adapter.api_config_cache.url=https://api.dev.platform.pagopa.it/api-config-cache/pr/v1 -#adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:http://localhost:9091/} - ################### ## SCHEDULER ################### @@ -101,6 +96,9 @@ api_config_cache.cron.expr=*/15 * * * * ? startconfig.enabled=true %openapi.startconfig.enabled=false %openapi_internal.startconfig.enabled=false +adapter.api_config_cache.api-key-name=Ocp-Apim-Subscription-Key +adapter.api_config_cache.api-key-value=${ADAPTER_API_CONFIG_CACHE_API_KEY:12345} +adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:${quarkus.mockserver.endpoint}} operations.filter=".*" ############## @@ -113,10 +111,4 @@ operations.filter=".*" %test.quarkus.mockserver.devservices.config-dir=src/test/resources/mockserver %test.quarkus.mockserver.devservices.log=false -%dev.adapter.api_config_cache.url=${quarkus.mockserver.endpoint} -%test.adapter.api_config_cache.url=${quarkus.mockserver.endpoint} - -adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:${quarkus.mockserver.endpoint}} - - quarkus.test.continuous-testing=disabled diff --git a/src/test/resources/mockserver.properties b/src/test/resources/mockserver.properties new file mode 100644 index 0000000..8629897 --- /dev/null +++ b/src/test/resources/mockserver.properties @@ -0,0 +1,3 @@ +mockserver.initializationJsonPath=/mockserver/*.json +# watch changes in the file +mockserver.watchInitializationJson=true \ No newline at end of file diff --git a/src/test/resources/mockserver/cache.json b/src/test/resources/mockserver/cache.json new file mode 100644 index 0000000..0a27c6a --- /dev/null +++ b/src/test/resources/mockserver/cache.json @@ -0,0 +1,1701 @@ +[{ + "id": "1", + "httpRequest": { + "path": "/stakeholders/node/cache/schemas/v1/id" + }, + "httpResponse": { + "body": { + "type": "JSON", + "json": { + "version": "15807041712995048" + }, + "contentType": "application/json" + } + } +}, + { + "id": "2", + "httpRequest": { + "path": "/stakeholders/node/cache/schemas/v1" + }, + "httpResponse": { + "body": { + "type": "JSON", + "json": { + "version": "15807041712995048", + "creditorInstitutions": { + "12345678900": { + "creditor_institution_code": "12345678900", + "enabled": true, + "business_name": "paStress80", + "description": null, + "address": { + "location": null, + "city": null, + "zip_code": null, + "country_code": null, + "tax_domicile": null + }, + "psp_payment": true, + "reporting_ftp": false, + "reporting_zip": false + }, + "00987654321": { + "creditor_institution_code": "00987654321", + "enabled": false, + "business_name": "paStress80", + "description": null, + "address": { + "location": null, + "city": null, + "zip_code": null, + "country_code": null, + "tax_domicile": null + }, + "psp_payment": true, + "reporting_ftp": false, + "reporting_zip": false + } + }, + "creditorInstitutionBrokers": { + "intPaStress14": { + "broker_code": "intPaStress14", + "enabled": true, + "description": "intPaStress14", + "extended_fault_bean": false + } + }, + "stations": { + "77777777777_01": { + "station_code": "77777777777_01", + "enabled": true, + "version": 2, + "connection": { + "protocol": "HTTPS", + "ip": "api.dev.platform.pagopa.it", + "port": 443 + } + } + }, + "creditorInstitutionStations": { + "11_15151515151_null_null_null": { + "creditor_institution_code": "15151515151", + "station_code": "11", + "application_code": null, + "aux_digit": null, + "segregation_code": null, + "mod4": false, + "broadcast": false, + "primitive_version": 1, + "spontaneous_payment": false + } + }, + "encodings": null, + "creditorInstitutionEncodings": null, + "ibans": null, + "creditorInstitutionInformations": null, + "psps": { + "pspTest": { + "psp_code": "pspTest", + "enabled": true, + "description": "pspStress1", + "business_name": "pspStress1", + "abi": "TBD", + "bic": "TBD", + "my_bank_code": null, + "digital_stamp": false, + "agid_psp": false, + "tax_code": "CFpspStress1", + "vat_number": null + }, + "pspTest2": { + "psp_code": "pspTest2", + "enabled": true, + "description": "pspStress1", + "business_name": "pspStress1", + "abi": "TBD", + "bic": "TBD", + "my_bank_code": null, + "digital_stamp": false, + "agid_psp": false, + "tax_code": "CFpspStress1", + "vat_number": null + }, + "pspNotEnabled": { + "psp_code": "pspNotEnabled", + "enabled": false, + "description": "pspStress1", + "business_name": "pspStress1", + "abi": "TBD", + "bic": "TBD", + "my_bank_code": null, + "digital_stamp": false, + "agid_psp": false, + "tax_code": "CFpspStress1", + "vat_number": null + } + }, + "pspBrokers": { + "intTest": { + "broker_psp_code": "intTest", + "description": "Intermediario per mybankSvil", + "enabled": true, + "extended_fault_bean": false + }, + "intTest2": { + "broker_psp_code": "intTest2", + "description": "Intermediario per mybankSvil", + "enabled": true, + "extended_fault_bean": false + }, + "intNotEnabled": { + "broker_psp_code": "intNotEnabled", + "description": "Intermediario per mybankSvil", + "enabled": false, + "extended_fault_bean": false + } + }, + "paymentTypes": { + "AD": { + "payment_type": "AD", + "description": "Addebito diretto" + }, + "JIF": { + "payment_type": "JIF", + "description": "Jiffy" + }, + "CP": { + "payment_type": "CP", + "description": "Carta di pagamento " + }, + "DEVPAY": { + "payment_type": "DEVPAY", + "description": "Develop PAY" + }, + "PPAL": { + "payment_type": "PPAL", + "description": "PayPal" + }, + "STP": { + "payment_type": "STP", + "description": "Satispay PROVA" + }, + "BP": { + "payment_type": "BP", + "description": "Bollettino postale " + }, + "MYBK": { + "payment_type": "MYBK", + "description": "MyBank" + }, + "TPAY": { + "payment_type": "TPAY", + "description": "Pagamento appIO di test aggiuntivo" + }, + "BBT": { + "payment_type": "BBT", + "description": "Bonifico bancario telematico" + }, + "BPAY": { + "payment_type": "BPAY", + "description": "Bancomat Pay" + }, + "OBEP": { + "payment_type": "OBEP", + "description": "Online Banking Electronic Payment " + }, + "PPAY": { + "payment_type": "PPAY", + "description": "PostePay" + }, + "PO": { + "payment_type": "PO", + "description": "Pagamento attivato presso PSP " + } + }, + "pspChannelPaymentTypes": { + "pspTest_canaleTest_PAYPAL": { + "psp_code": "pspTest", + "channel_code": "canaleTest", + "payment_type": "PAYPAL" + } + }, + "plugins": null, + "pspInformationTemplates": null, + "pspInformations": null, + "channels": { + "canaleTest": { + "channel_code": "canaleTest", + "description": null, + "enabled": true, + "password": null, + "broker_psp_code": "intTest", + "connection": { + "protocol": "HTTPS", + "ip": "api.dev.platform.pagopa.it", + "port": 443 + } + }, + "canaleNotEnabled": { + "channel_code": "canaleNotEnabled", + "description": null, + "enabled": false, + "password": null, + "broker_psp_code": "intTest", + "connection": { + "protocol": "HTTPS", + "ip": "api.dev.platform.pagopa.it", + "port": 443 + } + } + }, + "cdsServices": null, + "cdsSubjects": null, + "cdsSubjectServices": null, + "cdsCategories": null, + "configurations": { + "GLOBAL-idPspCD": { + "category": "GLOBAL", + "key": "idPspCD", + "value": "AGID_01", + "description": "id PSP Cittadinanza Digitale" + }, + "GLOBAL-scheduler.sendPaymentResultPollerMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.sendPaymentResultPollerMaxRetry", + "value": "5", + "description": "Numero massimo di tentativi di re-invio sendPaymentResult al PM" + }, + "GLOBAL-scheduler.jobName_situazioneOrdineCheck.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_situazioneOrdineCheck.enabled", + "value": "true", + "description": "Job enabled (true/false) - da P_READY a P_WAITING" + }, + "GLOBAL-scheduler.jobName_situazioneOrdineCheck.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_situazioneOrdineCheck.jobDescription", + "value": "Description", + "description": "processo di recovery che parte dal WFESP per tutte le redirect in stato P_READY" + }, + "info-quadr-commissioneCaricoPa.template.sender.name.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPa.template.sender.name.mail", + "value": "PPT", + "description": null + }, + "GLOBAL-scheduler.paAttivaRptMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.paAttivaRptMaxRetry", + "value": "5", + "description": "pa attiva Rpt max retry" + }, + "info-quadr-commissioneCaricoPa.template.sender.address.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPa.template.sender.address.mail", + "value": "prova@prova.com", + "description": null + }, + "GLOBAL-scheduler.jobName_pspRetryAckNegative.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspRetryAckNegative.cronExpression", + "value": "0/30 * * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-istitutoAttestante.civicoAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.civicoAttestante", + "value": "370", + "description": "civicoAttestante" + }, + "GLOBAL-chiediSceltaWisp.tipoVersamento": { + "category": "GLOBAL", + "key": "chiediSceltaWisp.tipoVersamento", + "value": "BBT", + "description": "tipo versamento restituito durante la chiedi scelta Wisp" + }, + "GLOBAL-scheduler.jobName_paRetryPaInviaRtNegative.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_paRetryPaInviaRtNegative.enabled", + "value": "false", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.retryPspSendPayment": { + "category": "GLOBAL", + "key": "scheduler.retryPspSendPayment", + "value": "5", + "description": "Retry psp sent payment max retries" + }, + "GLOBAL-timeout.pspInviaCarrelloRPT": { + "category": "GLOBAL", + "key": "timeout.pspInviaCarrelloRPT", + "value": "TIMEOUT_B", + "description": "Tipo timeout" + }, + "GLOBAL-istitutoAttestante.indirizzoAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.indirizzoAttestante", + "value": "Piazza Colonna", + "description": "indirizzoAttestante" + }, + "GLOBAL-scheduler.jobName_rtPullRecoveryPush.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_rtPullRecoveryPush.cronExpression", + "value": "0 0 0/1 ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-default_durata_estensione_token_IO": { + "category": "GLOBAL", + "key": "default_durata_estensione_token_IO", + "value": "1000", + "description": " default millisecondi validità token IO estesa" + }, + "GLOBAL-scheduler.jobName_rtPullRecoveryPush.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_rtPullRecoveryPush.jobDescription", + "value": "Description", + "description": "Description" + }, + "GLOBAL-scheduler.jobName_mod3CancelV1.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3CancelV1.enabled", + "value": "false", + "description": "Job enabled (true/false)" + }, + "rpt-invia-patch.ministeroDiGiustizia.idDominio": { + "category": "rpt-invia", + "key": "patch.ministeroDiGiustizia.idDominio", + "value": "01386030488", + "description": "Indicare qui idDominio della PA MdG sulle cui RPT si deve applicare la trasformazione. Eventuali identificativi devono essere separati dal carattere \",\" (virgola)" + }, + "GLOBAL-scheduler.jobName_pspRetryAckNegative.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspRetryAckNegative.jobDescription", + "value": "Description", + "description": "Description" + }, + "rpt-modello4-descrizioneServizioBolloAuto": { + "category": "rpt-modello4", + "key": "descrizioneServizioBolloAuto", + "value": "Tassa automobilistica", + "description": "-" + }, + "info-quadr-smtp.test.sia": { + "category": "info-quadr", + "key": "smtp.test.sia", + "value": "true", + "description": "set true or false se si usa smtp server test" + }, + "GLOBAL-httpmethod.wfesp.psp2wfesp": { + "category": "GLOBAL", + "key": "httpmethod.wfesp.psp2wfesp", + "value": "esito", + "description": null + }, + "GLOBAL-scheduler.jobName_situazioneOrdine.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_situazioneOrdine.jobDescription", + "value": "Description", + "description": "processo di recovery che parte dal WFESP" + }, + "GLOBAL-scheduler.jobName_positionRetrySendPaymentResult.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_positionRetrySendPaymentResult.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-payment_activation_validity_minutes": { + "category": "GLOBAL", + "key": "payment_activation_validity_minutes", + "value": "10", + "description": "Minuti di validita chiave idempotenza" + }, + "GLOBAL-scheduler.suspendAllJobs": { + "category": "GLOBAL", + "key": "scheduler.suspendAllJobs", + "value": "false", + "description": "Suspend all jobs for release" + }, + "GLOBAL-scheduler.pspChiediAvanzamentoRptPollerMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.pspChiediAvanzamentoRptPollerMaxRetry", + "value": "1", + "description": "numero massimo di tentativi di invio RPT incomplete verso il PSP" + }, + "GLOBAL-scheduler.jobName_pspSendPayment.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspSendPayment.jobDescription", + "value": "Description", + "description": "psp send payment" + }, + "GLOBAL-istitutoAttestante.codiceUnitOperAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.codiceUnitOperAttestante", + "value": "n/a", + "description": "codiceUnitOperAttestante" + }, + "GLOBAL-scheduler.jobName_generaRendicontazioneBollo.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_generaRendicontazioneBollo.jobDescription", + "value": "Description", + "description": "Description" + }, + "GLOBAL-istitutoAttestante.nazioneAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.nazioneAttestante", + "value": "IT", + "description": "nazioneAttestante" + }, + "FATTURAZIONI-tipoVersamento.PPAL": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.PPAL", + "value": "0;0;0;0;1;0;0;0", + "description": "codifica csv tipo versamento PPAL" + }, + "GLOBAL-scheduler.jobName_pspChiediListaAndChiediRt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspChiediListaAndChiediRt.jobDescription", + "value": "Description", + "description": "Description" + }, + "GLOBAL-scheduler.jobName_annullamentoRptMaiRichiesteDaPm.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_annullamentoRptMaiRichiesteDaPm.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-timeout.paaAttivaRPT": { + "category": "GLOBAL", + "key": "timeout.paaAttivaRPT", + "value": "TIMEOUT_A", + "description": "Tipo timeout" + }, + "GLOBAL-timeout.pspChiediRT": { + "category": "GLOBAL", + "key": "timeout.pspChiediRT", + "value": "TIMEOUT_C", + "description": "Tipo timeout" + }, + "GLOBAL-scheduler.jobName_pspChiediListaAndChiediRt.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspChiediListaAndChiediRt.cronExpression", + "value": "0/30 * * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-scheduler.jobName_annullamentoRptMaiRichiesteDaPm.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_annullamentoRptMaiRichiesteDaPm.jobDescription", + "value": "Description", + "description": "Description" + }, + "GLOBAL-idIntPspMod3New": { + "category": "GLOBAL", + "key": "idIntPspMod3New", + "value": "15376371009", + "description": "idIntPspMod3New" + }, + "GLOBAL-scheduler.rptExpiringDays": { + "category": "GLOBAL", + "key": "scheduler.rptExpiringDays", + "value": "8", + "description": "giorni per cui non si sono completate RPT" + }, + "GLOBAL-timeout.pspInviaCarrelloRPTCarte": { + "category": "GLOBAL", + "key": "timeout.pspInviaCarrelloRPTCarte", + "value": "TIMEOUT_B", + "description": "Tipo timeout" + }, + "GLOBAL-scheduler.jobName_mod3RiconciliazioneRpt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3RiconciliazioneRpt.jobDescription", + "value": "Description", + "description": "Riconciliazione rpt" + }, + "GLOBAL-scheduler.annullamentoRptMaiRichiesteDaPmPollerMinutesToBack": { + "category": "GLOBAL", + "key": "scheduler.annullamentoRptMaiRichiesteDaPmPollerMinutesToBack", + "value": "1", + "description": "totale minuti per cui una richiesta non è mai stata processata da WISP2" + }, + "info-quadr-smtp.password": { + "category": "info-quadr", + "key": "smtp.password", + "value": "pda", + "description": null + }, + "rpt-annulla-algoritmoFirmaRT": { + "category": "rpt-annulla", + "key": "algoritmoFirmaRT", + "value": "SHA256withRSA", + "description": null + }, + "GLOBAL-scheduler.jobName_refreshConfiguration.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_refreshConfiguration.jobDescription", + "value": "60", + "description": "Description" + }, + "GLOBAL-uri.wfesp": { + "category": "GLOBAL", + "key": "uri.wfesp", + "value": "https://api.dev.platform.pagopa.it/wfesp-ndp/service/v1/redirect", + "description": "Redirect wfesp" + }, + "GLOBAL-scheduler.jobName_refreshConfiguration.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_refreshConfiguration.cronExpression", + "value": "0 * 0 ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-scheduler.situazioneOrdineCheckMinutesToFilter": { + "category": "GLOBAL", + "key": "scheduler.situazioneOrdineCheckMinutesToFilter", + "value": "30", + "description": " indica i minuti che devono passare per un ordine prima di eseguire la Situazione Ordine - job \"check\"" + }, + "GLOBAL-scheduler.jobName_pspNotificaCancellazione.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspNotificaCancellazione.jobDescription", + "value": "Description", + "description": "Description" + }, + "GLOBAL-closePaymentV2DenyListTipoVersamento": { + "category": "GLOBAL", + "key": "closePaymentV2DenyListTipoVersamento", + "value": "AD,BBT,BP,OBEP,PO,JIF,MYBK,BPAY,PPAL", + "description": "tipi versamento non accettati per closePaymentV2 per pagamenti IO/Checkout" + }, + "info-quadr-commissioneCaricoPsp.template.sender.address.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.template.sender.address.mail", + "value": "prova@prova.com", + "description": null + }, + "info-quadr-smtp.port": { + "category": "info-quadr", + "key": "smtp.port", + "value": "1026", + "description": null + }, + "GLOBAL-scheduler.jobName_annullamentoRptMaiRichiesteDaPm.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_annullamentoRptMaiRichiesteDaPm.cronExpression", + "value": "0 0/2 * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-validate_output": { + "category": "GLOBAL", + "key": "validate_output", + "value": "true", + "description": "Validazione XSD output Bundle" + }, + "FATTURAZIONI-tipoVersamento.POS": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.POS", + "value": "0;0;0;0;0;0;0;0", + "description": "codifica csv tipo versamento POS" + }, + "GLOBAL-scheduler.jobName_situazioneOrdineCheck.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_situazioneOrdineCheck.cronExpression", + "value": "*/1 * * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "info-quadr-commissioneCaricoPa.noData.message": { + "category": "info-quadr", + "key": "commissioneCaricoPa.noData.message", + "value": "Nessun dato disponibile per il mese di riferimento", + "description": null + }, + "GLOBAL-scheduler.jobName_paInviaRtRecovery.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_paInviaRtRecovery.enabled", + "value": "true", + "description": "paInviaRtRecovery enabled" + }, + "GLOBAL-scheduler.jobName_pspChiediAvanzamentoRpt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspChiediAvanzamentoRpt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.pspRetryNotificheCancellazioneRptPollerMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.pspRetryNotificheCancellazioneRptPollerMaxRetry", + "value": "3", + "description": "numero massimo di tentativi di re-invio notifiche cancellazione al PSP" + }, + "GLOBAL-timeout.paGetPayment": { + "category": "GLOBAL", + "key": "timeout.paGetPayment", + "value": "TIMEOUT_A", + "description": "timeout" + }, + "GLOBAL-scheduler.jobName_generaRendicontazioneBollo.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_generaRendicontazioneBollo.cronExpression", + "value": "0 0 0 ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-intPspCD": { + "category": "GLOBAL", + "key": "intPspCD", + "value": "97735020584", + "description": "identificativo intermediario PSP Cittadinanza Digitale" + }, + "GLOBAL-scheduler.jobName_paSendRt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_paSendRt.jobDescription", + "value": "Description", + "description": "invio receipt verso Stazioni PA" + }, + "GLOBAL-GLOBAL-mod3_inizio": { + "category": "GLOBAL", + "key": "GLOBAL-mod3_inizio", + "value": "2021-01-01", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.jobName_ftpUpload.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_ftpUpload.jobDescription", + "value": "Description", + "description": "Description" + }, + "rpt-modello4-dataInizioValiditaBolloAuto": { + "category": "rpt-modello4", + "key": "dataInizioValiditaBolloAuto", + "value": "2017-04-30T00:00:00", + "description": "-" + }, + "GLOBAL-idCanaleAGID": { + "category": "GLOBAL", + "key": "idCanaleAGID", + "value": "97735020584_02", + "description": "identificativo canale AGID" + }, + "GLOBAL-idPspMod3New": { + "category": "GLOBAL", + "key": "idPspMod3New", + "value": "15376371009", + "description": "idPspMod3New" + }, + "GLOBAL-scheduler.jobName_pspRetryNotificheCancellazioneRpt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspRetryNotificheCancellazioneRpt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "FATTURAZIONI-tipoVersamento.BP": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.BP", + "value": "0;1;0;0;0;0;0;0", + "description": "codifica csv tipo versamento BP" + }, + "GLOBAL-scheduler.jobName_mod3UpdateNotifiedPositionPayment.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3UpdateNotifiedPositionPayment.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "info-quadr-commissioneCaricoPsp.pdf.aggregato.header": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.pdf.aggregato.header", + "value": "Tabella aggregato versamenti", + "description": null + }, + "rpt-modello4-aciDescrizione": { + "category": "rpt-modello4", + "key": "aciDescrizione", + "value": "Automobile Club d italia", + "description": "descrizione Automobile Club Italia" + }, + "GLOBAL-timeout.pspNotifyPayment": { + "category": "GLOBAL", + "key": "timeout.pspNotifyPayment", + "value": "TIMEOUT_A", + "description": "timeout" + }, + "GLOBAL-timeout.pspNotificaCancellazioneRPT": { + "category": "GLOBAL", + "key": "timeout.pspNotificaCancellazioneRPT", + "value": "TIMEOUT_C", + "description": "Tipo timeout" + }, + "GLOBAL-scheduler.jobName_ftpUpload.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_ftpUpload.cronExpression", + "value": "0 0/1 * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-scheduler.jobName_pspSendPayment.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspSendPayment.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "info-quadr-commissioneCaricoPsp.pdf.aggregato.footer": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.pdf.aggregato.footer", + "value": "n.a.", + "description": null + }, + "info-wisp-chiediListaPSP.listaPspLisPay": { + "category": "info-wisp", + "key": "chiediListaPSP.listaPspLisPay", + "value": "BIC36019", + "description": "id PSP LisPay,divisi da virgola" + }, + "FATTURAZIONI-tipoVersamento.JIF": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.JIF", + "value": "0;0;0;0;0;0;1;0", + "description": "codifica csv tipo versamento JIF" + }, + "GLOBAL-inviaCarrelloRpt.maxNumRptInCartMultibeneficiario": { + "category": "GLOBAL", + "key": "inviaCarrelloRpt.maxNumRptInCartMultibeneficiario", + "value": "2", + "description": null + }, + "GLOBAL-scheduler.jobName_pspNotificaCancellazione.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspNotificaCancellazione.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "info-quadr-commissioneCaricoPsp.template.sender.name.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.template.sender.name.mail", + "value": "PPT", + "description": null + }, + "GLOBAL-idempotency.outcome.ok.duration.days": { + "category": "GLOBAL", + "key": "idempotency.outcome.ok.duration.days", + "value": "2", + "description": "cache validity days outcome ok" + }, + "GLOBAL-mod3_inizio": { + "category": "GLOBAL", + "key": "mod3_inizio", + "value": "2021-01-01", + "description": "Job enabled (true/false)" + }, + "FATTURAZIONI-tipoVersamento.CP": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.CP", + "value": "0;0;0;0;1;0;0;0", + "description": "codifica csv tipo versamento CP" + }, + "GLOBAL-ccpRandomTraduttore": { + "category": "GLOBAL", + "key": "ccpRandomTraduttore", + "value": "true", + "description": "popolare il CCP nella paaVerificaRPT generata dal traduttore con NMP_[random 10 numeri]" + }, + "rpt-modello4-xsdRiferimentoBolloAuto": { + "category": "rpt-modello4", + "key": "xsdRiferimentoBolloAuto", + "value": "TassaAutomobilistica_1_0_0.xsd", + "description": "-" + }, + "GLOBAL-scheduler.jobName_mod3Cancel.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3Cancel.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.jobName_mod3Cancel.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3Cancel.jobDescription", + "value": "Description", + "description": "cancellazione position payment con token scaduti modello 3" + }, + "rpt-invia-inviaCarrelloRpt.maxNumRptInCart": { + "category": "rpt-invia", + "key": "inviaCarrelloRpt.maxNumRptInCart", + "value": "5", + "description": "Numero massimo di elementi nel Carrello" + }, + "rendicontazioni-bollo.intermediario.CAPDelDomicilioFiscale": { + "category": "rendicontazioni", + "key": "bollo.intermediario.CAPDelDomicilioFiscale", + "value": "20147", + "description": "Dati dell'intermediario della trasmissione/ C.A.P. domicilio fiscale" + }, + "GLOBAL-timeout.paSendRT": { + "category": "GLOBAL", + "key": "timeout.paSendRT", + "value": "TIMEOUT_B", + "description": "timeout" + }, + "GLOBAL-scheduler.jobName_pspRetryNotificheCancellazioneRpt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspRetryNotificheCancellazioneRpt.jobDescription", + "value": "Description", + "description": "Description" + }, + "GLOBAL-istitutoAttestante.capAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.capAttestante", + "value": "00187", + "description": "capAttestante" + }, + "info-quadr-commissioneCaricoPsp.template.subject.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.template.subject.mail", + "value": "Report commissioniCaricoPsp", + "description": null + }, + "rendicontazioni-bollo.intermediario.comuneDomicilioFiscale": { + "category": "rendicontazioni", + "key": "bollo.intermediario.comuneDomicilioFiscale", + "value": "Milano", + "description": "Dati dell'intermediario della trasmissione/ Comune domicilio fiscale" + }, + "GLOBAL-uri.wallet": { + "category": "GLOBAL", + "key": "uri.wallet", + "value": "https://acardste.vaservices.eu:1443/wallet/welcome", + "description": null + }, + "GLOBAL-timeout.paDemandPaymentNotice": { + "category": "GLOBAL", + "key": "timeout.paDemandPaymentNotice", + "value": "TIMEOUT_A", + "description": "Tipo timeout" + }, + "GLOBAL-scheduler.jobName_rtPullRecoveryPush.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_rtPullRecoveryPush.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "info-wisp-chiediListaPSP.outputJsonValid": { + "category": "info-wisp", + "key": "chiediListaPSP.outputJsonValid", + "value": "true", + "description": null + }, + "GLOBAL-scheduler.jobName_mod3RiconciliazioneRt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3RiconciliazioneRt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-istitutoAttestante.localitaAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.localitaAttestante", + "value": "Roma", + "description": "localitaAttestante" + }, + "GLOBAL-scheduler.paSendRtMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.paSendRtMaxRetry", + "value": "1", + "description": "pa Send Rt max retry" + }, + "GLOBAL-istitutoAttestante.denominazioneAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.denominazioneAttestante", + "value": "PagoPA S.p.A.", + "description": "denominazioneAttestante" + }, + "rendicontazioni-bollo.intermediario.indirizzoFrazioneViaENumeroCivicoDelDomicilioFiscale": { + "category": "rendicontazioni", + "key": "bollo.intermediario.indirizzoFrazioneViaENumeroCivicoDelDomicilioFiscale", + "value": "Via Gonin, 36", + "description": "Dati dell'intermediario della trasmissione/ Indirizzo, frazione, via e numero civico del domicilio fiscale" + }, + "GLOBAL-scheduler.jobName_paRetryAttivaRpt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_paRetryAttivaRpt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-timeout.paaInviaRT.push": { + "category": "GLOBAL", + "key": "timeout.paaInviaRT.push", + "value": "TIMEOUT_B", + "description": "Tipo timeout" + }, + "Z7HuDfyuFpvmg6KBF3i6FQ17SA6W0FiiC2F-conf-key": { + "category": "Z7HuDfyuFpvmg6KBF3i6FQ17SA6W0FiiC2F", + "key": "conf-key", + "value": "test value", + "description": "this is a test" + }, + "GLOBAL-scheduler.jobName_generaRendicontazioneBollo.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_generaRendicontazioneBollo.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "rendicontazioni-bollo.intermediario.denominazione": { + "category": "rendicontazioni", + "key": "bollo.intermediario.denominazione", + "value": "SIA S.p.A.", + "description": "Dati dell'intermediario della trasmissione/ Denominazione" + }, + "GLOBAL-timeout.pspInviaAckRT": { + "category": "GLOBAL", + "key": "timeout.pspInviaAckRT", + "value": "TIMEOUT_C", + "description": "Tipo timeout" + }, + "GLOBAL-scheduler.jobName_cancelIOPayment.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_cancelIOPayment.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.jobName_pspRetryNotificheCancellazioneRpt.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspRetryNotificheCancellazioneRpt.cronExpression", + "value": "0 0 * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "rendicontazioni-bollo.mittente.codiceFiscale": { + "category": "rendicontazioni", + "key": "bollo.mittente.codiceFiscale", + "value": "15376371009", + "description": null + }, + "GLOBAL-scheduler.jobName_idempotencyCacheClean.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_idempotencyCacheClean.enabled", + "value": "false", + "description": "jobName_idempotencyCacheClean enabled/disabled" + }, + "FATTURAZIONI-tipoVersamento.AD": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.AD", + "value": "0;0;1;0;0;0;0;0", + "description": "codifica csv tipo versamento AD" + }, + "GLOBAL-timeout.paaInviaRT.pull": { + "category": "GLOBAL", + "key": "timeout.paaInviaRT.pull", + "value": "TIMEOUT_C", + "description": "Tipo timeout" + }, + "GLOBAL-verificabollettino.validity.minutes": { + "category": "GLOBAL", + "key": "verificabollettino.validity.minutes", + "value": "1", + "description": "validità verifica bollettino" + }, + "GLOBAL-scheduler.pspRetryAckNegativePollerMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.pspRetryAckNegativePollerMaxRetry", + "value": "1", + "description": "numero massimo di tentativi di re-invio ACK al PSP" + }, + "GLOBAL-idPspCheckout": { + "category": "GLOBAL", + "key": "idPspCheckout", + "value": "TBD", + "description": "id PSP Checkout" + }, + "GLOBAL-intPspAGID": { + "category": "GLOBAL", + "key": "intPspAGID", + "value": "97735020584", + "description": "identificativo intermediario PSP AGID" + }, + "info-quadr-commissioneCaricoPa.pdf.dettaglio.footer": { + "category": "info-quadr", + "key": "commissioneCaricoPa.pdf.dettaglio.footer", + "value": "n.a.", + "description": null + }, + "GLOBAL-inviaCarrelloRpt.maxVersamentiInSecondRptMultibeneficiario": { + "category": "GLOBAL", + "key": "inviaCarrelloRpt.maxVersamentiInSecondRptMultibeneficiario", + "value": "1", + "description": null + }, + "GLOBAL-scheduler.jobName_paInviaRt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_paInviaRt.jobDescription", + "value": "Description", + "description": "Description" + }, + "GLOBAL-flag.chiediInfoPagamento.useNewField": { + "category": "GLOBAL", + "key": "flag.chiediInfoPagamento.useNewField", + "value": "true", + "description": "Flag che indica se il PM dovrà ricevere i nuovi campi di infoPagamento" + }, + "GLOBAL-idCanaleMod3New": { + "category": "GLOBAL", + "key": "idCanaleMod3New", + "value": "15376371009_01", + "description": "idCanaleMod3New" + }, + "GLOBAL-scheduler.jobName_situazioneOrdine.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_situazioneOrdine.enabled", + "value": "true", + "description": "Job enabled (true/false) - sitOrd per quelle in P_WAITING" + }, + "FATTURAZIONI-tipoVersamento.BPAY": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.BPAY", + "value": "0;0;0;0;1;0;0;0", + "description": "codifica csv tipo versamento BPAY" + }, + "rpt-modello4-idServizioBolloAuto": { + "category": "rpt-modello4", + "key": "idServizioBolloAuto", + "value": "00001", + "description": "-" + }, + "GLOBAL-azureSdkClientReEventEnabled": { + "category": "GLOBAL", + "key": "azureSdkClientReEventEnabled", + "value": "true", + "description": "abilitazione scrittura re su eventhub azure PagoPA" + }, + "GLOBAL-default_token_duration_validity_millis": { + "category": "GLOBAL", + "key": "default_token_duration_validity_millis", + "value": "70000", + "description": " default millisecondi validità token" + }, + "GLOBAL-scheduler.jobName_paRetryPaInviaRtNegative.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_paRetryPaInviaRtNegative.cronExpression", + "value": "0/30 * * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-scheduler.jobName_mod3RiconciliazioneRpt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3RiconciliazioneRpt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.mod3Cancel.minutesWaitPaOld": { + "category": "GLOBAL", + "key": "scheduler.mod3Cancel.minutesWaitPaOld", + "value": "0", + "description": "timeout" + }, + "info-quadr-smtp.host": { + "category": "info-quadr", + "key": "smtp.host", + "value": "10.10.39.132", + "description": null + }, + "GLOBAL-scheduler.jobName_retryPspSendPayment.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_retryPspSendPayment.jobDescription", + "value": "Description", + "description": "Retry psp send payment" + }, + "GLOBAL-validate_input": { + "category": "GLOBAL", + "key": "validate_input", + "value": "true", + "description": "Validazione XSD input Bundle" + }, + "GLOBAL-idempotency.activate.ko.duration.days": { + "category": "GLOBAL", + "key": "idempotency.activate.ko.duration.days", + "value": "1", + "description": "cache validity days activate ko" + }, + "GLOBAL-gec.fees.maxRetry": { + "category": "GLOBAL", + "key": "gec.fees.maxRetry", + "value": "0", + "description": "maxRetry to GEC service fees" + }, + "GLOBAL-istitutoAttestante.identificativoUnivocoAttestante.tipoIdentificativoUnivoco": { + "category": "GLOBAL", + "key": "istitutoAttestante.identificativoUnivocoAttestante.tipoIdentificativoUnivoco", + "value": "G", + "description": "CtIdentificativoUnivoco.tipoIdentificativoUnivoco" + }, + "GLOBAL-scheduler.jobName_mod3UpdateNotifiedPositionPayment.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3UpdateNotifiedPositionPayment.jobDescription", + "value": "Description", + "description": "Mod3 update notified Position Payment" + }, + "GLOBAL-idempotency.outcome.ko.duration.days": { + "category": "GLOBAL", + "key": "idempotency.outcome.ko.duration.days", + "value": "2", + "description": "cache validity days outcome ko" + }, + "info-wisp-chiediListaPSP.listaIdPoste": { + "category": "info-wisp", + "key": "chiediListaPSP.listaIdPoste", + "value": "POSTE1", + "description": null + }, + "rendicontazioni-ftp.internalFTPComponentEndpointPort": { + "category": "rendicontazioni", + "key": "ftp.internalFTPComponentEndpointPort", + "value": "9610", + "description": null + }, + "GLOBAL-scheduler.jobName_paRetryPaInviaRtNegative.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_paRetryPaInviaRtNegative.jobDescription", + "value": "Description", + "description": "Description" + }, + "FATTURAZIONI-tipoVersamento.PO": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.PO", + "value": "0;0;0;0;0;1;0;0", + "description": "codifica csv tipo versamento PO" + }, + "GLOBAL-usePspNotifyPayment": { + "category": "GLOBAL", + "key": "usePspNotifyPayment", + "value": "false", + "description": " flag di ON/OFF se usare primitiva pspNotifyPayment per PayPal" + }, + "GLOBAL-scheduler.jobName_paRetryAttivaRpt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_paRetryAttivaRpt.jobDescription", + "value": "Description", + "description": "retry attiva rpt " + }, + "info-quadr-smtp.username": { + "category": "info-quadr", + "key": "smtp.username", + "value": "pda@dev.test", + "description": null + }, + "GLOBAL-scheduler.jobName_ftpUpload.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_ftpUpload.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "info-quadr-commissioneCaricoPa.pdf.dettaglio.header": { + "category": "info-quadr", + "key": "commissioneCaricoPa.pdf.dettaglio.header", + "value": "Tabella dettaglio versamenti", + "description": null + }, + "GLOBAL-timeout.cdInfoWisp": { + "category": "GLOBAL", + "key": "timeout.cdInfoWisp", + "value": "TIMEOUT_A", + "description": "Tipo timeout" + }, + "GLOBAL-timeout.paSendRT.pull": { + "category": "GLOBAL", + "key": "timeout.paSendRT.pull", + "value": "TIMEOUT_C", + "description": "Tipo timeout" + }, + "GLOBAL-useCountChiediAvanzamento": { + "category": "GLOBAL", + "key": "useCountChiediAvanzamento", + "value": "true", + "description": "toggle per abilitare o disabilitare contatori NodoChiediAvanzamento" + }, + "GLOBAL-default_idempotency_key_validity_minutes": { + "category": "GLOBAL", + "key": "default_idempotency_key_validity_minutes", + "value": "10", + "description": "timeout" + }, + "rpt-info-chiediInfoPagamento.outputJsonValid": { + "category": "rpt-info", + "key": "chiediInfoPagamento.outputJsonValid", + "value": "true", + "description": "-" + }, + "GLOBAL-scheduler.jobName_paInviaRt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_paInviaRt.enabled", + "value": "false", + "description": "Job enabled (true/false)" + }, + "info-pa-psp-disableNodoChiediInformativaPSP": { + "category": "info-pa-psp", + "key": "disableNodoChiediInformativaPSP", + "value": "false", + "description": "restituisce come risposta alla nodoChiediInformativaPSP un SYSTEM_ERROR" + }, + "GLOBAL-scheduler.jobName_mod3GenerateReceipt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3GenerateReceipt.jobDescription", + "value": "Description", + "description": "generazione ricevute in formato receipt" + }, + "GLOBAL-scheduler.jobName_mod3Riconciliazione.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3Riconciliazione.jobDescription", + "value": "Description", + "description": "Riconciliazione rpt" + }, + "GLOBAL-scheduler.jobName_mod3RiconciliazioneRt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3RiconciliazioneRt.jobDescription", + "value": "Description", + "description": "Riconciliazione rpt" + }, + "GLOBAL-scheduler.jobName_mod3CancelV2.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3CancelV2.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.jobName_pspChiediAvanzamentoRpt.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspChiediAvanzamentoRpt.cronExpression", + "value": "0/30 * * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "info-wisp-chiediListaPSP.listaCanaliLisPay": { + "category": "info-wisp", + "key": "chiediListaPSP.listaCanaliLisPay", + "value": "13212880150_07", + "description": "id Canali LisPay,divisi da virgola" + }, + "GLOBAL-timeout.paVerifyPaymentNotice": { + "category": "GLOBAL", + "key": "timeout.paVerifyPaymentNotice", + "value": "TIMEOUT_A", + "description": "Tipo timeout" + }, + "GLOBAL-scheduler.jobName_refreshConfiguration.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_refreshConfiguration.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-gec.fees.maxOccurences": { + "category": "GLOBAL", + "key": "gec.fees.maxOccurences", + "value": "10", + "description": "maxOccurences to GEC service fees" + }, + "GLOBAL-idPlugin.mybank": { + "category": "GLOBAL", + "key": "idPlugin.mybank", + "value": "wpl04", + "description": "identificativo plugin MyBank" + }, + "GLOBAL-paymentmanager.baseurl": { + "category": "GLOBAL", + "key": "paymentmanager.baseurl", + "value": "http://localhost:8080", + "description": "Validazione XSD input Bundle" + }, + "FATTURAZIONI-tipoVersamento.MYBK": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.MYBK", + "value": "0;0;0;0;0;0;0;1", + "description": "codifica csv tipo versamento MYBK" + }, + "info-wisp-chiediListaPSP.ibanPosteMatch": { + "category": "info-wisp", + "key": "chiediListaPSP.ibanPosteMatch", + "value": "07601", + "description": "Check iban poste match" + }, + "GLOBAL-httpmethod.wfesp.psp2wfespMS": { + "category": "GLOBAL", + "key": "httpmethod.wfesp.psp2wfespMS", + "value": "esitoMS", + "description": null + }, + "rpt-invia-patch.ministeroDiGiustizia.active": { + "category": "rpt-invia", + "key": "patch.ministeroDiGiustizia.active", + "value": "true", + "description": "Flag di attivazione della patch" + }, + "info-quadr-commissioneCaricoPsp.noData.message": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.noData.message", + "value": "Nessun dato disponibile per il mese di riferimento", + "description": null + }, + "GLOBAL-timeout.paaVerificaRPT": { + "category": "GLOBAL", + "key": "timeout.paaVerificaRPT", + "value": "TIMEOUT_A", + "description": "Tipo timeout" + }, + "GLOBAL-timeout.pspChiediListaRT": { + "category": "GLOBAL", + "key": "timeout.pspChiediListaRT", + "value": "TIMEOUT_C", + "description": "Tipo timeout" + }, + "GLOBAL-idCanaleCheckout": { + "category": "GLOBAL", + "key": "idCanaleCheckout", + "value": "TBD", + "description": "id Canale Checkout" + }, + "GLOBAL-id_psp_poste": { + "category": "GLOBAL", + "key": "id_psp_poste", + "value": "POSTE3", + "description": "id psp poste" + }, + "GLOBAL-outcome_retry_active": { + "category": "GLOBAL", + "key": "outcome_retry_active", + "value": "true", + "description": "attivazione retry su outcome scaduto mod3" + }, + "rendicontazioni-bollo.codiceIdentificativo.1": { + "category": "rendicontazioni", + "key": "bollo.codiceIdentificativo.1", + "value": "SIA", + "description": null + }, + "GLOBAL-scheduler.jobName_paInviaRt.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_paInviaRt.cronExpression", + "value": "0/30 * * ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-scheduler.ftpUploadRetryPollerMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.ftpUploadRetryPollerMaxRetry", + "value": "5", + "description": "numero massimo di tentativi di re-invio file ftp" + }, + "GLOBAL-scheduler.sendPaymentResultPollerMinutesBack": { + "category": "GLOBAL", + "key": "scheduler.sendPaymentResultPollerMinutesBack", + "value": "1", + "description": "Minuti precedenti per cercare una retry sendPaymentResult" + }, + "rendicontazioni-bollo.codiceIdentificativo.2": { + "category": "rendicontazioni", + "key": "bollo.codiceIdentificativo.2", + "value": "YY", + "description": null + }, + "GLOBAL-timeout.pspChiediAvanzamentoRPT": { + "category": "GLOBAL", + "key": "timeout.pspChiediAvanzamentoRPT", + "value": "TIMEOUT_B", + "description": "Tipo timeout" + }, + "info-quadr-commissioneCaricoPsp.invio.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.invio.mail", + "value": "true", + "description": null + }, + "GLOBAL-maxChiediAvanzamento": { + "category": "GLOBAL", + "key": "maxChiediAvanzamento", + "value": "3", + "description": "numero massimo di tentativi per NodoChiediAvanzamento da PM" + }, + "GLOBAL-gec.enabled": { + "category": "GLOBAL", + "key": "gec.enabled", + "value": "true", + "description": "toggle to enabled/disabled gec service" + }, + "GLOBAL-scheduler.jobName_paSendRt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_paSendRt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "FATTURAZIONI-tipoVersamento.BBT": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.BBT", + "value": "1;0;0;0;0;0;0;0", + "description": "codifica csv tipo versamento BBT" + }, + "rpt-modello4-aciId": { + "category": "rpt-modello4", + "key": "aciId", + "value": "00493410583", + "description": "identificativo Automobile Club Italia" + }, + "GLOBAL-default_durata_token_IO": { + "category": "GLOBAL", + "key": "default_durata_token_IO", + "value": "2000", + "description": " default millisecondi validità token IO" + }, + "GLOBAL-idCanaleCD": { + "category": "GLOBAL", + "key": "idCanaleCD", + "value": "97735020584_03", + "description": "identificativo canale Cittadinanza Digitale" + }, + "GLOBAL-timeoutForSingleProcessSeconds": { + "category": "GLOBAL", + "key": "timeoutForSingleProcessSeconds", + "value": "130", + "description": "Secondi di timeout per singolo processo" + }, + "GLOBAL-scheduler.jobName_mod3Riconciliazione.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3Riconciliazione.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-ftp.env.path": { + "category": "GLOBAL", + "key": "ftp.env.path", + "value": "pate_", + "description": "cartella file rendicontazioni" + }, + "GLOBAL-mybank.params.passaggioCodiceMyBank": { + "category": "GLOBAL", + "key": "mybank.params.passaggioCodiceMyBank", + "value": "true", + "description": null + }, + "FATTURAZIONI-tipoVersamento.TPAY": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.TPAY", + "value": "0;0;0;0;1;0;0;0", + "description": "codifica csv tipo versamento TPAY" + }, + "GLOBAL-httpmethod.wfesp.pa2wfesp": { + "category": "GLOBAL", + "key": "httpmethod.wfesp.pa2wfesp", + "value": "get", + "description": null + }, + "FATTURAZIONI-tipoVersamento.OBEP": { + "category": "FATTURAZIONI", + "key": "tipoVersamento.OBEP", + "value": "0;0;0;1;0;0;0;0", + "description": "codifica csv tipo versamento OBEP" + }, + "GLOBAL-istitutoAttestante.identificativoUnivocoAttestante.codiceIdentificativoUnivoco": { + "category": "GLOBAL", + "key": "istitutoAttestante.identificativoUnivocoAttestante.codiceIdentificativoUnivoco", + "value": "15376371009", + "description": "CtIdentificativoUnivoco.codiceIdentificativoUnivoco" + }, + "GLOBAL-idPspECommerce": { + "category": "GLOBAL", + "key": "idPspECommerce", + "value": "TBD", + "description": "id PSP eCommerce" + }, + "GLOBAL-scheduler.jobName_pspChiediAvanzamentoRpt.jobDescription": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspChiediAvanzamentoRpt.jobDescription", + "value": "Description", + "description": "Description" + }, + "info-quadr-versioneQuadrature": { + "category": "info-quadr", + "key": "versioneQuadrature", + "value": "6.1", + "description": "Versione Quadrature" + }, + "info-quadr-commissioneCaricoPa.pdf.aggregato.footer": { + "category": "info-quadr", + "key": "commissioneCaricoPa.pdf.aggregato.footer", + "value": "n.a.", + "description": null + }, + "rendicontazioni-bollo.dateFormat": { + "category": "rendicontazioni", + "key": "bollo.dateFormat", + "value": "yyyy-MM-dd", + "description": null + }, + "info-quadr-commissioneCaricoPa.invio.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPa.invio.mail", + "value": "true", + "description": null + }, + "GLOBAL-scheduler.jobName_pspNotificaCancellazione.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspNotificaCancellazione.cronExpression", + "value": "0 0 1 ? * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "info-quadr-commissioneCaricoPa.template.subject.mail": { + "category": "info-quadr", + "key": "commissioneCaricoPa.template.subject.mail", + "value": "Report commissioniCaricoPa", + "description": null + }, + "rpt-invia-mybank.params.passaggioCodiceMyBank": { + "category": "rpt-invia", + "key": "mybank.params.passaggioCodiceMyBank", + "value": "true", + "description": null + }, + "rendicontazioni-bollo.intermediario.siglaDellaProvinciaDelDomicilioFiscale": { + "category": "rendicontazioni", + "key": "bollo.intermediario.siglaDellaProvinciaDelDomicilioFiscale", + "value": "MI", + "description": "Dati dell'intermediario della trasmissione/ Sigle della provincia del domicilio fiscale" + }, + "GLOBAL-useIdempotency": { + "category": "GLOBAL", + "key": "useIdempotency", + "value": "false", + "description": "use idempotency" + }, + "GLOBAL-scheduler.jobName_pspChiediListaAndChiediRt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspChiediListaAndChiediRt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-scheduler.cancelIOPaymentActorMinutesToBack": { + "category": "GLOBAL", + "key": "scheduler.cancelIOPaymentActorMinutesToBack", + "value": "1", + "description": "cancel IO Payment Minutes To Back" + }, + "GLOBAL-scheduler.paRetryPaInviaRtNegativePollerMaxRetry": { + "category": "GLOBAL", + "key": "scheduler.paRetryPaInviaRtNegativePollerMaxRetry", + "value": "5", + "description": "numero massimo di tentativi di re-invio delle RT alla PA" + }, + "GLOBAL-wisp.timeoutScelta": { + "category": "GLOBAL", + "key": "wisp.timeoutScelta", + "value": "75", + "description": "wisp timeout ChiediSceltaWISP" + }, + "info-quadr-commissioneCaricoPsp.pdf.dettaglio.header": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.pdf.dettaglio.header", + "value": "Tabella dettaglio versamenti", + "description": null + }, + "GLOBAL-scheduler.jobName_situazioneOrdine.cronExpression": { + "category": "GLOBAL", + "key": "scheduler.jobName_situazioneOrdine.cronExpression", + "value": "*/2 * * * *", + "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" + }, + "GLOBAL-scheduler.jobName_mod3GenerateReceipt.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_mod3GenerateReceipt.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-idCanaleECommerce": { + "category": "GLOBAL", + "key": "idCanaleECommerce", + "value": "TBD", + "description": "id Canale eCommerce" + }, + "GLOBAL-istitutoAttestante.provinciaAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.provinciaAttestante", + "value": "RM", + "description": "provinciaAttestante" + }, + "GLOBAL-mod3_descoping": { + "category": "GLOBAL", + "key": "mod3_descoping", + "value": "true", + "description": "check mod3 descoping" + }, + "GLOBAL-timeout.paaChiediNumeroAvviso": { + "category": "GLOBAL", + "key": "timeout.paaChiediNumeroAvviso", + "value": "TIMEOUT_A", + "description": "Tipo timeout" + }, + "GLOBAL-timeout.paaAttivaRPT.pull": { + "category": "GLOBAL", + "key": "timeout.paaAttivaRPT.pull", + "value": "TIMEOUT_C", + "description": "timeout" + }, + "GLOBAL-sendBizEventsToEventHub": { + "category": "GLOBAL", + "key": "sendBizEventsToEventHub", + "value": "true", + "description": "sendBizEventsToEventHub" + }, + "info-quadr-commissioneCaricoPsp.pdf.dettaglio.footer": { + "category": "info-quadr", + "key": "commissioneCaricoPsp.pdf.dettaglio.footer", + "value": "n.a.", + "description": null + }, + "GLOBAL-scheduler.jobName_pspRetryAckNegative.enabled": { + "category": "GLOBAL", + "key": "scheduler.jobName_pspRetryAckNegative.enabled", + "value": "true", + "description": "Job enabled (true/false)" + }, + "GLOBAL-urlFittizioRedirectEC": { + "category": "GLOBAL", + "key": "urlFittizioRedirectEC", + "value": "http://url.fittizio", + "description": "urlFittizioRedirectEC" + }, + "GLOBAL-istitutoAttestante.denomUnitOperAttestante": { + "category": "GLOBAL", + "key": "istitutoAttestante.denomUnitOperAttestante", + "value": "n/a", + "description": "denomUnitOperAttestante" + }, + "info-quadr-commissioneCaricoPa.pdf.aggregato.header": { + "category": "info-quadr", + "key": "commissioneCaricoPa.pdf.aggregato.header", + "value": "Tabella aggregato versamenti", + "description": null + }, + "GLOBAL-idPspAGID": { + "category": "GLOBAL", + "key": "idPspAGID", + "value": "AGID_01", + "description": "id PSP AGID" + }, + "GLOBAL-timeout.pspInviaRPT": { + "category": "GLOBAL", + "key": "timeout.pspInviaRPT", + "value": "TIMEOUT_B", + "description": "Tipo timeout" + }, + "GLOBAL-IO_token_duration_validity_millis": { + "category": "GLOBAL", + "key": "IO_token_duration_validity_millis", + "value": "3600000", + "description": " default millisecondi validità token IO" + }, + "rendicontazioni-ftp.internalFTPComponentEndpointHost": { + "category": "rendicontazioni", + "key": "ftp.internalFTPComponentEndpointHost", + "value": "0.0.0.0", + "description": null + }, + "rt-invia-idFaultBean.nodo": { + "category": "rt-invia", + "key": "idFaultBean.nodo", + "value": "NodoDeiPagamentiSPC", + "description": "identificativo del nodo per valorizzazione dell'elemento id nel Fault Bean, in caso di errore generato dal FESP" + } + }, + "ftpServers": null, + "languages": null, + "gdeConfigurations": null, + "metadataDict": null + }, + "contentType": "application/json" + } + } + } +] \ No newline at end of file From 80514b1e63075d852fd8d21d05b0c984bd44558e Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 5 Jul 2023 08:53:00 +0200 Subject: [PATCH 05/29] wip --- .devops/code-review-pipelines.yml | 91 ++++ .devops/deploy-pipelines.yml | 398 ++++++++++++++++++ .mvn/wrapper/.gitignore | 1 + .mvn/wrapper/MavenWrapperDownloader.java | 122 ++++++ .mvn/wrapper/maven-wrapper.properties | 18 + build-and-run.sh | 70 +++ docker-infra/alertmanager/alertmanager.conf | 12 + docker-infra/docker-compose.yml | 104 +++++ docker-infra/grafana/grafana_config.ini | 5 + docker-infra/grafana/grafana_datasources.yml | 7 + .../otel-collector/otel-collector-config.yaml | 33 ++ docker-infra/prometheus/alert_rules.yml | 13 + docker-infra/prometheus/prometheus.yml | 29 ++ helm/Chart.yaml | 11 + helm/weu-dev/values-dev.yaml | 83 ++++ mvnw | 316 ++++++++++++++ pom.xml | 12 + run-local-infra.sh | 213 +++++----- src/main/docker/Dockerfile.jvm | 9 +- src/main/docker/Dockerfile.multistage | 4 +- src/main/docker/Dockerfile.multistage.jvm | 34 ++ .../models/TransactionResponse.java | 9 +- .../repository/CosmosBizEventClient.java | 109 +++-- .../repository/CosmosNegBizEventClient.java | 12 +- .../repository/ReTableService.java | 7 +- .../repository/model/PositiveBizEvent.java | 2 + .../nodetsworker/service/WorkerService.java | 52 +-- .../pagopa/nodetsworker/util/StatusUtil.java | 1 + .../it/gov/pagopa/nodetsworker/util/Util.java | 19 + src/main/resources/application.properties | 19 +- .../nodetsworker/resources/ResourceTest.java | 98 +++++ .../util/AppConstantTestHelper.java | 69 +++ .../nodetsworker/util/AzuriteResource.java | 40 ++ .../nodetsworker/util/CosmosResource.java | 73 ++++ 34 files changed, 1877 insertions(+), 218 deletions(-) create mode 100644 .devops/code-review-pipelines.yml create mode 100644 .devops/deploy-pipelines.yml create mode 100644 .mvn/wrapper/.gitignore create mode 100644 .mvn/wrapper/MavenWrapperDownloader.java create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 build-and-run.sh create mode 100644 docker-infra/alertmanager/alertmanager.conf create mode 100644 docker-infra/docker-compose.yml create mode 100644 docker-infra/grafana/grafana_config.ini create mode 100644 docker-infra/grafana/grafana_datasources.yml create mode 100644 docker-infra/otel-collector/otel-collector-config.yaml create mode 100644 docker-infra/prometheus/alert_rules.yml create mode 100644 docker-infra/prometheus/prometheus.yml create mode 100644 helm/Chart.yaml create mode 100644 helm/weu-dev/values-dev.yaml create mode 100644 mvnw create mode 100644 src/main/docker/Dockerfile.multistage.jvm create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/util/Util.java create mode 100644 src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java create mode 100644 src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java create mode 100644 src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java create mode 100644 src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java diff --git a/.devops/code-review-pipelines.yml b/.devops/code-review-pipelines.yml new file mode 100644 index 0000000..aaafefc --- /dev/null +++ b/.devops/code-review-pipelines.yml @@ -0,0 +1,91 @@ +# Maven +# Build your Java project and run tests with Apache Maven. +# Add steps that analyze code, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/java + +# Automatically triggered on PR +# https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema%2Cparameter-schema#pr-trigger +trigger: none + +pool: + vmImage: 'ubuntu-22.04' + +variables: + MAVEN_CACHE_FOLDER: $(Pipeline.Workspace)/.m2/repository + MAVEN_OPTS: '-Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' + GRAALVM_VERSION: '22.3.1' + +stages: + - stage: Test + jobs: + - job: unit_test + steps: + - checkout: self + persistCredentials: true + + - task: Cache@2 + inputs: + key: 'maven | "$(Agent.OS)" | pom.xml' + restoreKeys: | + maven | "$(Agent.OS)" + maven + path: $(MAVEN_CACHE_FOLDER) + displayName: Cache Maven local repo + + - script: | + echo "Install GraalVM $(GRAALVM_VERSION) - JAVA 17" + cd /tmp + curl -o GraalVM.tar.gz -L https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-$(GRAALVM_VERSION)/graalvm-ce-java17-linux-amd64-$(GRAALVM_VERSION).tar.gz + tar -xzf GraalVM.tar.gz + GRAALVM_HOME=/tmp/graalvm-ce-java17-$(GRAALVM_VERSION) + + sudo apt-get install build-essential libz-dev zlib1g-dev + + ${GRAALVM_HOME}/bin/gu install native-image + + #set for next step + echo "##vso[task.setvariable variable=GRAALVM_HOME]${GRAALVM_HOME}" + echo "##vso[task.setvariable variable=JAVA_HOME]${GRAALVM_HOME}" + echo "##vso[task.setvariable variable=PATH]${GRAALVM_HOME}/bin;$(PATH)" + + #set fot this step + export GRAALVM_HOME=${GRAALVM_HOME} + export JAVA_HOME=${GRAALVM_HOME} + export PATH=${GRAALVM_HOME}/bin:$PATH + + java -version + displayName: Install GraalVM $(GRAALVM_VERSION) - JAVA 17 + + - task: SonarCloudPrepare@1 + displayName: 'Prepare SonarCloud analysis configuration' + inputs: + SonarCloud: '$(SONARCLOUD_SERVICE_CONN)' + organization: '$(SONARCLOUD_ORG)' + scannerMode: Other + extraProperties: | + sonar.projectKey=$(SONARCLOUD_PROJECT_KEY) + sonar.projectName=$(SONARCLOUD_PROJECT_NAME) + sonar.exclusions=src/main/java/it/gov/pagopa/fdr/**/*Entity.java,src/main/java/it/gov/pagopa/fdr/util/App*.java,src/main/java/it/gov/pagopa/fdr/**/model/*.java,src/main/java/it/gov/pagopa/fdr/**/projection/*.java + + - task: Maven@3 + displayName: 'Run Junit Test' + inputs: + mavenPomFile: 'pom.xml' + goals: 'clean verify' + publishJUnitResults: true + testResultsFiles: '**/surefire-reports/TEST-*.xml' + codeCoverageToolOption: 'JaCoCo' + javaHomeOption: '/tmp/graalvm-ce-java17-$(GRAALVM_VERSION)' + jdkDirectory: '/tmp/graalvm-ce-java17-$(GRAALVM_VERSION)' + mavenVersionOption: 'Default' + mavenOptions: '-Xmx3072m $(MAVEN_OPTS)' + mavenAuthenticateFeed: false + effectivePomSkip: false + sonarQubeRunAnalysis: true + isJacocoCoverageReportXML: true + sqMavenPluginVersionChoice: 'latest' + + - task: SonarCloudPublish@1 + displayName: 'Publish SonarCloud results on build summary' + inputs: + pollingTimeoutSec: '300' diff --git a/.devops/deploy-pipelines.yml b/.devops/deploy-pipelines.yml new file mode 100644 index 0000000..e7921eb --- /dev/null +++ b/.devops/deploy-pipelines.yml @@ -0,0 +1,398 @@ +# Only manual triggers +trigger: none +pr: none + +pool: + vmImage: 'ubuntu-22.04' + +resources: + repositories: + - repository: pagopaCommons + type: github + name: pagopa/azure-pipeline-templates + ref: refs/tags/v3.10.0 + endpoint: 'io-azure-devops-github-ro' + +parameters: + - name: "WEU" + displayName: "Deploy in WEU" + type: boolean + default: True + values: + - False + - True + - name: "NEU" + displayName: "Deploy in NEU" + type: boolean + default: False + values: + - False + - True + - name: ENV + displayName: Target Environment + type: string + default: dev + values: + - dev + - uat + - prod + - name: SEMVER + displayName: "When packing a release, define the version bump to apply. Use only buildNumber or skip for manual deployment" + type: string + values: + - major + - minor + - patch + - buildNumber + - skip + default: skip + - name: SOURCE_BRANCH + displayName: "Use for checkout a different branch" + type: string + default: ' ' + - name: "SKIP_BUILD" + displayName: "Skip Build" + type: boolean + default: False + values: + - False + - True + - name: "FORCE_REPLACE_DOCKER_IMAGE" + displayName: "Force the existing docker image to be replaced" + type: boolean + default: False + values: + - False + - True + - name: "FORCE_REDEPLOY" + displayName: "Force re-deploy" + type: boolean + default: False + values: + - False + - True + +variables: + imageRepository: '$(IMAGE_REPOSITORY_NAME)' + nameSpace: '$(K8S_NAMESPACE)' + MAVEN_CACHE_FOLDER: $(Pipeline.Workspace)/.m2/repository + MAVEN_OPTS: '-Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' + GRAALVM_VERSION: '22.3.1' + APPROVE_NOTIFY_GROUP: '[pagoPA-iac]\pagopa-iac-externals-team' + APPROVE_NOTIFY_ADMIN: '[pagoPA-iac]\Project Administrators' + BRANCH_NAME: ${{ replace(variables['Build.SourceBranch'], 'refs/heads/', '') }} + + WEU_value_file: "helm/weu-${{ parameters['ENV'] }}/values-${{ parameters['ENV'] }}.yaml" + NEU_value_file: "helm/neu-${{ parameters['ENV'] }}/values-${{ parameters['ENV'] }}.yaml" + + appName: 'pagopafdr' + + ${{ if eq(parameters['ENV'], 'dev') }}: + WEU_dockerRegistryServiceConnection: $(DEV_CONTAINER_REGISTRY_SERVICE_CONN) + WEU_dockerRegistryFqdn: $(DEV_CONTAINER_NAMESPACE) + WEU_kubernetesServiceConnection: '$(DEV_KUBERNETES_SERVICE_CONN)' + WEU_poolImage: '$(DEPLOY-POOL-DEV)' + + + ${{ if eq(parameters['ENV'], 'uat') }}: + WEU_dockerRegistryServiceConnection: $(UAT_CONTAINER_REGISTRY_SERVICE_CONN) + WEU_dockerRegistryFqdn: $(UAT_CONTAINER_NAMESPACE) + WEU_kubernetesServiceConnection: '$(UAT_KUBERNETES_SERVICE_CONN)' + WEU_poolImage: '$(DEPLOY-POOL-UAT)' + + ${{ if eq(parameters['ENV'], 'prod') }}: + WEU_dockerRegistryServiceConnection: $(PROD_CONTAINER_REGISTRY_SERVICE_CONN) + WEU_dockerRegistryFqdn: $(PROD_CONTAINER_NAMESPACE) + WEU_kubernetesServiceConnection: '$(PROD_KUBERNETES_SERVICE_CONN)' + WEU_poolImage: '$(DEPLOY-POOL-PROD)' + + +stages: + # Create a release on GitHub + - stage: release + displayName: "Release" + jobs: + - job: make_release + displayName: "Make release" + steps: + - bash: | + buildname="$(Build.BuildNumber) ${{ parameters.ENV }}" + echo "##vso[build.addbuildtag]${{ parameters.ENV }}" + echo "##vso[build.updatebuildnumber]$buildname" + - bash: | + echo "##vso[task.setvariable variable=LIGHTBEND_KEY]$(lightbend_key_secret)" + - checkout: self + clean: true + persistCredentials: true + + - template: templates/maven-github-release/template.yaml@pagopaCommons + parameters: + release_branch: $(BRANCH_NAME) + gitEmail: $(GIT_EMAIL) + gitUsername: $(GIT_USERNAME) + gitHubConnection: $(GITHUB_CONNECTION) + semver: ${{ parameters.SEMVER }} + customHelmStep: | + if [[ "${{ parameters.WEU }}" = "True" ]]; then + VALUES_FILE="$(WEU_value_file)" + if [[ -f "$VALUES_FILE" ]]; then + yq -i ".fdr.image.tag = \"$(next_version.value)\"" "$VALUES_FILE" + git add "$VALUES_FILE" + fi + fi + if [[ "${{ parameters.NEU }}" = "True" ]]; then + VALUES_FILE="$(NEU_value_file)" + if [[ -f "$VALUES_FILE" ]]; then + yq -i ".fdr.image.tag = \"$(next_version.value)\"" "$VALUES_FILE" + git add "$VALUES_FILE" + fi + fi + - template: templates/maven-github-current-version/template.yaml@pagopaCommons + + # Build and Push Docker Image + - stage: build + ${{ if parameters.SKIP_BUILD }}: + displayName: "Build skipped" + ${{ if not(parameters.SKIP_BUILD) }}: + displayName: "Build" + variables: + current_version: $[ stageDependencies.release.make_release.outputs['current_version.value'] ] + jobs: + - job: build + ${{ if parameters.SKIP_BUILD }}: + displayName: "Build skipped" + ${{ if not(parameters.SKIP_BUILD) }}: + displayName: "Build" + condition: and(succeeded(), eq(${{ parameters.SKIP_BUILD }}, false)) + steps: + - checkout: self + persistCredentials: true + + - script: | + git checkout $(sourceBranch) + displayName: Checkout and update branch + +# - task: AzureKeyVault@2 +# displayName: "Get secrets" +# inputs: +# azureSubscription: $(AZURE_SERVICE_CONNECTION) +# keyVaultName: 'pagopa-d-fdr-kv' +# secretsFilter: 'api-config-cache-subscription-key-string' + + - template: templates/docker-release/template.yaml@pagopaCommons + parameters: + CONTAINER_REGISTRY_SERVICE_CONN: $(WEU_dockerRegistryServiceConnection) + CONTAINER_REGISTRY_FQDN: $(WEU_dockerRegistryFqdn) + DOCKER_IMAGE_NAME: $(imageRepository) + DOCKER_IMAGE_TAG: $(current_version) + FORCE_REPLACE_DOCKER_IMAGE: ${{ parameters.FORCE_REPLACE_DOCKER_IMAGE }} + ##Attenzione si usa il file Dockerfile.multistage.jvm, e non Dockerfile.multistage, perchè la lib di azure non è compatibile per la build nativa + DOCKERFILE: "$(Build.SourcesDirectory)/src/main/docker/Dockerfile.multistage.jvm" + DOCKER_BUILD_ARGS: "--build-arg APP_NAME=$(imageRepository) --build-arg QUARKUS_PROFILE=prod" + + # Deploy Canary if prod or uat + - ${{ if and( parameters.WEU , in( parameters.ENV, 'prod', 'uat') ) }}: + - ${{ each step in split(variables.weight_steps, ',')}}: + - stage: deploy_fdr_${{ step }} + displayName: "Deploy ${{ parameters.ENV }} canary ${{ step }}%" + jobs: + - job: get_release_version + displayName: "Get Release Version" + steps: + - template: templates/maven-github-current-version/template.yaml@pagopaCommons + - job: step_approval_${{ step }} + pool: server + dependsOn: get_release_version + condition: ${{ in( parameters.ENV, 'prod', 'uat') }} + variables: + current_version: $[ dependencies.get_release_version.outputs['current_version.value'] ] + displayName: "Approval ${{ parameters.ENV }} canary ${{ step }}% " + timeoutInMinutes: 70 + steps: + - task: ManualValidation@0 + displayName: "Approval version $(current_version) ${{ parameters.ENV }} canary ${{ step }}% " + timeoutInMinutes: 60 + inputs: + notifyUsers: | + $(APPROVE_NOTIFY_GROUP) + $(APPROVE_NOTIFY_ADMIN) + instructions: "Please approve or reject ${{ parameters.ENV }} $(current_version) canary deploy ${{ step }}%" + onTimeout: 'reject' + - deployment: "Approved_${{ parameters.ENV }}_${{ step }}_Deploy" + dependsOn : + - get_release_version + - step_approval_${{ step }} + condition: in(dependencies.step_approval_${{ step }}.result, 'Succeeded', 'Skipped') + variables: + current_version: $[ dependencies.get_release_version.outputs['current_version.value'] ] + displayName: "Deploy ${{ parameters.ENV }} ${{ step }}%" + pool: $(WEU_poolImage) + environment: ${{ parameters['ENV'] }} + strategy: + runOnce: + deploy: + steps: + - checkout: self + clean: true + persistCredentials: true + + - task: Bash@3 + name: setup_helm_microservices_chart + displayName: "Setup helm chart" + inputs: + targetType: "inline" + script: | + CHART_FILE="helm/Chart.yaml" + if [[ -f "$CHART_FILE" ]]; then + yq -i ".version = \"$(current_version)\"" "$CHART_FILE" + yq -i ".appVersion = \"$(current_version)\"" "$CHART_FILE" + fi + helm dep build helm + failOnStderr: true + - ${{ if parameters.WEU }}: + - template: templates/helm-microservice-chart-deploy/template.yaml@pagopaCommons + parameters: + DO_DEPLOY: true + ENV: ${{ parameters['ENV'] }} + KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} + NAMESPACE: "fdr" + APP_NAME: "$(appName)-canary" + VALUE_FILE: $(WEU_value_file) + DEPLOY_VERSION: $(current_version) + #APPINSIGHTS_SERVICE_CONN: ${{ variables.WEU_appInsightsServiceConn }} + #APPINSIGHTS_RESOURCE_ID: ${{ variables.WEU_appInsightsResourceId }} + CHART_PATH: "helm" + ARGUMENTS: >- + --set fdr.image.tag="$(current_version)" + --set fdr.canaryDelivery.create="true" + --set fdr.forceRedeploy=${{ parameters.FORCE_REDEPLOY }} + --set fdr.canaryDelivery.ingress.weightPercent="${{ step }}" + # Deploy stable + - stage: deploy_fdr_stable + displayName: "Deploy ${{ parameters.ENV }} stable" + jobs: + - job: get_release_version + displayName: "Get Release Version" + steps: + - template: templates/maven-github-current-version/template.yaml@pagopaCommons + - job: step_approval_stable + pool: server + dependsOn: get_release_version + condition: ${{ in( parameters.ENV, 'prod', 'uat') }} + variables: + current_version: $[ dependencies.get_release_version.outputs['current_version.value'] ] + displayName: "Approval ${{ parameters.ENV }} stable" + timeoutInMinutes: 70 + steps: + - task: ManualValidation@0 + displayName: "Approval version $(current_version) ${{ parameters.ENV }} stable" + timeoutInMinutes: 60 + inputs: + notifyUsers: | + $(APPROVE_NOTIFY_GROUP) + $(APPROVE_NOTIFY_ADMIN) + instructions: "Please approve or reject ${{ parameters.ENV }} $(current_version) stable deploy" + onTimeout: 'reject' + - ${{ if parameters.WEU }}: + - deployment: "Approved_${{ parameters.ENV }}_Deploy" + dependsOn: + - get_release_version + - step_approval_stable + condition: in(dependencies.step_approval_stable.result, 'Succeeded', 'Skipped') + variables: + current_version: $[ dependencies.get_release_version.outputs['current_version.value'] ] + displayName: "Deploy ${{ parameters.ENV }} WEU stable" + pool: $(WEU_poolImage) + environment: ${{ parameters['ENV'] }} + strategy: + runOnce: + deploy: + steps: + - checkout: self + clean: true + persistCredentials: true + + - task: Bash@3 + name: setup_helm_microservices_chart + displayName: "Setup helm chart" + inputs: + targetType: "inline" + script: | + CHART_FILE="helm/Chart.yaml" + if [[ -f "$CHART_FILE" ]]; then + yq -i ".version = \"$(current_version)\"" "$CHART_FILE" + yq -i ".appVersion = \"$(current_version)\"" "$CHART_FILE" + fi + helm dep build helm + failOnStderr: true + - bash: | + echo "install WEU" + - template: templates/helm-microservice-chart-deploy/template.yaml@pagopaCommons + parameters: + DO_DEPLOY: true + ENV: ${{ parameters['ENV'] }} + KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} + NAMESPACE: "fdr" + APP_NAME: $(appName) + VALUE_FILE: $(WEU_value_file) + DEPLOY_VERSION: $(current_version) + #APPINSIGHTS_SERVICE_CONN: ${{ variables.WEU_appInsightsServiceConn }} + #APPINSIGHTS_RESOURCE_ID: ${{ variables.WEU_appInsightsResourceId }} + CHART_PATH: "helm" + ARGUMENTS: >- + --set fdr.image.tag="$(current_version)" + --set fdr.forceRedeploy=${{ parameters.FORCE_REDEPLOY }} + + - ${{ if in( parameters.ENV, 'prod', 'uat') }}: + - bash: | + echo "uninstall WEU CANARY" + - template: templates/helm-microservice-chart-deploy/template.yaml@pagopaCommons + parameters: + COMMAND: "uninstall" + DO_DEPLOY: true + ENV: ${{ parameters['ENV'] }} + KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} + NAMESPACE: "fdr" + APP_NAME: "$(appName)-canary" + VALUE_FILE: $(WEU_value_file) + DEPLOY_VERSION: $(current_version) + #APPINSIGHTS_SERVICE_CONN: ${{ variables.WEU_appInsightsServiceConn }} + #APPINSIGHTS_RESOURCE_ID: ${{ variables.WEU_appInsightsResourceId }} + CHART_PATH: "helm" + ARGUMENTS: "$(appName)-canary" + + # uninstall canary id prod or uat + - ${{ if in( parameters.ENV, 'prod', 'uat') }}: + - stage: uninstall + displayName: "Uninstall ${{ parameters.ENV }} canary" + condition: and( ${{ in( parameters.ENV, 'prod', 'uat') }} ,failed()) + jobs: + - deployment: "uninstall" + displayName: "Uninstall ${{ parameters.ENV }} canary" + pool: $(WEU_poolImage) + environment: ${{ parameters['ENV'] }} + strategy: + runOnce: + deploy: + steps: + - checkout: self + clean: true + persistCredentials: true + + - ${{ if and( parameters.WEU , in( parameters.ENV, 'prod', 'uat') ) }}: + - bash: | + echo "uninstall WEU CANARY" + - template: templates/helm-microservice-chart-deploy/template.yaml@pagopaCommons + parameters: + COMMAND: "uninstall" + DO_DEPLOY: true + ENV: ${{ parameters['ENV'] }} + KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} + NAMESPACE: "fdr" + APP_NAME: "$(appName)-canary" + VALUE_FILE: $(WEU_value_file) + DEPLOY_VERSION: $(current_version) + #APPINSIGHTS_SERVICE_CONN: ${{ variables.WEU_appInsightsServiceConn }} + #APPINSIGHTS_RESOURCE_ID: ${{ variables.WEU_appInsightsResourceId }} + CHART_PATH: "helm/fdr" + ARGUMENTS: "$(appName)-canary" diff --git a/.mvn/wrapper/.gitignore b/.mvn/wrapper/.gitignore new file mode 100644 index 0000000..e72f5e8 --- /dev/null +++ b/.mvn/wrapper/.gitignore @@ -0,0 +1 @@ +maven-wrapper.jar diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..e69e044 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.*; +import java.net.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + private static final String WRAPPER_VERSION = "3.1.1"; + + /** Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/" + + WRAPPER_VERSION + + "/maven-wrapper-" + + WRAPPER_VERSION + + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use + * instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** Path where the maven-wrapper.jar will be saved to. */ + private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + + outputFile.getParentFile().getAbsolutePath() + + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault( + new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } +} diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..61a2ef1 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/build-and-run.sh b/build-and-run.sh new file mode 100644 index 0000000..812164c --- /dev/null +++ b/build-and-run.sh @@ -0,0 +1,70 @@ +#!/bin/bash + +action=$1 + +if [ -z "$action" ]; then + echo "Missed action: " + exit 0 +fi + +REPO=pagopa/pagopafdr + +build () { + conf=$1 + version=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout) + echo "Build version [$version] [$conf]" + #./mvnw clean package -Pnative -Dquarkus.native.container-build=true -Dquarkus.profile=$conf + #docker build -f src/main/docker/Dockerfile.native -t $REPO:$version-$conf . + + ##Attenzione si usa il file Dockerfile.multistage.jvm, e non Dockerfile.multistage, perchè la lib di azure non è compatibile per la build nativa + docker build -f src/main/docker/Dockerfile.multistage.jvm \ + --build-arg APP_NAME=pagopafdr --build-arg QUARKUS_PROFILE=$conf \ + -t $REPO:$version-$conf . +} + +run () { + conf=$1 + version=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout) + echo "Run version [$version] [$conf]" + docker run -i --rm --network=docker-infra_infra -p 8080:8080 $REPO:$version-$conf +} + +generate_openapi () { + conf=$1 + version=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout) + echo "Generate OpenAPI JSON [$version] [$conf]" + docker run -i -d --name exportfdr_$conf --rm -p 8080:8080 $REPO:$version-$conf + sleep 10 + curl http://localhost:8080/q/openapi?format=json > openapi/$conf.json + docker rm -f exportfdr_$conf +} + +test_curl () { + curl localhost:8080/q/dev + curl localhost:8080/q/health + curl localhost:8080/q/health/live + curl localhost:8080/q/health/ready + curl localhost:8080/q/metrics + curl localhost:8080/q/swagger-ui + curl localhost:8080/q/openapi +} + +set -e +if echo "build run generate_openapi test_curl" | grep -w $action > /dev/null; then + if [ $action = "build" ]; then + build docker + elif [ $action = "run" ]; then + echo "###########" + echo "# REQUIRED: run-local-infra.sh" + echo "###########" + run docker + elif [ $action = "generate_openapi" ]; then + build openapi + generate_openapi openapi + else + test_curl + fi +else + echo "Action [$action] not allowed." + exit 1 +fi diff --git a/docker-infra/alertmanager/alertmanager.conf b/docker-infra/alertmanager/alertmanager.conf new file mode 100644 index 0000000..13611f6 --- /dev/null +++ b/docker-infra/alertmanager/alertmanager.conf @@ -0,0 +1,12 @@ +global: + resolve_timeout: 1m + pagerduty_url: 'https://events.pagerduty.com/v2/enqueue' + +route: + receiverEntity: 'pagerduty-notifications' + +receivers: +- name: 'pagerduty-notifications' + pagerduty_configs: + - service_key: 0c1cc665a594419b6d215e81f4e38f7 + send_resolved: true diff --git a/docker-infra/docker-compose.yml b/docker-infra/docker-compose.yml new file mode 100644 index 0000000..6cad351 --- /dev/null +++ b/docker-infra/docker-compose.yml @@ -0,0 +1,104 @@ +version: '3.8' + +services: + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch:8.6.2 + ports: + - "9200:9200" + - "9300:9300" + environment: + ES_JAVA_OPTS: "-Xms512m -Xmx512m" + discovery.type: "single-node" + xpack.security.enabled: false + xpack.security.enrollment.enabled: false + networks: + - infra + + kibana: + image: docker.elastic.co/kibana/kibana:8.6.2 + ports: + - "5601:5601" + networks: + - infra + depends_on: + - elasticsearch + + alertmanager: + hostname: alertmanager + image: prom/alertmanager + volumes: + - ${PWD}/alertmanager/alertmanager.conf:/etc/alertmanager/alertmanager.conf + command: + - '--config.file=/etc/alertmanager/alertmanager.conf' + ports: + - 9093:9093 + networks: + - infra + + prometheus: + hostname: prometheus + image: prom/prometheus + volumes: + - ${PWD}/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml + - ${PWD}/prometheus/alert_rules.yml:/etc/prometheus/alert_rules.yml + - prometheus_data:/prometheus + command: + - '--config.file=/etc/prometheus/prometheus.yml' + links: + - alertmanager:alertmanager + ports: + - 9090:9090 + networks: + - infra + + grafana: + hostname: grafana + image: grafana/grafana + volumes: + - ${PWD}/grafana/grafana_datasources.yml:/etc/grafana/provisioning/datasources/all.yaml + - ${PWD}/grafana/grafana_config.ini:/etc/grafana/config.ini + - grafana_data:/var/lib/grafana + ports: + - 3000:3000 + networks: + - infra + + jaeger-all-in-one: + image: jaegertracing/all-in-one:latest + ports: + - "16686:16686" + - "14268:14268" + - "14250:14250" + networks: + - infra + + otel-collector: + image: otel/opentelemetry-collector:latest + command: [ "--config=/etc/otel-collector-config.yaml" ] + volumes: + - ${PWD}/otel-collector/otel-collector-config.yaml:/etc/otel-collector-config.yaml:Z + ports: + - "13133:13133" # Health_check extension + - "4317:4317" # OTLP gRPC receiver + depends_on: + - jaeger-all-in-one + networks: + - infra + + azurite: + image: "mcr.microsoft.com/azure-storage/azurite" + restart: always + ports: + - 10000:10000 + - 10001:10001 + - 10002:10002 + networks: + - infra + + +volumes: + prometheus_data: { } + grafana_data: { } +networks: + infra: + driver: bridge diff --git a/docker-infra/grafana/grafana_config.ini b/docker-infra/grafana/grafana_config.ini new file mode 100644 index 0000000..9c84f44 --- /dev/null +++ b/docker-infra/grafana/grafana_config.ini @@ -0,0 +1,5 @@ +[paths] +provisioning = /etc/grafana/provisioning + +[server] +enable_gzip = true \ No newline at end of file diff --git a/docker-infra/grafana/grafana_datasources.yml b/docker-infra/grafana/grafana_datasources.yml new file mode 100644 index 0000000..ba6949e --- /dev/null +++ b/docker-infra/grafana/grafana_datasources.yml @@ -0,0 +1,7 @@ +apiVersion: 1 + +datasources: + - name: 'prometheus' + type: 'prometheus' + access: 'proxy' + url: 'http://prometheus:9090' \ No newline at end of file diff --git a/docker-infra/otel-collector/otel-collector-config.yaml b/docker-infra/otel-collector/otel-collector-config.yaml new file mode 100644 index 0000000..c08ab06 --- /dev/null +++ b/docker-infra/otel-collector/otel-collector-config.yaml @@ -0,0 +1,33 @@ +receivers: + otlp: + protocols: + grpc: + endpoint: otel-collector:4317 + +exporters: + jaeger: + endpoint: jaeger-all-in-one:14250 + tls: + insecure: true + otlphttp/elastic: + tls: + insecure: true + # Elastic APM server https endpoint without the "https://" prefix + endpoint: "https://kibana.dev.platform.pagopa.it:443/apm" + headers: + # Elastic APM Server secret token + Authorization: "Bearer 30K8q56M9r3jhKrIdhf968PO" + +processors: + batch: + +extensions: + health_check: + +service: + extensions: [ health_check ] + pipelines: + traces: + receivers: [ otlp ] + processors: [ batch ] + exporters: [ jaeger, otlphttp/elastic ] diff --git a/docker-infra/prometheus/alert_rules.yml b/docker-infra/prometheus/alert_rules.yml new file mode 100644 index 0000000..5d0c4fd --- /dev/null +++ b/docker-infra/prometheus/alert_rules.yml @@ -0,0 +1,13 @@ +groups: + - name: JVMMemory + rules: + - alert: JVMMemoryThresholdCrossed + # Condition for alerting + expr: jvm_memory_committed_bytes{region="heap"}/jvm_memory_max_bytes{region="heap"} > 0.8 + # Annotation - additional informational labels to store more information + annotations: + title: 'Instance has crossed 80% heap memory usage' + description: ' of job has crossed 80% heap memory usage' + # Labels - additional labels to be attached to the alert + labels: + severity: 'critical' \ No newline at end of file diff --git a/docker-infra/prometheus/prometheus.yml b/docker-infra/prometheus/prometheus.yml new file mode 100644 index 0000000..9521553 --- /dev/null +++ b/docker-infra/prometheus/prometheus.yml @@ -0,0 +1,29 @@ +# global settings +global: + scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute. + evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute. + # scrape_timeout is set to the global default (10s). + +alerting: + alertmanagers: + - static_configs: + - targets: [ "alertmanager:9093" ] + +# Load rules once and periodically evaluate them according to the global 'evaluation_interval'. +rule_files: + - /etc/prometheus/alert_rules.yml + +# A scrape configuration containing exactly one endpoint to scrape: +# Here it's Prometheus itself. +scrape_configs: + # The job name is added as a label `job=` to any timeseries scraped from this config. + - job_name: 'ndp-metrics' + metrics_path: '/q/metrics' + scrape_interval: 5s + static_configs: + - targets: [ 'docker.for.mac.host.internal:8080' ] + #labels: + # application: ndp + # namespace: nodo + # service: ndp + # env: dev diff --git a/helm/Chart.yaml b/helm/Chart.yaml new file mode 100644 index 0000000..2814a30 --- /dev/null +++ b/helm/Chart.yaml @@ -0,0 +1,11 @@ +apiVersion: v2 +name: pagopa-tech-support +description: Technical support api +type: application +version: "0.0.0-SNAPSHOT" +appVersion: "0.0.0-SNAPSHOT" +dependencies: + - name: microservice-chart + version: 3.0.0 + repository: "https://pagopa.github.io/aks-microservice-chart-blueprint" + alias: pagopa-tech-support diff --git a/helm/weu-dev/values-dev.yaml b/helm/weu-dev/values-dev.yaml new file mode 100644 index 0000000..439678d --- /dev/null +++ b/helm/weu-dev/values-dev.yaml @@ -0,0 +1,83 @@ +pagopa-tech-support: + namespace: "techsupport" + image: + repository: pagopadcommonacr.azurecr.io/pagopanodetechnicalsupportworker + tag: '1.0.0-SNAPSHOT' + readinessProbe: + httpGet: + path: /q/health/ready + port: 8080 + initialDelaySeconds: 8 + failureThreshold: 10 + periodSeconds: 2 + livenessProbe: + httpGet: + path: /q/health/live + port: 8080 + initialDelaySeconds: 8 + failureThreshold: 10 + periodSeconds: 2 + envConfig: + APP_ENVIRONMENT: "dev" + TZ: "Europe/Rome" + OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" + ADAPTER_API_CONFIG_CACHE_URL: "https://api.dev.platform.pagopa.it/api-config-cache/p/v1" + envFieldRef: + APP_NAME: "metadata.labels['app.kubernetes.io/instance']" + APP_VERSION: "metadata.labels['app.kubernetes.io/version']" + secretProvider: + create: true + envSecrets: + ADAPTER_API_CONFIG_CACHE_API_KEY: "api-config-cache-subscription-key-string" + OTEL_AUTH_BEARER: "otel-auth-bearer" + MONGODB_CONNECTION_STRING: "mongodb-connection-string" + QUEUE_CONVERSION_CONNECTION_STRING: "azure-queue-conversion-connection-string" + EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" + keyvault: + name: "pagopa-d-fdr-kv" + tenantId: "7788edaf-0346-4068-9d79-c868aed15b3d" + tmpVolumeMount: + create: true + resources: + requests: + memory: "2Gi" + cpu: "200m" + limits: + memory: "3Gi" + cpu: "400m" + autoscaling: + enable: true + minReplica: 1 + maxReplica: 2 + pollingInterval: 10 # seconds + cooldownPeriod: 50 # seconds + triggers: + - type: cpu + metadata: + type: Utilization + value: "75" + - type: memory + metadata: + type: Utilization + value: "75" + affinity: + nodeAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + - matchExpressions: + - key: node_type + operator: In + values: + - user + serviceMonitor: + create: true + endpoints: + - interval: 5s + targetPort: 8080 + path: /q/metrics + service: + create: true + ingress: + create: true + host: "weudev.techsupport.internal.dev.platform.pagopa.it" + path: /pagopa-tech-support(/|$)(.*) diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..eaa3d30 --- /dev/null +++ b/mvnw @@ -0,0 +1,316 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`\\unset -f command; \\command -v java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/pom.xml b/pom.xml index b150021..add3fb6 100644 --- a/pom.xml +++ b/pom.xml @@ -138,6 +138,18 @@ 1.18.1 test + + org.testcontainers + azure + 1.18.3 + test + + + com.github.terma + javaniotcpproxy + 1.6 + test + diff --git a/run-local-infra.sh b/run-local-infra.sh index bd4ce3f..13154e1 100644 --- a/run-local-infra.sh +++ b/run-local-infra.sh @@ -1,169 +1,154 @@ #!/bin/bash -project=$1 - -if [ -z "$project" ] -then - project="generic" -fi - - -cd docker +cd docker-infra docker compose down --remove-orphans --volumes docker compose up -d cd .. +exit 0 -sleep 30 +sleep 20 echo "" echo "" echo "Add policy" -printf -v body -- '{ - "policy": { - "phases": { - "hot": { - "min_age": "0ms", - "actions": { - "rollover": { - "max_primary_shard_size": "50gb", - "max_age": "2d" +curl -k -X PUT "http://localhost:9200/_ilm/policy/logs-fdr" \ + -H 'kbn-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{ + "policy": { + "phases": { + "hot": { + "min_age": "0ms", + "actions": { + "rollover": { + "max_primary_shard_size": "50gb", + "max_age": "2d" + } } - } - }, - "warm": { - "min_age": "2d", - "actions": { - "set_priority": { - "priority": 50 + }, + "warm": { + "min_age": "2d", + "actions": { + "set_priority": { + "priority": 50 + } } - } - }, - "cold": { - "min_age": "4d", - "actions": { - "set_priority": { - "priority": 0 + }, + "cold": { + "min_age": "4d", + "actions": { + "set_priority": { + "priority": 0 + } + } + }, + "delete": { + "min_age": "7d", + "actions": { + "delete": {} } } }, - "delete": { - "min_age": "7d", - "actions": { - "delete": {} - } + "_meta": { + "description": "Policy for FDR" } - }, - "_meta": { - "description": "Policy for %s" } } - } - ' ${project} -curl -k -X PUT "http://localhost:9200/_ilm/policy/logs-${project}" \ - -H 'kbn-xsrf: true' \ - -H 'Content-Type: application/json' \ - -d "${body}" + ' echo "" echo "" echo "Add _component_template settings" -printf -v body -- '{ - "template":{ - "settings": { - "index.lifecycle.name": "logs-%s" - } - }, - "_meta": { - "description": "Settings for %s" - } - } - ' ${project} ${project} -curl -k -X PUT "http://localhost:9200/_component_template/logs-${project}-settings" \ +curl -k -X PUT "http://localhost:9200/_component_template/logs-fdr-settings" \ -H 'kbn-xsrf: true' \ -H 'Content-Type: application/json' \ - -d "${body}" + -d '{ + "template":{ + "settings": { + "index.lifecycle.name": "logs-fdr" + } + }, + "_meta": { + "description": "Settings for FDR" + } + } + ' echo "" echo "" echo "Add _component_template mappings" -printf -v body -- '{ - "template":{ - "settings": { - "index.lifecycle.name": "logs-%s" - } - }, - "_meta": { - "description": "Settings for %s" - } - } - ' ${project} ${project} -curl -k -X PUT "http://localhost:9200/_component_template/logs-${project}-mappings" \ +curl -k -X PUT "http://localhost:9200/_component_template/logs-fdr-mappings" \ -H 'kbn-xsrf: true' \ -H 'Content-Type: application/json' \ - -d "${body}" + -d '{ + "template":{ + "settings": { + "index.lifecycle.name": "logs-fdr" + } + }, + "_meta": { + "description": "Settings for FDR" + } + } + ' echo "" echo "" echo "Add _index_template" -printf -v body -- '{ - "index_patterns": [ - "logs-%s-*" - ], - "data_stream": {}, - "composed_of": [ "logs-%s-mappings", "logs-%s-settings" ], - "priority": 500, - "_meta": { - "description": "Index template for %s" - } - } - ' ${project} ${project} ${project} ${project} -curl -k -X PUT "http://localhost:9200/_index_template/logs-${project}" \ +curl -k -X PUT "http://localhost:9200/_index_template/logs-fdr" \ -H 'kbn-xsrf: true' \ -H 'Content-Type: application/json' \ - -d "${body}" + -d '{ + "index_patterns": [ + "logs-fdr-*" + ], + "data_stream": {}, + "composed_of": [ "logs-fdr-mappings", "logs-fdr-settings" ], + "priority": 500, + "_meta": { + "description": "Index template for FDR" + } + } + ' echo "" echo "" echo "Add space" -printf -v body -- '{ - "id": "%s", - "name": "%s", - "description" : "This is the %s Space", - "color": "#4C54E7", - "disabledFeatures": [] - } - ' ${project} ${project} ${project} curl -k -X POST "http://localhost:5601/api/spaces/space" \ -H 'kbn-xsrf: true' \ -H 'Content-Type: application/json' \ - -d "${body}" + -d '{ + "id": "fdr", + "name": "Flussi di rendicontazione", + "description" : "This is the FDR Space", + "color": "#4C54E7", + "disabledFeatures": [] + } + ' echo "" echo "" echo "Add data_views" -printf -v body -- '{ - "data_view": { - "title": "logs-%s-log-*", - "name": "Log Data View", - "timeFieldName": "@timestamp" - } - } - ' ${project} -data_view=$(curl -k -X POST "http://localhost:5601/s/${project}/api/data_views/data_view" \ +data_view=$(curl -k -X POST "http://localhost:5601/s/fdr/api/data_views/data_view" \ -H 'kbn-xsrf: true' \ -H 'Content-Type: application/json' \ - -d "${body}") + -d '{ + "data_view": { + "title": "logs-fdr-log-*", + "name": "FDR log Data View", + "timeFieldName": "@timestamp" + } + } + ') echo "" echo "" echo "Set default data_views" -printf -v body -- '{ - "data_view_id": "%s" - } - ' $(echo "$data_view" | jq ".data_view.id") -curl -X POST "http://localhost:5601/s/${project}/api/data_views/default" \ +data_view_id=$(echo $data_view | jq ".data_view.id") +curl -X POST "http://localhost:5601/s/fdr/api/data_views/default" \ -H 'kbn-xsrf: true' \ -H 'Content-Type: application/json' \ - -d "${body}" - -# Note: if the previous curl fails, you don't have the space set as default, not a big problem :) + -d'{ + "data_view_id": "${data_view_id}" + } + ' diff --git a/src/main/docker/Dockerfile.jvm b/src/main/docker/Dockerfile.jvm index ad219b9..82671b9 100644 --- a/src/main/docker/Dockerfile.jvm +++ b/src/main/docker/Dockerfile.jvm @@ -79,7 +79,6 @@ FROM registry.access.redhat.com/ubi8/openjdk-17:1.14 ENV LANGUAGE='en_US:en' - # We make four distinct layers so if there are application changes the library layers can be re-used COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ COPY --chown=185 target/quarkus-app/*.jar /deployments/ @@ -88,6 +87,12 @@ COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ EXPOSE 8080 USER 185 -ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" + +ARG QUARKUS_PROFILE +ARG APP_NAME +ARG ADAPTER_API_CONFIG_CACHE_URL +ARG ADAPTER_API_CONFIG_CACHE_KEY + +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE -Djava.util.logging.manager=org.jboss.logmanager.LogManager" ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" diff --git a/src/main/docker/Dockerfile.multistage b/src/main/docker/Dockerfile.multistage index 7944201..58d47da 100644 --- a/src/main/docker/Dockerfile.multistage +++ b/src/main/docker/Dockerfile.multistage @@ -7,9 +7,11 @@ USER quarkus WORKDIR /code RUN ./mvnw -B org.apache.maven.plugins:maven-dependency-plugin:3.1.2:go-offline COPY src /code/src + ARG QUARKUS_PROFILE ARG APP_NAME -RUN ./mvnw package -Pnative -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE + +RUN ./mvnw package -DskipTests=true -Pnative -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE ## Stage 2 : create the docker final image FROM quay.io/quarkus/quarkus-micro-image:2.0 diff --git a/src/main/docker/Dockerfile.multistage.jvm b/src/main/docker/Dockerfile.multistage.jvm new file mode 100644 index 0000000..c627c29 --- /dev/null +++ b/src/main/docker/Dockerfile.multistage.jvm @@ -0,0 +1,34 @@ +## Stage 1 : build with maven builder image with native capabilities +FROM quay.io/quarkus/ubi-quarkus-graalvmce-builder-image:22.3-java17 AS build +COPY --chown=quarkus:quarkus mvnw /code/mvnw +COPY --chown=quarkus:quarkus .mvn /code/.mvn +COPY --chown=quarkus:quarkus pom.xml /code/ +USER quarkus +WORKDIR /code +RUN ./mvnw -B org.apache.maven.plugins:maven-dependency-plugin:3.1.2:go-offline +COPY src /code/src +ARG QUARKUS_PROFILE +ARG APP_NAME + +RUN ./mvnw package -DskipTests=true -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE + +FROM registry.access.redhat.com/ubi8/openjdk-17:1.14 + +ENV LANGUAGE='en_US:en' + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --from=build /code/target/quarkus-app/lib/ /deployments/lib/ +COPY --from=build /code/target/quarkus-app/*.jar /deployments/ +COPY --from=build /code/target/quarkus-app/app/ /deployments/app/ +COPY --from=build /code/target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 185 + +ARG QUARKUS_PROFILE +ARG APP_NAME + +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" + + diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java index ccb95d8..eb31e77 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java @@ -1,6 +1,7 @@ package it.gov.pagopa.nodetsworker.models; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSubTypes; import lombok.*; import java.time.LocalDate; @@ -11,10 +12,14 @@ @NoArgsConstructor @AllArgsConstructor @Builder -public class TransactionResponse { +public class TransactionResponse { private LocalDate dateFrom; private LocalDate dateTo; @JsonProperty("data") - private List payments; + @JsonSubTypes({ + @JsonSubTypes.Type(value = BasePaymentInfo.class, name = "car"), + @JsonSubTypes.Type(value = BasePaymentInfo.class, name = "truck") + }) + private List payments; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java index 2186114..ba15441 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -10,15 +10,17 @@ import it.gov.pagopa.nodetsworker.repository.model.Count; import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; +import it.gov.pagopa.nodetsworker.util.Util; import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; -import java.time.LocalDate; +import java.time.*; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -35,108 +37,91 @@ public class CosmosBizEventClient { private static String dbname = "db"; private static String tablename = "biz-events"; + private CosmosClient client; + @Inject Logger log; + private CosmosClient getClient(){ + if(client==null){ + client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); + } + return client; + } + private CosmosPagedIterable query(SqlQuerySpec query){ log.info("executing query:"+query.getQueryText()); - CosmosClient client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); - CosmosContainer container = client.getDatabase(dbname).getContainer(tablename); + CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); return container.queryItems(query, new CosmosQueryRequestOptions(), PositiveBizEvent.class); } private CosmosPagedIterable queryCount(SqlQuerySpec query){ log.info("executing query:"+query.getQueryText()); - CosmosClient client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); - CosmosContainer container = client.getDatabase(dbname).getContainer(tablename); + CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); return container.queryItems(query, new CosmosQueryRequestOptions(), Count.class); } public CosmosPagedIterable findEventsByCiAndNNAndToken(String organizationFiscalCode, String noticeNumber,String paymentToken, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@paymentToken", paymentToken)); + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@noticeNumber", noticeNumber), + new SqlParameter("@paymentToken", paymentToken), + new SqlParameter("@from", dateFrom.atStartOfDay()), + new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + ); SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.noticeNumber = @noticeNumber" + " and c.paymentInfo.paymentToken = @paymentToken" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" + Util.ifNotNull(dateFrom," and c.paymentInfo.paymentDateTime > @from") + + Util.ifNotNull(dateTo," and c.paymentInfo.paymentDateTime < @to") ) .setParameters(paramList); return query(q); } public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@iuv", iuv)); - paramList.add(new SqlParameter("@ccp", ccp)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); - + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@iuv", iuv), + new SqlParameter("@ccp", ccp), + new SqlParameter("@from", dateFrom.atStartOfDay()), + new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + ); SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.iuv = @iuv" + " and c.paymentInfo.paymentToken = @ccp" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" + Util.ifNotNull(dateFrom," and c.paymentInfo.paymentDateTime > @from") + + Util.ifNotNull(dateTo," and c.paymentInfo.paymentDateTime < @to") ) .setParameters(paramList); return query(q); } - public CosmosPagedIterable findEvents(String organizationFiscalCode, String noticeNumber, Optional paymentToken, Optional iuv, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); - paymentToken.ifPresent(pt->{ - paramList.add(new SqlParameter("@paymentToken", pt)); - }); - iuv.ifPresent(pt->{ - paramList.add(new SqlParameter("@iuv", pt)); - }); - - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.noticeNumber = @noticeNumber" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" + - (paymentToken.isPresent()? " and c.paymentInfo.paymentToken = @paymentToken" : "") + - (paymentToken.isPresent()? " and c.paymentInfo.iuv = @iuv" : "") - ) - .setParameters(paramList); - return query(q); - } - public CosmosPagedIterable countEventsByCiAndNN(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); - + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@noticeNumber", noticeNumber), + new SqlParameter("@from", dateFrom.atStartOfDay()), + new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + ); SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.noticeNumber = @noticeNumber" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" - ) - .setParameters(paramList); + " and c.timestamp > @from" + + " and c.timestamp < @to" + ).setParameters(paramList); return queryCount(q); } public CosmosPagedIterable countEventsByCiAndIUV(String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@iuv", iuv)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@iuv", iuv), + new SqlParameter("@from", dateFrom.atStartOfDay()), + new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + ); SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java index e03ae15..f0d8290 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java @@ -33,13 +33,21 @@ public class CosmosNegBizEventClient { private static String dbname = "db"; private static String tablename = "negative-biz-events"; + private CosmosClient client; + @Inject Logger log; + private CosmosClient getClient(){ + if(client==null){ + client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); + } + return client; + } + private CosmosPagedIterable query(SqlQuerySpec query){ log.info("executing query:"+query.getQueryText()); - CosmosClient client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); - CosmosContainer container = client.getDatabase(dbname).getContainer(tablename); + CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); return container.queryItems(query, new CosmosQueryRequestOptions(), NegativeBizEvent.class); } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java index 1d7e273..332b7cd 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java @@ -30,6 +30,7 @@ public class ReTableService { public TableClient getTableClient(){ if(tableServiceClient==null){ tableServiceClient = new TableServiceClientBuilder().connectionString(connString).buildClient(); + tableServiceClient.createTableIfNotExists(tableName); } return tableServiceClient.getTableClient(tableName); } @@ -65,9 +66,11 @@ private EventEntity tableEntityToEventEntity(TableEntity e){ } public List findReByCiAndNN(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber){ + + String filter = String.format("idDominio eq '%s' and noticeNumber eq '%s' and esito eq 'CAMBIO_STATO'" + + " and PartitionKey ge '%s' and PartitionKey le '%s'",creditorInstitution, noticeNumber,datefrom,dateTo); ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and noticeNumber eq '%s' and esito eq 'CAMBIO_STATO'", - datefrom,dateTo, creditorInstitution, noticeNumber)) + .setFilter(filter) .setSelect(propertiesToSelect); return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java index 93162a6..a2e30fe 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java @@ -7,6 +7,7 @@ import lombok.Data; import lombok.NoArgsConstructor; +import java.time.LocalDateTime; import java.util.List; @Data @@ -28,4 +29,5 @@ public class PositiveBizEvent { private PaymentInfo paymentInfo; private List transferList; private Object transactionDetails; + private LocalDateTime timestamp; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index f6bbfad..80a1aef 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -48,7 +48,7 @@ public class WorkerService { ReTableService reTableService; private PaymentInfo eventToPaymentInfo(ConfigDataV1 config,EventEntity ee){ - String brokerid = config.getChannels().get(ee.getCanale()).getBrokerPspCode(); + String brokerid = Optional.ofNullable(config.getChannels().get(ee.getCanale())).map(s->s.getBrokerPspCode()).orElse(null); return PaymentInfo.builder() .pspId(ee.getPsp()) .nodeId(ee.getServiceIdentifier()) @@ -116,7 +116,7 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndNN(dateFrom, dateTo, organizationFiscalCode, noticeNumber); + List reStorageEvents = reTableService.findReByCiAndNN(dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, noticeNumber); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); @@ -128,8 +128,8 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, Optional pos = positiveBizClient.countEventsByCiAndNN( lastEvent.getIdDominio(), lastEvent.getNoticeNumber(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(pos.isPresent() && pos.get().getCount()>0){ outcome = outcomeOK; @@ -137,8 +137,8 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, Optional neg = negativeBizClient.findEventsByCiAndNN( lastEvent.getIdDominio(), lastEvent.getNoticeNumber(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(neg.isPresent()){ if(!neg.get().getReAwakable()){ @@ -152,8 +152,8 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, }).collect(Collectors.toList()); return TransactionResponse.builder() - .dateFrom(dateFrom) - .dateTo(dateTo) + .dateFrom(dateRequest.getFrom()) + .dateTo(dateRequest.getTo()) .payments(collect) .build(); @@ -165,7 +165,7 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, LocalDate dateTo){ DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndIUV(dateFrom, dateTo, organizationFiscalCode, iuv); + List reStorageEvents = reTableService.findReByCiAndIUV(dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, iuv); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); @@ -177,8 +177,8 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, Optional pos = positiveBizClient.countEventsByCiAndIUV( lastEvent.getIdDominio(), lastEvent.getIuv(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(pos.isPresent() && pos.get().getCount()>0){ outcome = outcomeOK; @@ -186,8 +186,8 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, Optional neg = negativeBizClient.findEventsByCiAndIUV( lastEvent.getIdDominio(), lastEvent.getIuv(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(neg.isPresent()){ if(!neg.get().getReAwakable()){ @@ -212,7 +212,8 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizationFiscalCode, String noticeNumber, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndNNAndToken(dateFrom, dateTo, organizationFiscalCode, noticeNumber,paymentToken); + List reStorageEvents = reTableService.findReByCiAndNNAndToken(dateRequest.getFrom(), + dateRequest.getTo(), organizationFiscalCode, noticeNumber,paymentToken); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); List collect = reGroups.keySet().stream().map(gkey->{ @@ -225,8 +226,8 @@ public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizat lastEvent.getIdDominio(), lastEvent.getIuv(), lastEvent.getCcp(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(pos.isPresent()){ outcome = outcomeOK; @@ -237,8 +238,8 @@ public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizat lastEvent.getIdDominio(), lastEvent.getIuv(), lastEvent.getPaymentToken(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(neg.isPresent()){ if(!neg.get().getReAwakable()){ @@ -262,7 +263,8 @@ public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizat public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndIUVAndCCP(dateFrom, dateTo, organizationFiscalCode, iuv,ccp); + List reStorageEvents = reTableService.findReByCiAndIUVAndCCP(dateRequest.getFrom(), + dateRequest.getTo(), organizationFiscalCode, iuv,ccp); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); @@ -276,8 +278,8 @@ public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, lastEvent.getIdDominio(), lastEvent.getIuv(), lastEvent.getCcp(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(pos.isPresent()){ outcome = outcomeOK; @@ -288,8 +290,8 @@ public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, lastEvent.getIdDominio(), lastEvent.getIuv(), lastEvent.getPaymentToken(), - dateFrom, - dateTo + dateRequest.getFrom(), + dateRequest.getTo() ).stream().findFirst(); if(neg.isPresent()){ if(!neg.get().getReAwakable()){ @@ -321,8 +323,8 @@ else if (dateFrom != null && dateTo != null && dateFrom.isAfter(dateTo)) { throw new AppException(AppErrorCodeMessageEnum.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from must be before date to"); } if (dateFrom == null && dateTo == null) { - dateFrom = LocalDate.now(); - dateTo = dateFrom.minusDays(10); + dateTo = LocalDate.now(); + dateFrom = dateTo.minusDays(10); } return DateRequest.builder() .from(dateFrom) diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java b/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java index 989366d..ffc7df6 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java @@ -3,6 +3,7 @@ public class StatusUtil { public static String statoByReStatus(String reStatus){ + if(reStatus == null) return null; switch (reStatus) { case "payment_PAID": case "payment_PAID_NORPT": diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java new file mode 100644 index 0000000..910872f --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java @@ -0,0 +1,19 @@ +package it.gov.pagopa.nodetsworker.util; + +import java.util.function.Consumer; +import java.util.function.Function; + +public class Util { + public static String ifNotNull(Object o,String s){ + if(o!=null){ + return s; + }else{ + return ""; + } + } + public static void ifNotNull(Object o, Function func){ + if(o!=null){ + func.apply(null); + } + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 11d154b..fad6fd1 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -37,7 +37,6 @@ quarkus.otel.enabled=false %dev.quarkus.otel.enabled=false %test.quarkus.otel.enabled=false %openapi.quarkus.otel.enabled=false -%openapi_internal.quarkus.otel.enabled=false quarkus.otel.exporter.otlp.traces.endpoint=${OTEL_ENDPOINT} quarkus.otel.exporter.otlp.traces.headers=${OTEL_AUTH_BEARER} %dev.quarkus.otel.exporter.otlp.traces.endpoint=http://localhost:4317 @@ -67,12 +66,15 @@ quarkus.smallrye-openapi.servers=\\$\{host\}/tenchinal-support/api/v1 - APIM quarkus.mongodb.events.connection-string=${MONGODB_EVENTS_CONNECTION_STRING} quarkus.mongodb.events.database=nodo_re -biz.endpoint=${COSMOS_BIZ_ENDPOINT} -biz.key=${COSMOS_BIZ_KEY} -bizneg.endpoint=${COSMOS_NEG_BIZ_ENDPOINT} -bizneg.key=${COSMOS_NEG_BIZ_KEY} +biz.endpoint=${COSMOS_BIZ_ENDPOINT:${mockserver.biz.endpoint}} +biz.key=${COSMOS_BIZ_KEY:${mockserver.biz.key}} +bizneg.endpoint=${COSMOS_NEG_BIZ_ENDPOINT:${mockserver.biz.endpoint}} +bizneg.key=${COSMOS_NEG_BIZ_KEY:${mockserver.biz.key}} + re-table-storage.table-name=events -re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING} +re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING:${mockserver.azurite.connection-string}} +%dev.re-table-storage.connection-string=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1; + ################### ## ADAPTER API CONFIG CACHE @@ -86,7 +88,6 @@ quarkus.rest-client.logging.scope=request-response ################### %test.quarkus.scheduler.enabled=false %openapi.quarkus.scheduler.enabled=false -%openapi_internal.quarkus.scheduler.enabled=false # By default, the syntax used for cron expressions is based on Quartz - https://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html # You can change the syntax using the following property: @@ -95,7 +96,6 @@ api_config_cache.cron.expr=*/15 * * * * ? startconfig.enabled=true %openapi.startconfig.enabled=false -%openapi_internal.startconfig.enabled=false adapter.api_config_cache.api-key-name=Ocp-Apim-Subscription-Key adapter.api_config_cache.api-key-value=${ADAPTER_API_CONFIG_CACHE_API_KEY:12345} adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:${quarkus.mockserver.endpoint}} @@ -112,3 +112,6 @@ operations.filter=".*" %test.quarkus.mockserver.devservices.log=false quarkus.test.continuous-testing=disabled + + +quarkus.http.test-port=8083 \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java new file mode 100644 index 0000000..975e624 --- /dev/null +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java @@ -0,0 +1,98 @@ +package it.gov.pagopa.nodetsworker.resources; + +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.cosmos.models.PartitionKey; +import com.azure.data.tables.TableClient; +import com.azure.data.tables.TableServiceClientBuilder; +import io.quarkiverse.mockserver.test.MockServerTestResource; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.common.mapper.TypeRef; +import it.gov.pagopa.nodetsworker.models.PaymentInfo; +import it.gov.pagopa.nodetsworker.models.TransactionResponse; +import it.gov.pagopa.nodetsworker.util.AppConstantTestHelper; +import it.gov.pagopa.nodetsworker.util.AzuriteResource; +import it.gov.pagopa.nodetsworker.util.CosmosResource; +import lombok.SneakyThrows; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; +import java.util.Random; + +import static io.restassured.RestAssured.given; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.PA_CODE; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.SP03_NN; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; + +@QuarkusTest +@QuarkusTestResource(MockServerTestResource.class) +@QuarkusTestResource(AzuriteResource.class) +@QuarkusTestResource(CosmosResource.class) +class ResourceTest { + + @ConfigProperty(name = "re-table-storage.connection-string") + String connString; + + @ConfigProperty(name = "biz.endpoint") + String bizendpoint; + + @ConfigProperty(name = "biz.key") + String bizkey; + + private TableClient tableClient; + private CosmosClient clientbiz; + + private TableClient getTableClient(){ + if(tableClient==null){ + tableClient = new TableServiceClientBuilder().connectionString(connString).buildClient().getTableClient("events"); + tableClient.createTable(); + } + return tableClient; + } + + private CosmosClient getCosmosClient(){ + if(clientbiz==null) { + clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); + clientbiz.createDatabase("db"); + clientbiz.getDatabase("db").createContainerIfNotExists("biz-events","/timestamp"); + clientbiz.getDatabase("db").createContainerIfNotExists("negative-biz-events","/timestamp"); + } + return clientbiz; + + } + + @SneakyThrows + @Test + @DisplayName("OK") + void testOK() { + String noticeNumber = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String url = SP03_NN.formatted(PA_CODE, noticeNumber); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber)); +// getCosmosClient();//.getDatabase("db").getContainer("biz-events"); +// .createItem( +// AppConstantTestHelper.newBiz(PA_CODE, noticeNumber), +// new CosmosItemRequestOptions() +// ); + + TransactionResponse res = given() + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentInfo o = (PaymentInfo)res.getPayments().get(0); + assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); + } + +} diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java new file mode 100644 index 0000000..34f5c8d --- /dev/null +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java @@ -0,0 +1,69 @@ +package it.gov.pagopa.nodetsworker.util; + +import com.azure.data.tables.models.TableEntity; +import io.restassured.http.Header; +import it.gov.pagopa.nodetsworker.repository.model.*; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.UUID; + +public class AppConstantTestHelper { + + public static final String SP03_NN = "/organizations/%s/noticeNumber/%s"; + public static final String SP03_IUV = "/organizations/%s/iuv/%s"; + public static final String SP04_NN = "/organizations/%s/iuv/%s/paymentToken/%s"; + public static final String SP04_IUV = "/organizations/%s/iuv/%s/ccp/%s"; + + public static final String PA_CODE = "12345678900"; + public static final String outcomeOK = "OK"; + + public static final Header HEADER = new Header("Content-Type", "application/json"); + + public static final TableEntity newRe(String pa,String noticeNumber){ + TableEntity entity = new TableEntity(LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ISO_DATE_TIME), String.valueOf(noticeNumber)); + entity.addProperty("idDominio",pa); + entity.addProperty("noticeNumber",noticeNumber); + entity.addProperty("esito","CAMBIO_STATO"); + entity.addProperty("paymentToken","pt_"+noticeNumber); + return entity; + } + + public static final PositiveBizEvent newBiz(String pa, String noticeNumber){ + PositiveBizEvent p = PositiveBizEvent.builder() + .id(UUID.randomUUID().toString()) + .timestamp(LocalDateTime.now()) + .psp( + Psp.builder() + .psp("pspTest") + .idChannel("canaleTest") + .build() + ) + .creditor( + Creditor.builder().idPA(pa).build() + ).debtorPosition( + DebtorPosition.builder().noticeNumber(noticeNumber).build() + ).paymentInfo( + PaymentInfo.builder().paymentDateTime(LocalDateTime.now().minusDays(1)).build() + ) + .build(); + return p; + } + public static final NegativeBizEvent newNegBiz(String pa, String noticeNumber){ + NegativeBizEvent p = NegativeBizEvent.builder() + .id(UUID.randomUUID().toString()) + .creditor( + Creditor.builder().idPA(pa).build() + ).debtorPosition( + DebtorPosition.builder().noticeNumber(noticeNumber).build() + ).paymentInfo( + NegativePaymentInfo.builder() + .paymentDateTime(LocalDateTime.now().minusDays(1)) + .build() + ) + .build(); + return p; + } +} diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java new file mode 100644 index 0000000..c7746f7 --- /dev/null +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java @@ -0,0 +1,40 @@ +package it.gov.pagopa.nodetsworker.util; + +import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; +import lombok.SneakyThrows; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.utility.DockerImageName; + +import java.util.HashMap; +import java.util.Map; + +public class AzuriteResource implements QuarkusTestResourceLifecycleManager { + + private GenericContainer azurite; + + @SneakyThrows + @Override + public Map start() { + azurite = + new GenericContainer(DockerImageName.parse("mcr.microsoft.com/azure-storage/azurite")) + .withExposedPorts(10000, 10001, 10002); + azurite.start(); + + String connectStr = + "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:" + + azurite.getMappedPort(10000) + + "/devstoreaccount1;QueueEndpoint=http://127.0.0.1:" + + azurite.getMappedPort(10001) + + "/devstoreaccount1;TableEndpoint=http://127.0.0.1:" + + azurite.getMappedPort(10002) + + "/devstoreaccount1;"; + Map conf = new HashMap<>(); + conf.put("mockserver.azurite.connection-string", connectStr); + return conf; + } + + @Override + public void stop() { + azurite.stop(); + } +} diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java new file mode 100644 index 0000000..f6c10a2 --- /dev/null +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java @@ -0,0 +1,73 @@ +package it.gov.pagopa.nodetsworker.util; + +import com.github.terma.javaniotcpproxy.StaticTcpProxyConfig; +import com.github.terma.javaniotcpproxy.TcpProxy; +import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; +import lombok.SneakyThrows; +import org.testcontainers.containers.CosmosDBEmulatorContainer; +import org.testcontainers.utility.DockerImageName; + +import java.io.File; +import java.io.FileOutputStream; +import java.net.InetAddress; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CosmosResource implements QuarkusTestResourceLifecycleManager { + + + private static final Integer[] exposedPorts = {8081, 10251, 10252, 10253, 10254}; + + private static CosmosDBEmulatorContainer cosmos = null; + + private static final List startedProxies = new ArrayList<>(); + + @SneakyThrows + @Override + public Map start() { + + cosmos = new CosmosDBEmulatorContainer( + DockerImageName.parse("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest") + ) + .withEnv("AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE", InetAddress.getLocalHost().getHostAddress()) + .withEnv("AZURE_COSMOS_EMULATOR_PARTITION_COUNT", "3") + .withEnv("AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE", "true") + .withExposedPorts(exposedPorts); + + cosmos.start(); + + CosmosResource.startTcpProxy(exposedPorts); + + Path keyStoreFile = File.createTempFile("azure-cosmos-emulator",".keystore").toPath(); + KeyStore keyStore = cosmos.buildNewKeyStore(); + keyStore.store(new FileOutputStream(keyStoreFile.toFile()), cosmos.getEmulatorKey().toCharArray()); + + System.setProperty("javax.net.ssl.trustStore", keyStoreFile.toString()); + System.setProperty("javax.net.ssl.trustStorePassword", cosmos.getEmulatorKey()); + System.setProperty("javax.net.ssl.trustStoreType", "PKCS12"); + + Map conf = new HashMap<>(); + conf.put("mockserver.biz.endpoint", cosmos.getEmulatorEndpoint()); + conf.put("mockserver.biz.key", cosmos.getEmulatorKey()); + return conf; + } + + @Override + public void stop() { + cosmos.stop(); + } + + private static void startTcpProxy(Integer... ports) { + for (Integer port: ports) { + StaticTcpProxyConfig tcpProxyConfig = new StaticTcpProxyConfig(port, cosmos.getHost(), cosmos.getMappedPort(port)); + tcpProxyConfig.setWorkerCount(1); + TcpProxy tcpProxy = new TcpProxy(tcpProxyConfig); + tcpProxy.start(); + startedProxies.add(tcpProxy); + } + } +} From 4f979f2d45c1dab8cc72f50144620f478bb1990d Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 5 Jul 2023 10:08:41 +0200 Subject: [PATCH 06/29] wip --- .../repository/CosmosBizEventClient.java | 42 +++++------ .../repository/CosmosNegBizEventClient.java | 73 +++++++++++-------- .../repository/ReTableService.java | 12 +-- .../repository/model/NegativeBizEvent.java | 7 +- .../repository/model/PositiveBizEvent.java | 1 - .../it/gov/pagopa/nodetsworker/util/Util.java | 15 +++- src/main/resources/application.properties | 2 +- .../nodetsworker/resources/ResourceTest.java | 22 +++--- .../nodetsworker/util/CosmosResource.java | 7 +- 9 files changed, 104 insertions(+), 77 deletions(-) diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java index ba15441..d7b0119 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -34,8 +34,8 @@ public class CosmosBizEventClient { @ConfigProperty(name = "biz.key") private String key; - private static String dbname = "db"; - private static String tablename = "biz-events"; + public static String dbname = "db"; + public static String tablename = "biz-events"; private CosmosClient client; @@ -65,17 +65,16 @@ public CosmosPagedIterable findEventsByCiAndNNAndToken(String new SqlParameter("@organizationFiscalCode", organizationFiscalCode), new SqlParameter("@noticeNumber", noticeNumber), new SqlParameter("@paymentToken", paymentToken), - new SqlParameter("@from", dateFrom.atStartOfDay()), - new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) ); SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.noticeNumber = @noticeNumber" + " and c.paymentInfo.paymentToken = @paymentToken" + - Util.ifNotNull(dateFrom," and c.paymentInfo.paymentDateTime > @from") + - Util.ifNotNull(dateTo," and c.paymentInfo.paymentDateTime < @to") - ) - .setParameters(paramList); + " and c.timestamp > @from" + + " and c.timestamp < @to" + ).setParameters(paramList); return query(q); } @@ -84,17 +83,16 @@ public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String o new SqlParameter("@organizationFiscalCode", organizationFiscalCode), new SqlParameter("@iuv", iuv), new SqlParameter("@ccp", ccp), - new SqlParameter("@from", dateFrom.atStartOfDay()), - new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) ); SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.iuv = @iuv" + " and c.paymentInfo.paymentToken = @ccp" + - Util.ifNotNull(dateFrom," and c.paymentInfo.paymentDateTime > @from") + - Util.ifNotNull(dateTo," and c.paymentInfo.paymentDateTime < @to") - ) - .setParameters(paramList); + " and c.timestamp > @from" + + " and c.timestamp < @to" + ).setParameters(paramList); return query(q); } @@ -102,8 +100,8 @@ public CosmosPagedIterable countEventsByCiAndNN(String organizationFiscal List paramList = Arrays.asList( new SqlParameter("@organizationFiscalCode", organizationFiscalCode), new SqlParameter("@noticeNumber", noticeNumber), - new SqlParameter("@from", dateFrom.atStartOfDay()), - new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) ); SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + @@ -119,18 +117,16 @@ public CosmosPagedIterable countEventsByCiAndIUV(String organizationFisca List paramList = Arrays.asList( new SqlParameter("@organizationFiscalCode", organizationFiscalCode), new SqlParameter("@iuv", iuv), - new SqlParameter("@from", dateFrom.atStartOfDay()), - new SqlParameter("@to", LocalDateTime.of(dateTo, LocalTime.MAX)) + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) ); - SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.iuv = @iuv" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" - ) - .setParameters(paramList); + " and c.timestamp > @from" + + " and c.timestamp < @to" + ).setParameters(paramList); return queryCount(q); } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java index f0d8290..12cfcfb 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java @@ -8,6 +8,7 @@ import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; +import it.gov.pagopa.nodetsworker.util.Util; import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -15,8 +16,11 @@ import org.jboss.logging.Logger; import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -30,8 +34,8 @@ public class CosmosNegBizEventClient { @ConfigProperty(name = "bizneg.key") private String key; - private static String dbname = "db"; - private static String tablename = "negative-biz-events"; + public static String dbname = "db"; + public static String tablename = "negative-biz-events"; private CosmosClient client; @@ -52,69 +56,74 @@ private CosmosPagedIterable query(SqlQuerySpec query){ } public CosmosPagedIterable findEventsByCiAndNN(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@noticeNumber", noticeNumber), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) + ); + SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.noticeNumber = @noticeNumber" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" + " and c.timestamp > @from" + + " and c.timestamp < @to" ) .setParameters(paramList); return query(q); } public CosmosPagedIterable findEventsByCiAndNNAndToken(String organizationFiscalCode, String noticeNumber,String paymentToken, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@noticeNumber", noticeNumber)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@paymentToken", paymentToken)); + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@noticeNumber", noticeNumber), + new SqlParameter("@paymentToken", paymentToken), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) + ); SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.noticeNumber = @noticeNumber" + " and c.paymentInfo.paymentToken = @paymentToken" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" + " and c.timestamp > @from" + + " and c.timestamp < @to" ) .setParameters(paramList); return query(q); } public CosmosPagedIterable findEventsByCiAndIUV(String organizationFiscalCode,String iuv, LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@iuv", iuv)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@iuv", iuv), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) + ); SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.iuv = @iuv" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" + " and c.timestamp > @from" + + " and c.timestamp < @to" ) .setParameters(paramList); return query(q); } public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String organizationFiscalCode,String iuv, String ccp,LocalDate dateFrom, LocalDate dateTo){ - List paramList = new ArrayList(); - paramList.add(new SqlParameter("@organizationFiscalCode", organizationFiscalCode)); - paramList.add(new SqlParameter("@iuv", iuv)); - paramList.add(new SqlParameter("@ccp", ccp)); - paramList.add(new SqlParameter("@from", dateFrom.format(DateTimeFormatter.ISO_DATE))); - paramList.add(new SqlParameter("@to", dateTo.format(DateTimeFormatter.ISO_DATE))); + List paramList = Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@iuv", iuv), + new SqlParameter("@ccp", ccp), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) + ); SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.iuv = @iuv" + " and c.paymentInfo.paymentToken = @ccp" + - " and c.paymentInfo.paymentDateTime > @from" + - " and c.paymentInfo.paymentDateTime < @to" + " and c.timestamp > @from" + + " and c.timestamp < @to" ) .setParameters(paramList); return query(q); diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java index 332b7cd..1252520 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java @@ -6,10 +6,12 @@ import com.azure.data.tables.models.ListEntitiesOptions; import com.azure.data.tables.models.TableEntity; import it.gov.pagopa.nodetsworker.repository.model.EventEntity; +import it.gov.pagopa.nodetsworker.util.Util; import jakarta.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.config.inject.ConfigProperty; import java.time.LocalDate; +import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -67,8 +69,8 @@ private EventEntity tableEntityToEventEntity(TableEntity e){ public List findReByCiAndNN(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber){ - String filter = String.format("idDominio eq '%s' and noticeNumber eq '%s' and esito eq 'CAMBIO_STATO'" + - " and PartitionKey ge '%s' and PartitionKey le '%s'",creditorInstitution, noticeNumber,datefrom,dateTo); + String filter = String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and noticeNumber eq '%s' and esito eq 'CAMBIO_STATO'", + Util.format(datefrom),Util.format(dateTo),creditorInstitution, noticeNumber); ListEntitiesOptions options = new ListEntitiesOptions() .setFilter(filter) .setSelect(propertiesToSelect); @@ -77,7 +79,7 @@ public List findReByCiAndNN(LocalDate datefrom, LocalDate dateTo, S public List findReByCiAndIUV(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv){ ListEntitiesOptions options = new ListEntitiesOptions() .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and iuv eq '%s' and esito eq 'CAMBIO_STATO'", - datefrom,dateTo, creditorInstitution, iuv)) + Util.format(datefrom),Util.format(dateTo), creditorInstitution, iuv)) .setSelect(propertiesToSelect); return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); } @@ -85,7 +87,7 @@ public List findReByCiAndIUV(LocalDate datefrom, LocalDate dateTo, public List findReByCiAndNNAndToken(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber, String paymentToken){ ListEntitiesOptions options = new ListEntitiesOptions() .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and noticeNumber eq '%s' and paymentToken eq '%s' and esito eq 'CAMBIO_STATO'", - datefrom,dateTo, creditorInstitution, noticeNumber,paymentToken)) + Util.format(datefrom),Util.format(dateTo), creditorInstitution, noticeNumber,paymentToken)) .setSelect(propertiesToSelect); return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); } @@ -93,7 +95,7 @@ public List findReByCiAndNNAndToken(LocalDate datefrom, LocalDate d public List findReByCiAndIUVAndCCP(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv,String ccp){ ListEntitiesOptions options = new ListEntitiesOptions() .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and iuv eq '%s' and ccp eq '%s' and esito eq 'CAMBIO_STATO'", - datefrom,dateTo, creditorInstitution, iuv,ccp)) + Util.format(datefrom),Util.format(dateTo), creditorInstitution, iuv,ccp)) .setSelect(propertiesToSelect); return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java index 64f2176..aa223b6 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java @@ -1,12 +1,18 @@ package it.gov.pagopa.nodetsworker.repository.model; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; import java.util.List; @Data @Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) public class NegativeBizEvent { private String version; private String id; @@ -20,5 +26,4 @@ public class NegativeBizEvent { private NegativePaymentInfo paymentInfo; private List transferList; private Object transactionDetails; - } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java index a2e30fe..84d478e 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java @@ -12,7 +12,6 @@ @Data @Builder -@MongoEntity(collection = "biz-events", clientName = "biz") @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java index 910872f..0e8f381 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java @@ -1,6 +1,11 @@ package it.gov.pagopa.nodetsworker.util; -import java.util.function.Consumer; +import jakarta.ejb.Local; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.function.Function; public class Util { @@ -16,4 +21,12 @@ public static void ifNotNull(Object o, Function func){ func.apply(null); } } + + public static Long toMillis(LocalDateTime d){ + return d.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + } + + public static String format(LocalDate d){ + return d.format(DateTimeFormatter.ISO_DATE); + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index fad6fd1..2490d0f 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -73,7 +73,7 @@ bizneg.key=${COSMOS_NEG_BIZ_KEY:${mockserver.biz.key}} re-table-storage.table-name=events re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING:${mockserver.azurite.connection-string}} -%dev.re-table-storage.connection-string=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1; +%dev.re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING} ################### diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java index 975e624..bed7e59 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java @@ -12,6 +12,8 @@ import io.restassured.common.mapper.TypeRef; import it.gov.pagopa.nodetsworker.models.PaymentInfo; import it.gov.pagopa.nodetsworker.models.TransactionResponse; +import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; +import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; import it.gov.pagopa.nodetsworker.util.AppConstantTestHelper; import it.gov.pagopa.nodetsworker.util.AzuriteResource; import it.gov.pagopa.nodetsworker.util.CosmosResource; @@ -56,16 +58,16 @@ private TableClient getTableClient(){ return tableClient; } - private CosmosClient getCosmosClient(){ - if(clientbiz==null) { - clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); - clientbiz.createDatabase("db"); - clientbiz.getDatabase("db").createContainerIfNotExists("biz-events","/timestamp"); - clientbiz.getDatabase("db").createContainerIfNotExists("negative-biz-events","/timestamp"); - } - return clientbiz; - - } +// private CosmosClient getCosmosClient(){ +// if(clientbiz==null) { +// clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); +// clientbiz.createDatabaseIfNotExists(CosmosBizEventClient.dbname); +// clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosBizEventClient.tablename,"/timestamp"); +// clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosNegBizEventClient.tablename,"/timestamp"); +// } +// return clientbiz; +// +// } @SneakyThrows @Test diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java index f6c10a2..dc938b5 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java @@ -31,11 +31,11 @@ public class CosmosResource implements QuarkusTestResourceLifecycleManager { public Map start() { cosmos = new CosmosDBEmulatorContainer( - DockerImageName.parse("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest") + DockerImageName.parse("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator") ) .withEnv("AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE", InetAddress.getLocalHost().getHostAddress()) .withEnv("AZURE_COSMOS_EMULATOR_PARTITION_COUNT", "3") - .withEnv("AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE", "true") + .withEnv("AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE", "false") .withExposedPorts(exposedPorts); cosmos.start(); @@ -51,7 +51,7 @@ public Map start() { System.setProperty("javax.net.ssl.trustStoreType", "PKCS12"); Map conf = new HashMap<>(); - conf.put("mockserver.biz.endpoint", cosmos.getEmulatorEndpoint()); + conf.put("mockserver.biz.endpoint", "https://" + InetAddress.getLocalHost().getHostAddress() + ":" + cosmos.getMappedPort(8081)); conf.put("mockserver.biz.key", cosmos.getEmulatorKey()); return conf; } @@ -59,6 +59,7 @@ public Map start() { @Override public void stop() { cosmos.stop(); + startedProxies.forEach(p->p.shutdown()); } private static void startTcpProxy(Integer... ports) { From cf612207bbb86540c1c72d34ed38b98c901313ca Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 5 Jul 2023 11:50:43 +0200 Subject: [PATCH 07/29] wip --- .../repository/model/NegativeBizEvent.java | 1 + .../repository/model/PositiveBizEvent.java | 2 +- src/main/resources/application.properties | 2 +- .../nodetsworker/resources/ResourceTest.java | 135 ++++++++++++++---- .../util/AppConstantTestHelper.java | 23 +-- .../nodetsworker/util/CosmosResource.java | 2 +- 6 files changed, 130 insertions(+), 35 deletions(-) diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java index aa223b6..2e8501b 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java @@ -26,4 +26,5 @@ public class NegativeBizEvent { private NegativePaymentInfo paymentInfo; private List transferList; private Object transactionDetails; + private Long timestamp; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java index 84d478e..4f179ee 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java @@ -28,5 +28,5 @@ public class PositiveBizEvent { private PaymentInfo paymentInfo; private List transferList; private Object transactionDetails; - private LocalDateTime timestamp; + private Long timestamp; } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 2490d0f..fad6fd1 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -73,7 +73,7 @@ bizneg.key=${COSMOS_NEG_BIZ_KEY:${mockserver.biz.key}} re-table-storage.table-name=events re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING:${mockserver.azurite.connection-string}} -%dev.re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING} +%dev.re-table-storage.connection-string=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1; ################### diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java index bed7e59..ff49297 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java @@ -3,8 +3,8 @@ import com.azure.cosmos.CosmosClient; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.models.CosmosItemRequestOptions; -import com.azure.cosmos.models.PartitionKey; import com.azure.data.tables.TableClient; +import com.azure.data.tables.TableServiceClient; import com.azure.data.tables.TableServiceClientBuilder; import io.quarkiverse.mockserver.test.MockServerTestResource; import io.quarkus.test.common.QuarkusTestResource; @@ -22,12 +22,10 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.time.LocalDateTime; import java.util.Random; import static io.restassured.RestAssured.given; -import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.PA_CODE; -import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.SP03_NN; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; @@ -52,36 +50,35 @@ class ResourceTest { private TableClient getTableClient(){ if(tableClient==null){ - tableClient = new TableServiceClientBuilder().connectionString(connString).buildClient().getTableClient("events"); - tableClient.createTable(); + TableServiceClient tableServiceClient = new TableServiceClientBuilder().connectionString(connString).buildClient(); + tableServiceClient.createTableIfNotExists("events"); + tableClient = tableServiceClient.getTableClient("events"); } return tableClient; } -// private CosmosClient getCosmosClient(){ -// if(clientbiz==null) { -// clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); -// clientbiz.createDatabaseIfNotExists(CosmosBizEventClient.dbname); -// clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosBizEventClient.tablename,"/timestamp"); -// clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosNegBizEventClient.tablename,"/timestamp"); -// } -// return clientbiz; -// -// } + private CosmosClient getCosmosClient(){ + if(clientbiz==null) { + clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); + clientbiz.createDatabaseIfNotExists(CosmosBizEventClient.dbname); + clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosBizEventClient.tablename,"/timestamp"); + clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosNegBizEventClient.tablename,"/timestamp"); + } + return clientbiz; + + } @SneakyThrows @Test - @DisplayName("OK") - void testOK() { + @DisplayName("by ci and nn with positive") + void test1() { String noticeNumber = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); String url = SP03_NN.formatted(PA_CODE, noticeNumber); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber)); -// getCosmosClient();//.getDatabase("db").getContainer("biz-events"); -// .createItem( -// AppConstantTestHelper.newBiz(PA_CODE, noticeNumber), -// new CosmosItemRequestOptions() -// ); + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, noticeNumber,null),new CosmosItemRequestOptions() + ); TransactionResponse res = given() .when() @@ -95,6 +92,96 @@ void testOK() { assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); + } + + @SneakyThrows + @Test + @DisplayName("by ci and nn with negative") + void test2() { + String noticeNumber = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String url = SP03_NN.formatted(PA_CODE, noticeNumber); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, noticeNumber,null,false),new CosmosItemRequestOptions() + ); + + TransactionResponse res = given() + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentInfo o = (PaymentInfo)res.getPayments().get(0); + assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); + } + + @SneakyThrows + @Test + @DisplayName("by ci and iuv with positive") + void test3() { + String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String url = SP03_IUV.formatted(PA_CODE, iuv); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, null, iuv),new CosmosItemRequestOptions() + ); + + TransactionResponse res = given() + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentInfo o = (PaymentInfo)res.getPayments().get(0); + assertThat(o.getIuv(),equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); + } + + @SneakyThrows + @Test + @DisplayName("by ci and iuv with negative") + void test4() { + String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String url = SP03_IUV.formatted(PA_CODE, iuv); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, null,iuv,false),new CosmosItemRequestOptions() + ); + + TransactionResponse res = given() + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentInfo o = (PaymentInfo)res.getPayments().get(0); + assertThat(o.getIuv(),equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); } } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java index 34f5c8d..c210f93 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java @@ -4,10 +4,8 @@ import io.restassured.http.Header; import it.gov.pagopa.nodetsworker.repository.model.*; -import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.HashMap; import java.util.UUID; public class AppConstantTestHelper { @@ -19,22 +17,29 @@ public class AppConstantTestHelper { public static final String PA_CODE = "12345678900"; public static final String outcomeOK = "OK"; + public static final String outcomeKO = "KO"; public static final Header HEADER = new Header("Content-Type", "application/json"); - public static final TableEntity newRe(String pa,String noticeNumber){ + public static final TableEntity newRe(String pa,String noticeNumber,String iuv){ TableEntity entity = new TableEntity(LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ISO_DATE_TIME), String.valueOf(noticeNumber)); entity.addProperty("idDominio",pa); entity.addProperty("noticeNumber",noticeNumber); + entity.addProperty("iuv",iuv); entity.addProperty("esito","CAMBIO_STATO"); entity.addProperty("paymentToken","pt_"+noticeNumber); + entity.addProperty("ccp","ccp_"+iuv); + entity.addProperty("stazione","77777777777_01"); + entity.addProperty("psp","pspTest"); + entity.addProperty("canale","canaleTest"); + entity.addProperty("status","PAID"); return entity; } - public static final PositiveBizEvent newBiz(String pa, String noticeNumber){ + public static final PositiveBizEvent newPositiveBiz(String pa,String noticeNumber, String iuv){ PositiveBizEvent p = PositiveBizEvent.builder() .id(UUID.randomUUID().toString()) - .timestamp(LocalDateTime.now()) + .timestamp(Util.toMillis(LocalDateTime.now())) .psp( Psp.builder() .psp("pspTest") @@ -44,25 +49,27 @@ public static final PositiveBizEvent newBiz(String pa, String noticeNumber){ .creditor( Creditor.builder().idPA(pa).build() ).debtorPosition( - DebtorPosition.builder().noticeNumber(noticeNumber).build() + DebtorPosition.builder().modelType("1").iuv(iuv).noticeNumber(noticeNumber).build() ).paymentInfo( PaymentInfo.builder().paymentDateTime(LocalDateTime.now().minusDays(1)).build() ) .build(); return p; } - public static final NegativeBizEvent newNegBiz(String pa, String noticeNumber){ + public static final NegativeBizEvent newNegBiz(String pa, String noticeNumber, String iuv,boolean reawakable){ NegativeBizEvent p = NegativeBizEvent.builder() .id(UUID.randomUUID().toString()) + .timestamp(Util.toMillis(LocalDateTime.now())) .creditor( Creditor.builder().idPA(pa).build() ).debtorPosition( - DebtorPosition.builder().noticeNumber(noticeNumber).build() + DebtorPosition.builder().iuv(iuv).noticeNumber(noticeNumber).build() ).paymentInfo( NegativePaymentInfo.builder() .paymentDateTime(LocalDateTime.now().minusDays(1)) .build() ) + .reAwakable(reawakable) .build(); return p; } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java index dc938b5..ffaeb1a 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java @@ -51,7 +51,7 @@ public Map start() { System.setProperty("javax.net.ssl.trustStoreType", "PKCS12"); Map conf = new HashMap<>(); - conf.put("mockserver.biz.endpoint", "https://" + InetAddress.getLocalHost().getHostAddress() + ":" + cosmos.getMappedPort(8081)); + conf.put("mockserver.biz.endpoint", cosmos.getEmulatorEndpoint()); conf.put("mockserver.biz.key", cosmos.getEmulatorKey()); return conf; } From 17d66e3d7a886d7b4378d69d263e60cc67a4e78e Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 5 Jul 2023 18:04:47 +0200 Subject: [PATCH 08/29] wip --- .../repository/CosmosNegBizEventClient.java | 35 --- .../repository/ReTableService.java | 6 +- .../resources/WorkerResource.java | 18 +- .../exceptionmapper/ErrorResponse.java | 49 +++ .../exceptionmapper/ExceptionMappers.java | 278 ++++++++++++++++++ .../response/FindEventsResponse.java | 25 -- .../response}/TransactionResponse.java | 3 +- .../nodetsworker/service/WorkerService.java | 155 +++++----- .../{ResourceTest.java => Sp03Test.java} | 61 +++- .../nodetsworker/resources/Sp04Test.java | 234 +++++++++++++++ .../util/AppConstantTestHelper.java | 12 +- 11 files changed, 716 insertions(+), 160 deletions(-) create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java delete mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java rename src/main/java/it/gov/pagopa/nodetsworker/{models => resources/response}/TransactionResponse.java (84%) rename src/test/java/it/gov/pagopa/nodetsworker/resources/{ResourceTest.java => Sp03Test.java} (80%) create mode 100644 src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java index 12cfcfb..fb6def0 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java @@ -55,23 +55,6 @@ private CosmosPagedIterable query(SqlQuerySpec query){ return container.queryItems(query, new CosmosQueryRequestOptions(), NegativeBizEvent.class); } - public CosmosPagedIterable findEventsByCiAndNN(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@noticeNumber", noticeNumber), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); - - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.noticeNumber = @noticeNumber" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ) - .setParameters(paramList); - return query(q); - } public CosmosPagedIterable findEventsByCiAndNNAndToken(String organizationFiscalCode, String noticeNumber,String paymentToken, LocalDate dateFrom, LocalDate dateTo){ List paramList = Arrays.asList( new SqlParameter("@organizationFiscalCode", organizationFiscalCode), @@ -91,24 +74,6 @@ public CosmosPagedIterable findEventsByCiAndNNAndToken(String return query(q); } - public CosmosPagedIterable findEventsByCiAndIUV(String organizationFiscalCode,String iuv, LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@iuv", iuv), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); - - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.iuv = @iuv" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ) - .setParameters(paramList); - return query(q); - } - public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String organizationFiscalCode,String iuv, String ccp,LocalDate dateFrom, LocalDate dateTo){ List paramList = Arrays.asList( new SqlParameter("@organizationFiscalCode", organizationFiscalCode), diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java index 1252520..b59aa67 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java @@ -78,7 +78,7 @@ public List findReByCiAndNN(LocalDate datefrom, LocalDate dateTo, S } public List findReByCiAndIUV(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv){ ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and iuv eq '%s' and esito eq 'CAMBIO_STATO'", + .setFilter(String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and iuv eq '%s' and esito eq 'CAMBIO_STATO'", Util.format(datefrom),Util.format(dateTo), creditorInstitution, iuv)) .setSelect(propertiesToSelect); return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); @@ -86,7 +86,7 @@ public List findReByCiAndIUV(LocalDate datefrom, LocalDate dateTo, public List findReByCiAndNNAndToken(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber, String paymentToken){ ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and noticeNumber eq '%s' and paymentToken eq '%s' and esito eq 'CAMBIO_STATO'", + .setFilter(String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and noticeNumber eq '%s' and paymentToken eq '%s' and esito eq 'CAMBIO_STATO'", Util.format(datefrom),Util.format(dateTo), creditorInstitution, noticeNumber,paymentToken)) .setSelect(propertiesToSelect); return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); @@ -94,7 +94,7 @@ public List findReByCiAndNNAndToken(LocalDate datefrom, LocalDate d public List findReByCiAndIUVAndCCP(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv,String ccp){ ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(String.format("PartitionKey gt '%s' and PartitionKey lt '%s' and idDominio eq '%s' and iuv eq '%s' and ccp eq '%s' and esito eq 'CAMBIO_STATO'", + .setFilter(String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and iuv eq '%s' and ccp eq '%s' and esito eq 'CAMBIO_STATO'", Util.format(datefrom),Util.format(dateTo), creditorInstitution, iuv,ccp)) .setSelect(propertiesToSelect); return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java index 92c9fb8..9e51b04 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java @@ -1,22 +1,18 @@ package it.gov.pagopa.nodetsworker.resources; import it.gov.pagopa.nodetsworker.models.ProblemJson; -import it.gov.pagopa.nodetsworker.models.TransactionResponse; +import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; import it.gov.pagopa.nodetsworker.service.WorkerService; +import jakarta.inject.Inject; +import jakarta.validation.constraints.NotNull; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.openapi.annotations.media.Content; import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; -import jakarta.inject.Inject; -import jakarta.validation.constraints.NotNull; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.PathParam; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.QueryParam; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; import java.io.Serializable; import java.time.LocalDate; @@ -92,7 +88,7 @@ public Response useCaseSP04_byIUV_PaymentToken( @QueryParam("dateFrom") LocalDate dateFrom, @QueryParam("dateTo") LocalDate dateTo ) { - return Response.ok(workerService.getInfoByNoticeNumberAndPaymentToken(organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)).build(); + return Response.ok(workerService.getAttemptByNoticeNumberAndPaymentToken(organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)).build(); } @APIResponses(value = { diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java new file mode 100644 index 0000000..ad892be --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java @@ -0,0 +1,49 @@ +package it.gov.pagopa.nodetsworker.resources.exceptionmapper; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.quarkus.runtime.annotations.RegisterForReflection; +import lombok.*; +import lombok.extern.jackson.Jacksonized; +import org.eclipse.microprofile.openapi.annotations.media.Schema; + +import java.util.List; + +@Getter +@Builder +@Jacksonized +@JsonPropertyOrder({"errorId", "httpStatusCode", "httpStatusDescription", "appErrorCode", "errors"}) +@RegisterForReflection +public class ErrorResponse { + + @JsonInclude(JsonInclude.Include.NON_NULL) + @Schema(example = "50905466-1881-457b-b42f-fb7b2bfb1610") + private String errorId; + + @Schema(example = "500") + private int httpStatusCode; + + @Schema(example = "Internal Server Error") + private String httpStatusDescription; + + @Schema(example = "FDR-500") + private String appErrorCode; + + private List errors; + + @Builder + @Data + @AllArgsConstructor + @NoArgsConstructor + @JsonPropertyOrder({"path", "message"}) + @RegisterForReflection + public static class ErrorMessage { + + @Schema(example = "demo.test") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String path; + + @Schema(example = "An unexpected error has occurred. Please contact support.") + private String message; + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java new file mode 100644 index 0000000..7e533b4 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java @@ -0,0 +1,278 @@ +package it.gov.pagopa.nodetsworker.resources.exceptionmapper; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonMappingException.Reference; +import com.fasterxml.jackson.databind.exc.InvalidFormatException; +import com.fasterxml.jackson.databind.exc.MismatchedInputException; +import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageEnum; +import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageInterface; +import it.gov.pagopa.nodetsworker.exceptions.AppException; +import it.gov.pagopa.nodetsworker.util.AppMessageUtil; +import jakarta.inject.Inject; +import jakarta.validation.ConstraintViolationException; +import jakarta.validation.UnexpectedTypeException; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; +import org.jboss.resteasy.reactive.RestResponse; +import org.jboss.resteasy.reactive.server.ServerExceptionMapper; +import org.slf4j.MDC; + +import java.time.Instant; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +//import static it.gov.pagopa.fdr.util.AppMessageUtil.logErrorMessage; +//import static it.gov.pagopa.fdr.util.MDCKeys.TRX_ID; + +public class ExceptionMappers { + + @Inject Logger log; + + @ServerExceptionMapper + public Response mapWebApplicationException(WebApplicationException webApplicationException) { + if (webApplicationException.getCause() instanceof JsonMappingException jsonMappingException) { + return mapJsonMappingException(jsonMappingException).toResponse(); + } else if (webApplicationException.getCause() + instanceof JsonParseException jsonParseException) { + return mapJsonParseException(jsonParseException).toResponse(); + } + + return webApplicationException.getResponse(); + } + + @ServerExceptionMapper + public RestResponse mapAppException(AppException appEx) { + AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); + RestResponse.Status status = codeMessage.httpStatus(); + String message = codeMessage.message(appEx.getArgs()); + + ErrorResponse errorResponse = + ErrorResponse.builder() + .httpStatusCode(status.getStatusCode()) + .httpStatusDescription(status.getReasonPhrase()) + .appErrorCode(codeMessage.errorCode()) + .errors(List.of(ErrorResponse.ErrorMessage.builder().message(message).build())) + .build(); + + return RestResponse.status(codeMessage.httpStatus(), errorResponse); + } + + private RestResponse mapJsonMappingException( + JsonMappingException jsonMappingException) { + // quando jackson riesce a parsare il messaggio perchè non formato json valido + AppException appEx = + new AppException( + jsonMappingException, AppErrorCodeMessageEnum.BAD_REQUEST_INPUT_JSON_NON_VALID_FORMAT); + + AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); + RestResponse.Status status = codeMessage.httpStatus(); + + ErrorResponse errorResponse = + ErrorResponse.builder() + .httpStatusCode(status.getStatusCode()) + .httpStatusDescription(status.getReasonPhrase()) + .appErrorCode(codeMessage.errorCode()) + .errors( + List.of( + ErrorResponse.ErrorMessage.builder() + .message(codeMessage.message(appEx.getArgs())) + .build())) + .build(); + + return RestResponse.status(codeMessage.httpStatus(), errorResponse); + } + + private RestResponse mapJsonParseException(JsonParseException jsonParseException) { + // quando jackson riesce a parsare il messaggio perchè non formato json valido + + AppException appEx = + new AppException( + jsonParseException, AppErrorCodeMessageEnum.BAD_REQUEST_INPUT_JSON_NON_VALID_FORMAT); + + AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); + RestResponse.Status status = codeMessage.httpStatus(); + + ErrorResponse errorResponse = + ErrorResponse.builder() + .httpStatusCode(status.getStatusCode()) + .httpStatusDescription(status.getReasonPhrase()) + .appErrorCode(codeMessage.errorCode()) + .errors( + List.of( + ErrorResponse.ErrorMessage.builder() + .message(codeMessage.message(appEx.getArgs())) + .build())) + .build(); + + return RestResponse.status(codeMessage.httpStatus(), errorResponse); + } + + @SuppressWarnings("unchecked") + @ServerExceptionMapper + public RestResponse mapInvalidFormatException( + InvalidFormatException invalidFormatException) { + // quando jackson riesce a parsare il messaggio per popolare il bean ma i valori NON sono + // corretti + String field = + invalidFormatException.getPath().stream() + .map(Reference::getFieldName) + .filter(Objects::nonNull) + .collect(Collectors.joining(".")); + String currentValue = invalidFormatException.getValue().toString(); + AppException appEx = null; + try { + Class target = Class.forName(invalidFormatException.getTargetType().getName()); + if (target.isEnum()) { + Class> enumClass = (Class>) target; + List accepted = Stream.of(enumClass.getEnumConstants()).map(Enum::name).toList(); + appEx = + new AppException( + invalidFormatException, + AppErrorCodeMessageEnum.BAD_REQUEST_INPUT_JSON_ENUM, + field, + currentValue, + accepted); + } else if (target.isAssignableFrom(Instant.class)) { + appEx = + new AppException( + invalidFormatException, + AppErrorCodeMessageEnum.BAD_REQUEST_INPUT_JSON_INSTANT, + field, + currentValue); + } else { + appEx = + new AppException( + invalidFormatException, + AppErrorCodeMessageEnum.BAD_REQUEST_INPUT_JSON, + field, + currentValue); + } + + } catch (ClassNotFoundException e) { + appEx = + new AppException( + invalidFormatException, + AppErrorCodeMessageEnum.BAD_REQUEST_INPUT_JSON, + field, + currentValue); + } + + AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); + RestResponse.Status status = codeMessage.httpStatus(); + + ErrorResponse errorResponse = + ErrorResponse.builder() + .httpStatusCode(status.getStatusCode()) + .httpStatusDescription(status.getReasonPhrase()) + .appErrorCode(codeMessage.errorCode()) + .errors( + List.of( + ErrorResponse.ErrorMessage.builder() + .message(codeMessage.message(appEx.getArgs())) + .build())) + .build(); + + return RestResponse.status(codeMessage.httpStatus(), errorResponse); + } + + @ServerExceptionMapper + public RestResponse mapMismatchedInputException( + MismatchedInputException mismatchedInputException) { + // quando jackson NON riesce a parsare il messaggio per popolare il bean + String field = + mismatchedInputException.getPath().stream() + .map(Reference::getFieldName) + .filter(Objects::nonNull) + .collect(Collectors.joining(".")); + AppException appEx = + new AppException( + mismatchedInputException, + AppErrorCodeMessageEnum.BAD_REQUEST_INPUT_JSON_DESERIALIZE_ERROR, + field); + + AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); + RestResponse.Status status = codeMessage.httpStatus(); + + ErrorResponse errorResponse = + ErrorResponse.builder() + .httpStatusCode(status.getStatusCode()) + .httpStatusDescription(status.getReasonPhrase()) + .appErrorCode(codeMessage.errorCode()) + .errors( + List.of( + ErrorResponse.ErrorMessage.builder() + .message(codeMessage.message(appEx.getArgs())) + .build())) + .build(); + + return RestResponse.status(codeMessage.httpStatus(), errorResponse); + } + + @ServerExceptionMapper + public RestResponse mapUnexpectedTypeException(UnexpectedTypeException exception) { + return mapThrowable(exception); + } + + @ServerExceptionMapper + public RestResponse mapThrowable(Throwable exception) { +// String errorId = MDC.get(TRX_ID); +// log.errorf(logErrorMessage(exception.getMessage())); + + AppException appEx = new AppException(exception, AppErrorCodeMessageEnum.ERROR); + AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); + RestResponse.Status status = codeMessage.httpStatus(); + + ErrorResponse errorResponse = + ErrorResponse.builder() +// .errorId(errorId) + .httpStatusCode(status.getStatusCode()) + .httpStatusDescription(status.getReasonPhrase()) + .appErrorCode(codeMessage.errorCode()) + .errors( + List.of( + ErrorResponse.ErrorMessage.builder() + .message(codeMessage.message(appEx.getArgs())) + .build())) + .build(); + + return RestResponse.status(codeMessage.httpStatus(), errorResponse); + } + + @ServerExceptionMapper + public RestResponse mapConstraintViolationException( + ConstraintViolationException constraintViolationException) { + + AppException appEx = + new AppException(constraintViolationException, AppErrorCodeMessageEnum.BAD_REQUEST); + AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); + RestResponse.Status status = codeMessage.httpStatus(); + + ErrorResponse errorResponse = + ErrorResponse.builder() + .httpStatusCode(status.getStatusCode()) + .httpStatusDescription(status.getReasonPhrase()) + .appErrorCode(codeMessage.errorCode()) + .errors( + constraintViolationException.getConstraintViolations().stream() + .sorted( + (a, b) -> + b.getPropertyPath() + .toString() + .compareTo(a.getPropertyPath().toString())) + .map( + constraintViolation -> + ErrorResponse.ErrorMessage.builder() + .path(constraintViolation.getPropertyPath().toString()) + .message( + AppMessageUtil.getMessage(constraintViolation.getMessage())) + .build()) + .toList()) + .build(); + + return RestResponse.status(codeMessage.httpStatus(), errorResponse); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java deleted file mode 100644 index eaaf2e9..0000000 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/FindEventsResponse.java +++ /dev/null @@ -1,25 +0,0 @@ -package it.gov.pagopa.nodetsworker.resources.response; - -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import it.gov.pagopa.nodetsworker.resources.model.Metadata; -import it.gov.pagopa.nodetsworker.service.dto.EventDto; -import lombok.Builder; -import lombok.Getter; -import lombok.extern.jackson.Jacksonized; -import org.eclipse.microprofile.openapi.annotations.media.Schema; - -import java.util.List; - -@Getter -@Builder -@Jacksonized -@JsonPropertyOrder({"metadata", "count", "data"}) -public class FindEventsResponse { - - private Metadata metadata; - - @Schema(example = "100") - private Long count; - - private List data; -} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/TransactionResponse.java similarity index 84% rename from src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java rename to src/main/java/it/gov/pagopa/nodetsworker/resources/response/TransactionResponse.java index eb31e77..23506f7 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/TransactionResponse.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/TransactionResponse.java @@ -1,7 +1,8 @@ -package it.gov.pagopa.nodetsworker.models; +package it.gov.pagopa.nodetsworker.resources.response; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; +import it.gov.pagopa.nodetsworker.models.BasePaymentInfo; import lombok.*; import java.time.LocalDate; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index 80a1aef..6d5cbdd 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -3,7 +3,10 @@ import it.gov.pagopa.nodetsworker.Config; import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageEnum; import it.gov.pagopa.nodetsworker.exceptions.AppException; -import it.gov.pagopa.nodetsworker.models.*; +import it.gov.pagopa.nodetsworker.models.BasePaymentInfo; +import it.gov.pagopa.nodetsworker.models.DateRequest; +import it.gov.pagopa.nodetsworker.models.PaymentAttemptInfo; +import it.gov.pagopa.nodetsworker.models.PaymentInfo; import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; import it.gov.pagopa.nodetsworker.repository.ReTableService; @@ -11,6 +14,7 @@ import it.gov.pagopa.nodetsworker.repository.model.EventEntity; import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; +import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; import it.gov.pagopa.nodetsworker.service.mapper.EventMapper; import it.gov.pagopa.nodetsworker.util.StatusUtil; import jakarta.enterprise.context.ApplicationScoped; @@ -19,6 +23,7 @@ import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; import java.time.LocalDate; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @@ -84,7 +89,9 @@ private void enrichPaymentAttemptInfo(ConfigDataV1 config,PaymentAttemptInfo pai Long stationVersion = Optional.ofNullable(config.getStations().get(pai.getStationId())).map(s->s.getVersion()).orElse(null); pai.setPaymentToken(pbe.getPaymentInfo().getPaymentToken()); pai.setIsOldPaymentModel(pbe.getDebtorPosition().getModelType().equals("1")); - pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); + if(pai.getBrokerPspId()==null){ + pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); + } pai.setStationVersion(stationVersion); pai.setAmount(pbe.getPaymentInfo().getAmount()); pai.setFee(pbe.getPaymentInfo().getFee()); @@ -101,7 +108,9 @@ private void enrichPaymentAttemptInfo(ConfigDataV1 config,PaymentAttemptInfo pai private void enrichPaymentAttemptInfo(ConfigDataV1 config,PaymentAttemptInfo pai, NegativeBizEvent nbe){ Long stationVersion = Optional.ofNullable(config.getStations().get(pai.getStationId())).map(s->s.getVersion()).orElse(null); pai.setIsOldPaymentModel(nbe.getDebtorPosition().getModelType().equals("1")); - pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); + if(pai.getBrokerPspId()==null) { + pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); + } pai.setStationVersion(stationVersion); pai.setAmount(nbe.getPaymentInfo().getAmount()); pai.setPaymentMethod(nbe.getPaymentInfo().getPaymentMethod()); @@ -114,16 +123,20 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, LocalDate dateFrom, LocalDate dateTo){ + log.infof("getInfoByNoticeNumber %s,%s,%s,%s",organizationFiscalCode,noticeNumber,dateFrom,dateTo); + DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndNN(dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, noticeNumber); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); - List collect = reGroups.keySet().stream().map(gkey->{ - List events = reGroups.get(gkey); + log.infof("found %d different tokens",reGroups.size()); + + List collect = reGroups.keySet().stream().map(paymentToken->{ + List events = reGroups.get(paymentToken); EventEntity lastEvent = events.get(events.size()-1); - String outcome = null; + PaymentInfo pi = eventToPaymentInfo(config,lastEvent); Optional pos = positiveBizClient.countEventsByCiAndNN( lastEvent.getIdDominio(), @@ -132,22 +145,21 @@ public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, dateRequest.getTo() ).stream().findFirst(); if(pos.isPresent() && pos.get().getCount()>0){ - outcome = outcomeOK; + pi.setOutcome(outcomeOK); }else{ - Optional neg = negativeBizClient.findEventsByCiAndNN( + Optional neg = negativeBizClient.findEventsByCiAndNNAndToken( lastEvent.getIdDominio(), lastEvent.getNoticeNumber(), + paymentToken, dateRequest.getFrom(), dateRequest.getTo() ).stream().findFirst(); if(neg.isPresent()){ if(!neg.get().getReAwakable()){ - outcome = outcomeKO; + pi.setOutcome(outcomeKO); } } } - PaymentInfo pi = eventToPaymentInfo(config,lastEvent); - pi.setOutcome(outcome); return pi; }).collect(Collectors.toList()); @@ -163,16 +175,21 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo){ + + log.infof("getInfoByIUV %s,%s,%s,%s",organizationFiscalCode,iuv,dateFrom,dateTo); + DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndIUV(dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, iuv); Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); - List collect = reGroups.keySet().stream().map(gkey->{ - List events = reGroups.get(gkey); + log.infof("found %d different ccps",reGroups.size()); + + List collect = reGroups.keySet().stream().map(ccp->{ + List events = reGroups.get(ccp); EventEntity lastEvent = events.get(events.size()-1); - String outcome = null; + PaymentInfo pi = eventToPaymentInfo(config,lastEvent); Optional pos = positiveBizClient.countEventsByCiAndIUV( lastEvent.getIdDominio(), @@ -181,23 +198,22 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, dateRequest.getTo() ).stream().findFirst(); if(pos.isPresent() && pos.get().getCount()>0){ - outcome = outcomeOK; + pi.setOutcome(outcomeOK); }else{ - Optional neg = negativeBizClient.findEventsByCiAndIUV( + Optional neg = negativeBizClient.findEventsByCiAndIUVAndCCP( lastEvent.getIdDominio(), lastEvent.getIuv(), + ccp, dateRequest.getFrom(), dateRequest.getTo() ).stream().findFirst(); if(neg.isPresent()){ if(!neg.get().getReAwakable()){ - outcome = outcomeKO; + pi.setOutcome(outcomeKO); } } } - PaymentInfo pi = eventToPaymentInfo(config,lastEvent); - pi.setOutcome(outcome); return pi; }).collect(Collectors.toList()); @@ -209,104 +225,101 @@ public TransactionResponse getInfoByIUV(String organizationFiscalCode, } - public TransactionResponse getInfoByNoticeNumberAndPaymentToken(String organizationFiscalCode, String noticeNumber, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { - DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndNNAndToken(dateRequest.getFrom(), - dateRequest.getTo(), organizationFiscalCode, noticeNumber,paymentToken); + public TransactionResponse getAttemptByNoticeNumberAndPaymentToken(String organizationFiscalCode, String noticeNumber, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { - Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); - List collect = reGroups.keySet().stream().map(gkey->{ - List events = reGroups.get(gkey); + log.infof("getInfoByNoticeNumberAndPaymentToken %s,%s,%s,%s,%s",organizationFiscalCode,noticeNumber,paymentToken,dateFrom,dateTo); + + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + List events = reTableService.findReByCiAndNNAndToken(dateRequest.getFrom(),dateRequest.getTo(), organizationFiscalCode, noticeNumber,paymentToken); + List pais = new ArrayList<>(); + if(events.size()>0){ EventEntity lastEvent = events.get(events.size()-1); - PaymentAttemptInfo pi = eventToPaymentAttemptInfo(config,lastEvent); - String outcome = null; + ConfigDataV1 config = configObject.getClonedCache(); + PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config,lastEvent); - Optional pos = positiveBizClient.findEventsByCiAndIUVAndCCP( - lastEvent.getIdDominio(), - lastEvent.getIuv(), - lastEvent.getCcp(), + Optional pos = positiveBizClient.findEventsByCiAndNNAndToken( + organizationFiscalCode, + noticeNumber, + paymentToken, dateRequest.getFrom(), dateRequest.getTo() ).stream().findFirst(); if(pos.isPresent()){ - outcome = outcomeOK; - pi.setOutcome(outcome); - enrichPaymentAttemptInfo(config,pi,pos.get()); + pai.setOutcome(outcomeOK); + enrichPaymentAttemptInfo(config,pai,pos.get()); }else{ Optional neg = negativeBizClient.findEventsByCiAndNNAndToken( - lastEvent.getIdDominio(), - lastEvent.getIuv(), - lastEvent.getPaymentToken(), + organizationFiscalCode, + noticeNumber, + paymentToken, dateRequest.getFrom(), dateRequest.getTo() ).stream().findFirst(); if(neg.isPresent()){ if(!neg.get().getReAwakable()){ - outcome = outcomeKO; + pai.setOutcome(outcomeKO); } - enrichPaymentAttemptInfo(config,pi,neg.get()); + enrichPaymentAttemptInfo(config,pai,neg.get()); } } - return pi; - }).collect(Collectors.toList()); + pais.add(pai); + } + return TransactionResponse.builder() .dateFrom(dateFrom) .dateTo(dateTo) - .payments(collect) + .payments(pais) .build(); } public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { - DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndIUVAndCCP(dateRequest.getFrom(), - dateRequest.getTo(), organizationFiscalCode, iuv,ccp); - Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); + log.infof("getAttemptByIUVAndCCP %s,%s,%s,%s,%s",organizationFiscalCode,iuv,ccp,dateFrom,dateTo); - List collect = reGroups.keySet().stream().map(gkey->{ - List events = reGroups.get(gkey); - EventEntity lastEvent = events.get(events.size()-1); - PaymentAttemptInfo pi = eventToPaymentAttemptInfo(config,lastEvent); + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); + List events = reTableService.findReByCiAndIUVAndCCP(dateRequest.getFrom(),dateRequest.getTo(), organizationFiscalCode, iuv,ccp); + List pais = new ArrayList<>(); + if(events.size()>0) { + EventEntity lastEvent = events.get(events.size() - 1); + PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config, lastEvent); String outcome = null; Optional pos = positiveBizClient.findEventsByCiAndIUVAndCCP( - lastEvent.getIdDominio(), - lastEvent.getIuv(), - lastEvent.getCcp(), + organizationFiscalCode, + iuv, + ccp, dateRequest.getFrom(), dateRequest.getTo() ).stream().findFirst(); - if(pos.isPresent()){ - outcome = outcomeOK; - pi.setOutcome(outcome); - enrichPaymentAttemptInfo(config,pi,pos.get()); - }else{ + if (pos.isPresent()) { + pai.setOutcome(outcomeOK); + enrichPaymentAttemptInfo(config, pai, pos.get()); + } else { Optional neg = negativeBizClient.findEventsByCiAndIUVAndCCP( - lastEvent.getIdDominio(), - lastEvent.getIuv(), - lastEvent.getPaymentToken(), + organizationFiscalCode, + iuv, + ccp, dateRequest.getFrom(), dateRequest.getTo() ).stream().findFirst(); - if(neg.isPresent()){ - if(!neg.get().getReAwakable()){ - outcome = outcomeKO; + if (neg.isPresent()) { + if (!neg.get().getReAwakable()) { + pai.setOutcome(outcomeKO); } - enrichPaymentAttemptInfo(config,pi,neg.get()); + enrichPaymentAttemptInfo(config, pai, neg.get()); } } - return pi; - }).collect(Collectors.toList()); + pais.add(pai); + } return TransactionResponse.builder() .dateFrom(dateFrom) .dateTo(dateTo) - .payments(collect) + .payments(pais) .build(); } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java similarity index 80% rename from src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java rename to src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java index ff49297..88261ad 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/ResourceTest.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java @@ -11,17 +11,20 @@ import io.quarkus.test.junit.QuarkusTest; import io.restassured.common.mapper.TypeRef; import it.gov.pagopa.nodetsworker.models.PaymentInfo; -import it.gov.pagopa.nodetsworker.models.TransactionResponse; +import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; import it.gov.pagopa.nodetsworker.util.AppConstantTestHelper; import it.gov.pagopa.nodetsworker.util.AzuriteResource; import it.gov.pagopa.nodetsworker.util.CosmosResource; +import it.gov.pagopa.nodetsworker.util.Util; import lombok.SneakyThrows; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.time.Instant; +import java.time.LocalDate; import java.util.Random; import static io.restassured.RestAssured.given; @@ -34,7 +37,7 @@ @QuarkusTestResource(MockServerTestResource.class) @QuarkusTestResource(AzuriteResource.class) @QuarkusTestResource(CosmosResource.class) -class ResourceTest { +class Sp03Test { @ConfigProperty(name = "re-table-storage.connection-string") String connString; @@ -70,9 +73,9 @@ private CosmosClient getCosmosClient(){ @SneakyThrows @Test - @DisplayName("by ci and nn with positive") + @DisplayName("sp03 by ci and nn with positive") void test1() { - String noticeNumber = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_NN.formatted(PA_CODE, noticeNumber); getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); @@ -81,6 +84,8 @@ void test1() { ); TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) .when() .get(url) .then() @@ -99,9 +104,9 @@ void test1() { @SneakyThrows @Test - @DisplayName("by ci and nn with negative") + @DisplayName("sp03 by ci and nn with negative") void test2() { - String noticeNumber = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_NN.formatted(PA_CODE, noticeNumber); getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); @@ -110,6 +115,8 @@ void test2() { ); TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) .when() .get(url) .then() @@ -128,9 +135,9 @@ void test2() { @SneakyThrows @Test - @DisplayName("by ci and iuv with positive") + @DisplayName("sp03 by ci and iuv with positive") void test3() { - String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String iuv = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_IUV.formatted(PA_CODE, iuv); getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); @@ -139,6 +146,8 @@ void test3() { ); TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) .when() .get(url) .then() @@ -157,9 +166,9 @@ void test3() { @SneakyThrows @Test - @DisplayName("by ci and iuv with negative") + @DisplayName("sp03 by ci and iuv with negative") void test4() { - String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String iuv = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_IUV.formatted(PA_CODE, iuv); getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); @@ -168,6 +177,8 @@ void test4() { ); TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) .when() .get(url) .then() @@ -184,4 +195,34 @@ void test4() { assertThat(o.getBrokerPspId(),equalTo("intTest")); } + @SneakyThrows + @Test + @DisplayName("dateFrom 400") + void test5() { + String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String url = SP03_IUV.formatted(PA_CODE, iuv); + + given() + .param("dateFrom",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(400); + } + + @SneakyThrows + @Test + @DisplayName("dateTo 400") + void test6() { + String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String url = SP03_IUV.formatted(PA_CODE, iuv); + + given() + .param("dateTo",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(400); + } + } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java new file mode 100644 index 0000000..7e63397 --- /dev/null +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java @@ -0,0 +1,234 @@ +package it.gov.pagopa.nodetsworker.resources; + +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.data.tables.TableClient; +import com.azure.data.tables.TableServiceClient; +import com.azure.data.tables.TableServiceClientBuilder; +import io.quarkiverse.mockserver.test.MockServerTestResource; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.common.mapper.TypeRef; +import it.gov.pagopa.nodetsworker.models.PaymentAttemptInfo; +import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; +import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; +import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; +import it.gov.pagopa.nodetsworker.util.AppConstantTestHelper; +import it.gov.pagopa.nodetsworker.util.AzuriteResource; +import it.gov.pagopa.nodetsworker.util.CosmosResource; +import it.gov.pagopa.nodetsworker.util.Util; +import lombok.SneakyThrows; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.time.LocalDate; +import java.util.Random; + +import static io.restassured.RestAssured.given; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; + +@QuarkusTest +@QuarkusTestResource(MockServerTestResource.class) +@QuarkusTestResource(AzuriteResource.class) +@QuarkusTestResource(CosmosResource.class) +class Sp04Test { + + @ConfigProperty(name = "re-table-storage.connection-string") + String connString; + + @ConfigProperty(name = "biz.endpoint") + String bizendpoint; + + @ConfigProperty(name = "biz.key") + String bizkey; + + private TableClient tableClient; + private CosmosClient clientbiz; + + private TableClient getTableClient(){ + if(tableClient==null){ + TableServiceClient tableServiceClient = new TableServiceClientBuilder().connectionString(connString).buildClient(); + tableServiceClient.createTableIfNotExists("events"); + tableClient = tableServiceClient.getTableClient("events"); + } + return tableClient; + } + + private CosmosClient getCosmosClient(){ + if(clientbiz==null) { + clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); + clientbiz.createDatabaseIfNotExists(CosmosBizEventClient.dbname); + clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosBizEventClient.tablename,"/timestamp"); + clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosNegBizEventClient.tablename,"/timestamp"); + } + return clientbiz; + + } + + @SneakyThrows + @Test + @DisplayName("sp04 by ci,nn,token with positive") + void test1() { + String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); + String token = "pt_"+noticeNumber; + String url = SP04_NN.formatted(PA_CODE, noticeNumber,token); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, noticeNumber,null),new CosmosItemRequestOptions() + ); + + TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); + assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); + } + + @SneakyThrows + @Test + @DisplayName("sp04 by ci,nn,token with negative") + void test2() { + String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); + String token = "pt_"+noticeNumber; + String url = SP04_NN.formatted(PA_CODE, noticeNumber, token); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, noticeNumber,null,false),new CosmosItemRequestOptions() + ); + + TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); + assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); + } + + @SneakyThrows + @Test + @DisplayName("sp04 by ci,iuv,ccp with positive") + void test3() { + String iuv = String.valueOf(Instant.now().toEpochMilli()); + String ccp = "ccp_"+iuv; + String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, null, iuv),new CosmosItemRequestOptions() + ); + + TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); + assertThat(o.getIuv(),equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); + } + + @SneakyThrows + @Test + @DisplayName("sp04 by ci,iuv,ccp with negative") + void test4() { + String iuv = String.valueOf(Instant.now().toEpochMilli()); + String ccp = "ccp_"+iuv; + String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); + getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, null,iuv,false),new CosmosItemRequestOptions() + ); + + TransactionResponse res = given() + .param("dateFrom",Util.format(LocalDate.now())) + .param("dateTo",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); + assertThat(res.getPayments().size(), greaterThan(0)); + PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); + assertThat(o.getIuv(),equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); + assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(),equalTo("pspTest")); + assertThat(o.getChannelId(),equalTo("canaleTest")); + assertThat(o.getBrokerPspId(),equalTo("intTest")); + } + + @SneakyThrows + @Test + @DisplayName("dateFrom 400") + void test5() { + String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String ccp = "ccp_"+iuv; + String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); + + given() + .param("dateFrom",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(400); + } + + @SneakyThrows + @Test + @DisplayName("dateTo 400") + void test6() { + String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String ccp = "ccp_"+iuv; + String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); + + given() + .param("dateTo",Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(400); + } + +} diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java index c210f93..e9af8c5 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java @@ -4,14 +4,17 @@ import io.restassured.http.Header; import it.gov.pagopa.nodetsworker.repository.model.*; +import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.Optional; import java.util.UUID; public class AppConstantTestHelper { public static final String SP03_NN = "/organizations/%s/noticeNumber/%s"; public static final String SP03_IUV = "/organizations/%s/iuv/%s"; + public static final String SP04_NN = "/organizations/%s/iuv/%s/paymentToken/%s"; public static final String SP04_IUV = "/organizations/%s/iuv/%s/ccp/%s"; @@ -22,7 +25,7 @@ public class AppConstantTestHelper { public static final Header HEADER = new Header("Content-Type", "application/json"); public static final TableEntity newRe(String pa,String noticeNumber,String iuv){ - TableEntity entity = new TableEntity(LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ISO_DATE_TIME), String.valueOf(noticeNumber)); + TableEntity entity = new TableEntity(Util.format(LocalDate.now()), String.valueOf(Optional.ofNullable(noticeNumber).orElse(iuv))); entity.addProperty("idDominio",pa); entity.addProperty("noticeNumber",noticeNumber); entity.addProperty("iuv",iuv); @@ -51,7 +54,7 @@ public static final PositiveBizEvent newPositiveBiz(String pa,String noticeNumbe ).debtorPosition( DebtorPosition.builder().modelType("1").iuv(iuv).noticeNumber(noticeNumber).build() ).paymentInfo( - PaymentInfo.builder().paymentDateTime(LocalDateTime.now().minusDays(1)).build() + PaymentInfo.builder().paymentToken(noticeNumber!=null?"pt_"+noticeNumber:"ccp_"+iuv).paymentDateTime(LocalDateTime.now()).build() ) .build(); return p; @@ -63,10 +66,11 @@ public static final NegativeBizEvent newNegBiz(String pa, String noticeNumber, S .creditor( Creditor.builder().idPA(pa).build() ).debtorPosition( - DebtorPosition.builder().iuv(iuv).noticeNumber(noticeNumber).build() + DebtorPosition.builder().iuv(iuv).noticeNumber(noticeNumber).modelType("1").build() ).paymentInfo( NegativePaymentInfo.builder() - .paymentDateTime(LocalDateTime.now().minusDays(1)) + .paymentToken(noticeNumber!=null?"pt_"+noticeNumber:"ccp_"+iuv) + .paymentDateTime(LocalDateTime.now()) .build() ) .reAwakable(reawakable) From e0c429067edfa572c0c4c5d15232622ff17f3a9c Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 5 Jul 2023 18:28:30 +0200 Subject: [PATCH 09/29] wip --- api-test/README.md | 1 - build-and-run.sh | 8 +- docker/README.md | 21 - docker/alertmanager/alertmanager.conf | 12 - docker/docker-compose.yml | 117 ---- docker/grafana/grafana_config.ini | 5 - docker/grafana/grafana_datasources.yml | 7 - .../otel-collector/otel-collector-config.yaml | 33 - docker/prometheus/alert_rules.yml | 13 - docker/prometheus/prometheus.yml | 29 - docker/run_docker.sh | 63 -- format-code.sh | 16 + openapi/openapi.json | 449 ++++++++++++ perfomance-test/README.md | 1 - .../it/gov/pagopa/nodetsworker/Config.java | 25 +- .../exceptions/AppErrorCodeMessageEnum.java | 2 +- .../nodetsworker/exceptions/AppException.java | 3 +- .../pagopa/nodetsworker/models/AppInfo.java | 7 +- .../models/BasePaymentAttemptInfo.java | 11 +- .../nodetsworker/models/BasePaymentInfo.java | 24 +- .../nodetsworker/models/DateRequest.java | 8 +- .../models/PaymentAttemptInfo.java | 26 +- .../nodetsworker/models/PaymentInfo.java | 7 +- .../nodetsworker/models/ProblemJson.java | 42 +- .../nodetsworker/models/RPTAttemptInfo.java | 21 +- .../repository/CosmosBizEventClient.java | 216 +++--- .../repository/CosmosNegBizEventClient.java | 137 ++-- .../repository/ReTableService.java | 145 ++-- .../nodetsworker/repository/model/Count.java | 2 +- .../repository/model/EventEntity.java | 48 +- .../repository/model/NegativeBizEvent.java | 3 +- .../repository/model/NegativePaymentInfo.java | 1 - .../repository/model/NegativeTransfer.java | 1 - .../repository/model/PaymentInfo.java | 4 +- .../repository/model/PositiveBizEvent.java | 7 +- .../repository/model/Transfer.java | 3 +- .../nodetsworker/resources/InfoResource.java | 3 +- .../resources/WorkerResource.java | 240 ++++--- .../exceptionmapper/ErrorResponse.java | 3 +- .../exceptionmapper/ExceptionMappers.java | 18 +- .../resources/response/InfoResponse.java | 3 +- .../response/TransactionResponse.java | 20 +- .../nodetsworker/service/WorkerService.java | 637 ++++++++++-------- .../nodetsworker/service/dto/EventDto.java | 67 +- .../service/mapper/EventMapper.java | 5 +- .../pagopa/nodetsworker/util/StatusUtil.java | 85 ++- .../it/gov/pagopa/nodetsworker/util/Util.java | 34 +- src/main/resources/application.properties | 6 + .../nodetsworker/resources/GenericTest.java | 18 +- .../nodetsworker/resources/Sp03Test.java | 204 +++--- .../nodetsworker/resources/Sp04Test.java | 218 +++--- .../util/AppConstantTestHelper.java | 85 ++- .../nodetsworker/util/AzuriteResource.java | 5 +- .../nodetsworker/util/CosmosResource.java | 36 +- 54 files changed, 1770 insertions(+), 1435 deletions(-) delete mode 100644 api-test/README.md delete mode 100644 docker/README.md delete mode 100644 docker/alertmanager/alertmanager.conf delete mode 100644 docker/docker-compose.yml delete mode 100644 docker/grafana/grafana_config.ini delete mode 100644 docker/grafana/grafana_datasources.yml delete mode 100644 docker/otel-collector/otel-collector-config.yaml delete mode 100644 docker/prometheus/alert_rules.yml delete mode 100644 docker/prometheus/prometheus.yml delete mode 100644 docker/run_docker.sh create mode 100644 format-code.sh delete mode 100644 perfomance-test/README.md diff --git a/api-test/README.md b/api-test/README.md deleted file mode 100644 index a343732..0000000 --- a/api-test/README.md +++ /dev/null @@ -1 +0,0 @@ -Put here the Postman collection diff --git a/build-and-run.sh b/build-and-run.sh index 812164c..62b861f 100644 --- a/build-and-run.sh +++ b/build-and-run.sh @@ -7,7 +7,7 @@ if [ -z "$action" ]; then exit 0 fi -REPO=pagopa/pagopafdr +REPO=pagopa/pagopatechsupport build () { conf=$1 @@ -18,7 +18,7 @@ build () { ##Attenzione si usa il file Dockerfile.multistage.jvm, e non Dockerfile.multistage, perchè la lib di azure non è compatibile per la build nativa docker build -f src/main/docker/Dockerfile.multistage.jvm \ - --build-arg APP_NAME=pagopafdr --build-arg QUARKUS_PROFILE=$conf \ + --build-arg APP_NAME=pagopatechsupport --build-arg QUARKUS_PROFILE=$conf \ -t $REPO:$version-$conf . } @@ -33,10 +33,10 @@ generate_openapi () { conf=$1 version=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout) echo "Generate OpenAPI JSON [$version] [$conf]" - docker run -i -d --name exportfdr_$conf --rm -p 8080:8080 $REPO:$version-$conf + docker run -i -d --name exporttechsupport_$conf --rm -p 8080:8080 $REPO:$version-$conf sleep 10 curl http://localhost:8080/q/openapi?format=json > openapi/$conf.json - docker rm -f exportfdr_$conf + docker rm -f exporttechsupport_$conf } test_curl () { diff --git a/docker/README.md b/docker/README.md deleted file mode 100644 index ec6b0ca..0000000 --- a/docker/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Docker Environment 🐳 - -`run_docker.sh` is a script to launch the image of this microservice and all the dependencies on -Docker. - -## How to use 💻 - -You can use `local`, `dev`, `uat` or `prod` images - -`sh ./run_docker.sh ` - -You can skip to recreate the images of Docker with `--skip-recreate` - ---- - -ℹ️ _Note_: for **PagoPa ACR** is **required** the login `az acr login -n ` - -ℹ️ _Note_: If you run the script without the parameter, `local` is used as default. - -ℹ️ _Note_: When you select `local`, a new image of this microservice is created from your branch, -but the `dev` dependencies are used. diff --git a/docker/alertmanager/alertmanager.conf b/docker/alertmanager/alertmanager.conf deleted file mode 100644 index 13611f6..0000000 --- a/docker/alertmanager/alertmanager.conf +++ /dev/null @@ -1,12 +0,0 @@ -global: - resolve_timeout: 1m - pagerduty_url: 'https://events.pagerduty.com/v2/enqueue' - -route: - receiverEntity: 'pagerduty-notifications' - -receivers: -- name: 'pagerduty-notifications' - pagerduty_configs: - - service_key: 0c1cc665a594419b6d215e81f4e38f7 - send_resolved: true diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml deleted file mode 100644 index f834154..0000000 --- a/docker/docker-compose.yml +++ /dev/null @@ -1,117 +0,0 @@ -version: '3.8' - -services: - elasticsearch: - image: docker.elastic.co/elasticsearch/elasticsearch:8.6.2 - ports: - - "9200:9200" - - "9300:9300" - environment: - ES_JAVA_OPTS: "-Xms512m -Xmx512m" - discovery.type: "single-node" - xpack.security.enabled: false - xpack.security.enrollment.enabled: false - networks: - - infra - - kibana: - image: docker.elastic.co/kibana/kibana:8.6.2 - ports: - - "5601:5601" - networks: - - infra - depends_on: - - elasticsearch - - alertmanager: - hostname: alertmanager - image: prom/alertmanager - volumes: - - ${PWD}/alertmanager/alertmanager.conf:/etc/alertmanager/alertmanager.conf - command: - - '--config.file=/etc/alertmanager/alertmanager.conf' - ports: - - "9093:9093" - networks: - - infra - - prometheus: - hostname: prometheus - image: prom/prometheus - volumes: - - ${PWD}/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml - - ${PWD}/prometheus/alert_rules.yml:/etc/prometheus/alert_rules.yml - - prometheus_data:/prometheus - command: - - '--config.file=/etc/prometheus/prometheus.yml' - links: - - alertmanager:alertmanager - ports: - - "9090:9090" - networks: - - infra - - grafana: - hostname: grafana - image: grafana/grafana - volumes: - - ${PWD}/grafana/grafana_datasources.yml:/etc/grafana/provisioning/datasources/all.yaml - - ${PWD}/grafana/grafana_config.ini:/etc/grafana/config.ini - - grafana_data:/var/lib/grafana - ports: - - "3000:3000" - networks: - - infra - - jaeger-all-in-one: - image: jaegertracing/all-in-one:latest - ports: - - "16686:16686" - - "14268:14268" - - "14250:14250" - networks: - - infra - - otel-collector: - image: otel/opentelemetry-collector:latest - command: [ "--config=/etc/otel-collector-config.yaml" ] - volumes: - - ${PWD}/otel-collector/otel-collector-config.yaml:/etc/otel-collector-config.yaml:Z - ports: - - "13133:13133" # Health-check extension - - "4317:4317" # OTLP gRPC receiver - depends_on: - - jaeger-all-in-one - networks: - - infra - -# mongo: -# image: mongo -# restart: always -# environment: -# MONGO_INITDB_ROOT_USERNAME: root -# MONGO_INITDB_ROOT_PASSWORD: example -# ports: -# - 27017:27017 -# networks: -# - infra -# -# mongo-express: -# image: mongo-express -# restart: always -# ports: -# - 8085:8081 -# environment: -# ME_CONFIG_MONGODB_ADMINUSERNAME: root -# ME_CONFIG_MONGODB_ADMINPASSWORD: example -# ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/ -# networks: -# - infra - - -volumes: - prometheus_data: { } - grafana_data: { } -networks: - infra: - driver: bridge diff --git a/docker/grafana/grafana_config.ini b/docker/grafana/grafana_config.ini deleted file mode 100644 index 9c84f44..0000000 --- a/docker/grafana/grafana_config.ini +++ /dev/null @@ -1,5 +0,0 @@ -[paths] -provisioning = /etc/grafana/provisioning - -[server] -enable_gzip = true \ No newline at end of file diff --git a/docker/grafana/grafana_datasources.yml b/docker/grafana/grafana_datasources.yml deleted file mode 100644 index ba6949e..0000000 --- a/docker/grafana/grafana_datasources.yml +++ /dev/null @@ -1,7 +0,0 @@ -apiVersion: 1 - -datasources: - - name: 'prometheus' - type: 'prometheus' - access: 'proxy' - url: 'http://prometheus:9090' \ No newline at end of file diff --git a/docker/otel-collector/otel-collector-config.yaml b/docker/otel-collector/otel-collector-config.yaml deleted file mode 100644 index c08ab06..0000000 --- a/docker/otel-collector/otel-collector-config.yaml +++ /dev/null @@ -1,33 +0,0 @@ -receivers: - otlp: - protocols: - grpc: - endpoint: otel-collector:4317 - -exporters: - jaeger: - endpoint: jaeger-all-in-one:14250 - tls: - insecure: true - otlphttp/elastic: - tls: - insecure: true - # Elastic APM server https endpoint without the "https://" prefix - endpoint: "https://kibana.dev.platform.pagopa.it:443/apm" - headers: - # Elastic APM Server secret token - Authorization: "Bearer 30K8q56M9r3jhKrIdhf968PO" - -processors: - batch: - -extensions: - health_check: - -service: - extensions: [ health_check ] - pipelines: - traces: - receivers: [ otlp ] - processors: [ batch ] - exporters: [ jaeger, otlphttp/elastic ] diff --git a/docker/prometheus/alert_rules.yml b/docker/prometheus/alert_rules.yml deleted file mode 100644 index 5d0c4fd..0000000 --- a/docker/prometheus/alert_rules.yml +++ /dev/null @@ -1,13 +0,0 @@ -groups: - - name: JVMMemory - rules: - - alert: JVMMemoryThresholdCrossed - # Condition for alerting - expr: jvm_memory_committed_bytes{region="heap"}/jvm_memory_max_bytes{region="heap"} > 0.8 - # Annotation - additional informational labels to store more information - annotations: - title: 'Instance has crossed 80% heap memory usage' - description: ' of job has crossed 80% heap memory usage' - # Labels - additional labels to be attached to the alert - labels: - severity: 'critical' \ No newline at end of file diff --git a/docker/prometheus/prometheus.yml b/docker/prometheus/prometheus.yml deleted file mode 100644 index 9521553..0000000 --- a/docker/prometheus/prometheus.yml +++ /dev/null @@ -1,29 +0,0 @@ -# global settings -global: - scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute. - evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute. - # scrape_timeout is set to the global default (10s). - -alerting: - alertmanagers: - - static_configs: - - targets: [ "alertmanager:9093" ] - -# Load rules once and periodically evaluate them according to the global 'evaluation_interval'. -rule_files: - - /etc/prometheus/alert_rules.yml - -# A scrape configuration containing exactly one endpoint to scrape: -# Here it's Prometheus itself. -scrape_configs: - # The job name is added as a label `job=` to any timeseries scraped from this config. - - job_name: 'ndp-metrics' - metrics_path: '/q/metrics' - scrape_interval: 5s - static_configs: - - targets: [ 'docker.for.mac.host.internal:8080' ] - #labels: - # application: ndp - # namespace: nodo - # service: ndp - # env: dev diff --git a/docker/run_docker.sh b/docker/run_docker.sh deleted file mode 100644 index f907c83..0000000 --- a/docker/run_docker.sh +++ /dev/null @@ -1,63 +0,0 @@ -# sh ./run_docker.sh --skip-recreate - -ENV=$1 -RECREATE=$2 - -if [ -z "$ENV" ] -then - ENV="local" - echo "No environment specified: local is used." -fi - - -if [ "$ENV" = "local" ]; then - containerRegistry="pagopadcommonacr.azurecr.io" - image="service-local:latest" - echo "Running local image and dev dependencies" -else - - if [ "$ENV" = "dev" ]; then - containerRegistry="pagopadcommonacr.azurecr.io" - echo "Running all dev images" - elif [ "$ENV" = "uat" ]; then - containerRegistry="pagopaucommonacr.azurecr.io" - echo "Running all uat images" - elif [ "$ENV" = "prod" ]; then - containerRegistry="pagopapcommonacr.azurecr.io" - echo "Running all prod images" - else - echo "Error with parameter: use " - exit 1 - fi - - pip3 install yq - repository=$(yq -r '."microservice-chart".image.repository' ../helm/values-$ENV.yaml) - image="${repository}:latest" -fi - - -export containerRegistry=${containerRegistry} -export image=${image} - -stack_name=$(cd .. && basename "$PWD") -if [ "$RECREATE" = "--skip-recreate" ]; then - docker compose -p "${stack_name}" up -d - else - docker compose -p "${stack_name}" up -d --remove-orphans --force-recreate --build -fi - -# waiting the containers -printf 'Waiting for the service' -attempt_counter=0 -max_attempts=50 -until $(curl --output /dev/null --silent --head --fail http://localhost:8080/actuator/info); do - if [ ${attempt_counter} -eq ${max_attempts} ];then - echo "Max attempts reached" - exit 1 - fi - - printf '.' - attempt_counter=$((attempt_counter+1)) - sleep 5 -done -echo 'Service Started' diff --git a/format-code.sh b/format-code.sh new file mode 100644 index 0000000..93f685d --- /dev/null +++ b/format-code.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env sh +mkdir -p .cache +cd .cache +if [ ! -f google-java-format-1.17.0-all-deps.jar ] +then + curl -LJO "https://github.com/google/google-java-format/releases/download/v1.17.0/google-java-format-1.17.0-all-deps.jar" + chmod 755 google-java-format-1.17.0-all-deps.jar +fi +cd .. + +#changed_java_files=$(git diff --cached --name-only --diff-filter=ACMR | grep ".*java$" ) +#echo $changed_java_files +#java -jar .cache/google-java-format-1.17.0-all-deps.jar --replace $changed_java_files + +## escludo le classi con il String text block perchè non ancora supportate da google java format +java -jar .cache/google-java-format-1.17.0-all-deps.jar --replace $(find . -type f -name "*.java" ! -name "App.java" ! -name "PspResourceTest.java" ! -name "OrganizationResourceTest.java") diff --git a/openapi/openapi.json b/openapi/openapi.json index e69de29..e700d89 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -0,0 +1,449 @@ +{ + "openapi" : "3.0.3", + "info" : { + "title" : "Node technical support - Api (local) ${service}", + "termsOfService" : "https://www.pagopa.gov.it/", + "version" : "1.0.0-SNAPSHOT" + }, + "servers" : [ { + "url" : "${host}/tenchinal-support/api/v1 - APIM" + } ], + "tags" : [ { + "name" : "Info", + "description" : "Info operations" + } ], + "paths" : { + "/info" : { + "get" : { + "tags" : [ "Info" ], + "summary" : "Get info of FDR", + "responses" : { + "default" : { + "$ref" : "#/components/responses/InternalServerError" + }, + "200" : { + "description" : "Success", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/InfoResponse" + } + } + } + } + } + } + }, + "/organizations/{organizationFiscalCode}/iuv/{iuv}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "iuv", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" + } + } + } + }, + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + }, + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + } + } + } + }, + "/organizations/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "ccp", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "iuv", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" + } + } + } + }, + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + }, + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + } + } + } + }, + "/organizations/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "iuv", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "paymentToken", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" + } + } + } + }, + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + }, + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + } + } + } + }, + "/organizations/{organizationFiscalCode}/noticeNumber/{noticeNumber}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "noticeNumber", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" + } + } + } + }, + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + }, + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" + } + } + } + } + } + } + } + }, + "components" : { + "schemas" : { + "BasePaymentInfo" : { + "type" : "object", + "properties" : { + "organizationFiscalCode" : { + "type" : "string" + }, + "noticeNumber" : { + "type" : "string" + }, + "iuv" : { + "type" : "string" + }, + "pspId" : { + "type" : "string" + }, + "brokerPspId" : { + "type" : "string" + }, + "channelId" : { + "type" : "string" + }, + "outcome" : { + "type" : "string" + }, + "status" : { + "type" : "string" + }, + "insertedTimestamp" : { + "type" : "string" + }, + "updatedTimestamp" : { + "type" : "string" + }, + "isOldPaymentModel" : { + "type" : "boolean" + }, + "nodeId" : { + "type" : "string" + } + } + }, + "ErrorCode" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "string", + "example" : "FDR-0500" + }, + "description" : { + "type" : "string", + "example" : "An unexpected error has occurred. Please contact support." + }, + "statusCode" : { + "format" : "int32", + "type" : "integer", + "example" : 500 + } + } + }, + "InfoResponse" : { + "type" : "object", + "properties" : { + "name" : { + "type" : "string", + "example" : "pagopa-fdr" + }, + "version" : { + "type" : "string", + "example" : "1.2.3" + }, + "environment" : { + "type" : "string", + "example" : "dev" + }, + "description" : { + "type" : "string", + "example" : "FDR - Flussi di rendicontazione" + }, + "errorCodes" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/ErrorCode" + } + } + } + }, + "LocalDate" : { + "format" : "date", + "type" : "string", + "example" : "2022-03-10" + }, + "ProblemJson" : { + "type" : "object", + "properties" : { + "title" : { + "description" : "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable", + "type" : "string" + }, + "status" : { + "format" : "int32", + "description" : "The HTTP status code generated by the origin server for this occurrence of the problem.", + "maximum" : 600, + "minimum" : 100, + "type" : "integer", + "example" : 200 + }, + "details" : { + "description" : "A human readable explanation specific to this occurrence of the problem.", + "type" : "string", + "example" : "There was an error processing the request" + } + } + }, + "TransactionResponse" : { + "type" : "object", + "properties" : { + "dateFrom" : { + "$ref" : "#/components/schemas/LocalDate" + }, + "dateTo" : { + "$ref" : "#/components/schemas/LocalDate" + }, + "data" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/BasePaymentInfo" + } + } + } + } + }, + "securitySchemes" : { + "SecurityScheme" : { + "type" : "http", + "description" : "Authentication", + "scheme" : "basic" + } + } + } +} \ No newline at end of file diff --git a/perfomance-test/README.md b/perfomance-test/README.md deleted file mode 100644 index a7638d5..0000000 --- a/perfomance-test/README.md +++ /dev/null @@ -1 +0,0 @@ -Put here the performance tests with K6 diff --git a/src/main/java/it/gov/pagopa/nodetsworker/Config.java b/src/main/java/it/gov/pagopa/nodetsworker/Config.java index c5fd9f3..e4d6f95 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/Config.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/Config.java @@ -6,6 +6,8 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.client.ClientRequestFilter; +import java.net.URI; +import java.util.Collections; import lombok.SneakyThrows; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.rest.client.RestClientBuilder; @@ -13,9 +15,6 @@ import org.openapi.quarkus.api_config_cache_json.api.NodeCacheApi; import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; -import java.net.URI; -import java.util.Collections; - @ApplicationScoped public class Config { @@ -34,15 +33,15 @@ public class Config { @SneakyThrows public void init() { nodeCacheApi = - RestClientBuilder.newBuilder() - .baseUri(new URI(url)) - .register( - (ClientRequestFilter) - context -> - context - .getHeaders() - .put(apiKeyName, Collections.singletonList(apiKeyValue))) - .build(NodeCacheApi.class); + RestClientBuilder.newBuilder() + .baseUri(new URI(url)) + .register( + (ClientRequestFilter) + context -> + context + .getHeaders() + .put(apiKeyName, Collections.singletonList(apiKeyValue))) + .build(NodeCacheApi.class); ConfigDataV1 newCache = nodeCacheApi.cache(null); log.debugf("Cache init. Version [%s]", newCache.getVersion()); @@ -60,7 +59,7 @@ public ConfigDataV1 getClonedCache() { return null; } else { return objectMapper.readValue( - objectMapper.writeValueAsString(this.cache), ConfigDataV1.class); + objectMapper.writeValueAsString(this.cache), ConfigDataV1.class); } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java index 60a5488..8f234c6 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppErrorCodeMessageEnum.java @@ -5,7 +5,7 @@ import org.jboss.resteasy.reactive.RestResponse; public enum AppErrorCodeMessageEnum implements AppErrorCodeMessageInterface { - POSITION_SERVICE_DATE_BAD_REQUEST("0400","bad.request", RestResponse.Status.BAD_REQUEST), + POSITION_SERVICE_DATE_BAD_REQUEST("0400", "bad.request", RestResponse.Status.BAD_REQUEST), ERROR("0500", "system.error", RestResponse.Status.INTERNAL_SERVER_ERROR), BAD_REQUEST("0400", "bad.request", RestResponse.Status.BAD_REQUEST), BAD_REQUEST_INPUT_JSON("0401", "bad.request.inputJson", RestResponse.Status.BAD_REQUEST), diff --git a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java index 70dca33..1a52262 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/exceptions/AppException.java @@ -1,8 +1,7 @@ package it.gov.pagopa.nodetsworker.exceptions; -import lombok.Getter; - import java.io.Serializable; +import lombok.Getter; @Getter public class AppException extends RuntimeException { diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/AppInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/AppInfo.java index 2153efe..9c163fa 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/AppInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/AppInfo.java @@ -6,14 +6,13 @@ import lombok.NoArgsConstructor; import lombok.Setter; - @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor public class AppInfo { - private String name; - private String version; - private String environment; + private String name; + private String version; + private String environment; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java index 3d43f18..24421d9 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentAttemptInfo.java @@ -1,13 +1,12 @@ package it.gov.pagopa.nodetsworker.models; +import java.math.BigDecimal; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; -import java.math.BigDecimal; - @Getter @Setter @NoArgsConstructor @@ -15,8 +14,8 @@ @SuperBuilder public class BasePaymentAttemptInfo extends BasePaymentInfo { - private String brokerOrganizationId; - private String stationId; - private String paymentMethod; - private BigDecimal amount; + private String brokerOrganizationId; + private String stationId; + private String paymentMethod; + private BigDecimal amount; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java index db822bb..d50b4f6 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java @@ -13,16 +13,16 @@ @SuperBuilder public class BasePaymentInfo { - private String organizationFiscalCode; - private String noticeNumber; - private String iuv; - private String pspId; - private String brokerPspId; - private String channelId; - private String outcome; - private String status; - private String insertedTimestamp; - private String updatedTimestamp; - private Boolean isOldPaymentModel; - private String nodeId; + private String organizationFiscalCode; + private String noticeNumber; + private String iuv; + private String pspId; + private String brokerPspId; + private String channelId; + private String outcome; + private String status; + private String insertedTimestamp; + private String updatedTimestamp; + private Boolean isOldPaymentModel; + private String nodeId; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java b/src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java index 8dc3ad0..99d642f 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/DateRequest.java @@ -1,13 +1,12 @@ package it.gov.pagopa.nodetsworker.models; +import java.time.LocalDate; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.time.LocalDate; - @Getter @Setter @AllArgsConstructor @@ -15,7 +14,6 @@ @Builder public class DateRequest { - private LocalDate from; - private LocalDate to; - + private LocalDate from; + private LocalDate to; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java index 098c5b3..7189ba8 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java @@ -1,14 +1,12 @@ package it.gov.pagopa.nodetsworker.models; +import java.math.BigDecimal; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; -import java.math.BigDecimal; -import java.time.LocalDate; - @Getter @Setter @NoArgsConstructor @@ -16,15 +14,15 @@ @SuperBuilder public class PaymentAttemptInfo extends BasePaymentAttemptInfo { - private String paymentToken; - private Boolean pmReceipt; - private String paymentMethod; - private String paymentChannel; - private Long stationVersion; - private BigDecimal fee; - private BigDecimal feeOrganization; - private String bundleId; - private String bundleOrganizationId; - private String applicationDate; - private String transferDate; + private String paymentToken; + private Boolean pmReceipt; + private String paymentMethod; + private String paymentChannel; + private Long stationVersion; + private BigDecimal fee; + private BigDecimal feeOrganization; + private String bundleId; + private String bundleOrganizationId; + private String applicationDate; + private String transferDate; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java index 209042d..d3c77df 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java @@ -1,14 +1,11 @@ package it.gov.pagopa.nodetsworker.models; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; -import java.time.LocalDateTime; - @Getter @Setter @NoArgsConstructor @@ -16,6 +13,6 @@ @SuperBuilder public class PaymentInfo extends BasePaymentInfo { - private String paymentToken; // for new payment model is payment token and for old payment model is ccp - + private String + paymentToken; // for new payment model is payment token and for old payment model is ccp } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java b/src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java index ac6543d..033746d 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/ProblemJson.java @@ -1,8 +1,9 @@ package it.gov.pagopa.nodetsworker.models; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -10,9 +11,6 @@ import lombok.ToString; import org.eclipse.microprofile.openapi.annotations.media.Schema; -import jakarta.validation.constraints.Max; -import jakarta.validation.constraints.Min; - @Data @Builder(toBuilder = true) @NoArgsConstructor @@ -21,18 +19,26 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class ProblemJson { - @JsonProperty("title") - @Schema(description = "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable") - private String title; - - @JsonProperty("status") - @Schema(example = "200", description = "The HTTP status code generated by the origin server for this occurrence of the problem.") - @Min(100) - @Max(600) - private Integer status; - - @JsonProperty("details") - @Schema(example = "There was an error processing the request", description = "A human readable explanation specific to this occurrence of the problem.") - private String details; - + @JsonProperty("title") + @Schema( + description = + "A short, summary of the problem type. Written in english and readable for engineers" + + " (usually not suited for non technical stakeholders and not localized); example:" + + " Service Unavailable") + private String title; + + @JsonProperty("status") + @Schema( + example = "200", + description = + "The HTTP status code generated by the origin server for this occurrence of the problem.") + @Min(100) + @Max(600) + private Integer status; + + @JsonProperty("details") + @Schema( + example = "There was an error processing the request", + description = "A human readable explanation specific to this occurrence of the problem.") + private String details; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java index 79da60a..6c0547e 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java @@ -2,15 +2,11 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; -import java.time.LocalDate; -import java.time.LocalDateTime; - @Getter @Setter @NoArgsConstructor @@ -18,12 +14,13 @@ @SuperBuilder public class RPTAttemptInfo extends BasePaymentAttemptInfo { - private String ccp; - private Long numberOfPayments; - private Boolean retriedRPT; - private Boolean isOldPaymentModel = true; - private Boolean wispInitialization; - private Boolean pmReceipt; - @JsonProperty("iuv") - private String noticeNumber; + private String ccp; + private Long numberOfPayments; + private Boolean retriedRPT; + private Boolean isOldPaymentModel = true; + private Boolean wispInitialization; + private Boolean pmReceipt; + + @JsonProperty("iuv") + private String noticeNumber; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java index d7b0119..6b68821 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -8,126 +8,136 @@ import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; import it.gov.pagopa.nodetsworker.repository.model.Count; -import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; import it.gov.pagopa.nodetsworker.util.Util; import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.eclipse.microprofile.config.inject.ConfigProperty; -import org.jboss.logging.Logger; - import java.time.*; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Optional; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; @ApplicationScoped @Startup public class CosmosBizEventClient { - @ConfigProperty(name = "biz.endpoint") - private String endpoint; + @ConfigProperty(name = "biz.endpoint") + private String endpoint; - @ConfigProperty(name = "biz.key") - private String key; + @ConfigProperty(name = "biz.key") + private String key; - public static String dbname = "db"; - public static String tablename = "biz-events"; + public static String dbname = "db"; + public static String tablename = "biz-events"; - private CosmosClient client; + private CosmosClient client; - @Inject - Logger log; + @Inject Logger log; - private CosmosClient getClient(){ - if(client==null){ - client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); - } - return client; + private CosmosClient getClient() { + if (client == null) { + client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); } - - private CosmosPagedIterable query(SqlQuerySpec query){ - log.info("executing query:"+query.getQueryText()); - CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); - return container.queryItems(query, new CosmosQueryRequestOptions(), PositiveBizEvent.class); - } - private CosmosPagedIterable queryCount(SqlQuerySpec query){ - log.info("executing query:"+query.getQueryText()); - CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); - return container.queryItems(query, new CosmosQueryRequestOptions(), Count.class); - } - - public CosmosPagedIterable findEventsByCiAndNNAndToken(String organizationFiscalCode, String noticeNumber,String paymentToken, LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@noticeNumber", noticeNumber), - new SqlParameter("@paymentToken", paymentToken), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.noticeNumber = @noticeNumber" + - " and c.paymentInfo.paymentToken = @paymentToken" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ).setParameters(paramList); - return query(q); - } - - public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@iuv", iuv), - new SqlParameter("@ccp", ccp), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.iuv = @iuv" + - " and c.paymentInfo.paymentToken = @ccp" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ).setParameters(paramList); - return query(q); - } - - public CosmosPagedIterable countEventsByCiAndNN(String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@noticeNumber", noticeNumber), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); - - SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.noticeNumber = @noticeNumber" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ).setParameters(paramList); - return queryCount(q); - } - - public CosmosPagedIterable countEventsByCiAndIUV(String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@iuv", iuv), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); - - SqlQuerySpec q = new SqlQuerySpec("SELECT count(1) as count FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.iuv = @iuv" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ).setParameters(paramList); - return queryCount(q); - } - + return client; + } + + private CosmosPagedIterable query(SqlQuerySpec query) { + log.info("executing query:" + query.getQueryText()); + CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); + return container.queryItems(query, new CosmosQueryRequestOptions(), PositiveBizEvent.class); + } + + private CosmosPagedIterable queryCount(SqlQuerySpec query) { + log.info("executing query:" + query.getQueryText()); + CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); + return container.queryItems(query, new CosmosQueryRequestOptions(), Count.class); + } + + public CosmosPagedIterable findEventsByCiAndNNAndToken( + String organizationFiscalCode, + String noticeNumber, + String paymentToken, + LocalDate dateFrom, + LocalDate dateTo) { + List paramList = + Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@noticeNumber", noticeNumber), + new SqlParameter("@paymentToken", paymentToken), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX)))); + SqlQuerySpec q = + new SqlQuerySpec( + "SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.paymentInfo.paymentToken = @paymentToken" + + " and c.timestamp > @from" + + " and c.timestamp < @to") + .setParameters(paramList); + return query(q); + } + + public CosmosPagedIterable findEventsByCiAndIUVAndCCP( + String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { + List paramList = + Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@iuv", iuv), + new SqlParameter("@ccp", ccp), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX)))); + SqlQuerySpec q = + new SqlQuerySpec( + "SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.iuv = @iuv" + + " and c.paymentInfo.paymentToken = @ccp" + + " and c.timestamp > @from" + + " and c.timestamp < @to") + .setParameters(paramList); + return query(q); + } + + public CosmosPagedIterable countEventsByCiAndNN( + String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo) { + List paramList = + Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@noticeNumber", noticeNumber), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX)))); + + SqlQuerySpec q = + new SqlQuerySpec( + "SELECT count(1) as count FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.timestamp > @from" + + " and c.timestamp < @to") + .setParameters(paramList); + return queryCount(q); + } + + public CosmosPagedIterable countEventsByCiAndIUV( + String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo) { + List paramList = + Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@iuv", iuv), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX)))); + + SqlQuerySpec q = + new SqlQuerySpec( + "SELECT count(1) as count FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.iuv = @iuv" + + " and c.timestamp > @from" + + " and c.timestamp < @to") + .setParameters(paramList); + return queryCount(q); + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java index fb6def0..af6bdec 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java @@ -12,90 +12,97 @@ import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.eclipse.microprofile.config.inject.ConfigProperty; -import org.jboss.logging.Logger; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Optional; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; @ApplicationScoped @Startup public class CosmosNegBizEventClient { - @ConfigProperty(name = "bizneg.endpoint") - private String endpoint; + @ConfigProperty(name = "bizneg.endpoint") + private String endpoint; - @ConfigProperty(name = "bizneg.key") - private String key; + @ConfigProperty(name = "bizneg.key") + private String key; - public static String dbname = "db"; - public static String tablename = "negative-biz-events"; + public static String dbname = "db"; + public static String tablename = "negative-biz-events"; - private CosmosClient client; + private CosmosClient client; - @Inject - Logger log; + @Inject Logger log; - private CosmosClient getClient(){ - if(client==null){ - client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); - } - return client; + private CosmosClient getClient() { + if (client == null) { + client = new CosmosClientBuilder().endpoint(endpoint).key(key).buildClient(); } + return client; + } - private CosmosPagedIterable query(SqlQuerySpec query){ - log.info("executing query:"+query.getQueryText()); - CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); - return container.queryItems(query, new CosmosQueryRequestOptions(), NegativeBizEvent.class); - } + private CosmosPagedIterable query(SqlQuerySpec query) { + log.info("executing query:" + query.getQueryText()); + CosmosContainer container = getClient().getDatabase(dbname).getContainer(tablename); + return container.queryItems(query, new CosmosQueryRequestOptions(), NegativeBizEvent.class); + } - public CosmosPagedIterable findEventsByCiAndNNAndToken(String organizationFiscalCode, String noticeNumber,String paymentToken, LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@noticeNumber", noticeNumber), - new SqlParameter("@paymentToken", paymentToken), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.noticeNumber = @noticeNumber" + - " and c.paymentInfo.paymentToken = @paymentToken" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ) - .setParameters(paramList); - return query(q); - } + public CosmosPagedIterable findEventsByCiAndNNAndToken( + String organizationFiscalCode, + String noticeNumber, + String paymentToken, + LocalDate dateFrom, + LocalDate dateTo) { + List paramList = + Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@noticeNumber", noticeNumber), + new SqlParameter("@paymentToken", paymentToken), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX)))); + SqlQuerySpec q = + new SqlQuerySpec( + "SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.noticeNumber = @noticeNumber" + + " and c.paymentInfo.paymentToken = @paymentToken" + + " and c.timestamp > @from" + + " and c.timestamp < @to") + .setParameters(paramList); + return query(q); + } - public CosmosPagedIterable findEventsByCiAndIUVAndCCP(String organizationFiscalCode,String iuv, String ccp,LocalDate dateFrom, LocalDate dateTo){ - List paramList = Arrays.asList( - new SqlParameter("@organizationFiscalCode", organizationFiscalCode), - new SqlParameter("@iuv", iuv), - new SqlParameter("@ccp", ccp), - new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), - new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX))) - ); + public CosmosPagedIterable findEventsByCiAndIUVAndCCP( + String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { + List paramList = + Arrays.asList( + new SqlParameter("@organizationFiscalCode", organizationFiscalCode), + new SqlParameter("@iuv", iuv), + new SqlParameter("@ccp", ccp), + new SqlParameter("@from", Util.toMillis(dateFrom.atStartOfDay())), + new SqlParameter("@to", Util.toMillis(LocalDateTime.of(dateTo, LocalTime.MAX)))); - SqlQuerySpec q = new SqlQuerySpec("SELECT * FROM c where" + - " c.creditor.idPA = @organizationFiscalCode" + - " and c.debtorPosition.iuv = @iuv" + - " and c.paymentInfo.paymentToken = @ccp" + - " and c.timestamp > @from" + - " and c.timestamp < @to" - ) - .setParameters(paramList); - return query(q); - } - - public CosmosPagedIterable findEventsByCiAndIUVAndToken(String organizationFiscalCode,String iuv, String paymentToken,LocalDate dateFrom, LocalDate dateTo){ - return findEventsByCiAndIUVAndCCP(organizationFiscalCode,iuv,paymentToken,dateFrom,dateTo); - } + SqlQuerySpec q = + new SqlQuerySpec( + "SELECT * FROM c where" + + " c.creditor.idPA = @organizationFiscalCode" + + " and c.debtorPosition.iuv = @iuv" + + " and c.paymentInfo.paymentToken = @ccp" + + " and c.timestamp > @from" + + " and c.timestamp < @to") + .setParameters(paramList); + return query(q); + } + public CosmosPagedIterable findEventsByCiAndIUVAndToken( + String organizationFiscalCode, + String iuv, + String paymentToken, + LocalDate dateFrom, + LocalDate dateTo) { + return findEventsByCiAndIUVAndCCP(organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo); + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java index b59aa67..6ee6b55 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/ReTableService.java @@ -8,13 +8,11 @@ import it.gov.pagopa.nodetsworker.repository.model.EventEntity; import it.gov.pagopa.nodetsworker.util.Util; import jakarta.enterprise.context.ApplicationScoped; -import org.eclipse.microprofile.config.inject.ConfigProperty; - import java.time.LocalDate; -import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import org.eclipse.microprofile.config.inject.ConfigProperty; // @Startup @ApplicationScoped @@ -29,15 +27,17 @@ public class ReTableService { private TableServiceClient tableServiceClient = null; - public TableClient getTableClient(){ - if(tableServiceClient==null){ - tableServiceClient = new TableServiceClientBuilder().connectionString(connString).buildClient(); + public TableClient getTableClient() { + if (tableServiceClient == null) { + tableServiceClient = + new TableServiceClientBuilder().connectionString(connString).buildClient(); tableServiceClient.createTableIfNotExists(tableName); } return tableServiceClient.getTableClient(tableName); } - private List propertiesToSelect = Arrays.asList( + private List propertiesToSelect = + Arrays.asList( "serviceIdentifier", "status", "psp", @@ -47,62 +47,107 @@ public TableClient getTableClient(){ "idDominio", "iuv", "ccp", - "insertedTimestamp" - ); - + "insertedTimestamp"); - private EventEntity tableEntityToEventEntity(TableEntity e){ + private EventEntity tableEntityToEventEntity(TableEntity e) { return EventEntity.builder() - .canale(getString(e.getProperty("canale"))) - .iuv(getString(e.getProperty("iuv"))) - .ccp(getString(e.getProperty("ccp"))) - .noticeNumber(getString(e.getProperty("noticeNumber"))) - .paymentToken(getString(e.getProperty("paymentToken"))) - .idDominio(getString(e.getProperty("idDominio"))) - .serviceIdentifier(getString(e.getProperty("serviceIdentifier"))) - .insertedTimestamp(getString(e.getProperty("insertedTimestamp"))) - .psp(getString(e.getProperty("psp"))) - .status(getString(e.getProperty("status"))) - .uniqueId(getString(e.getProperty("uniqueId"))) - .build(); + .canale(getString(e.getProperty("canale"))) + .iuv(getString(e.getProperty("iuv"))) + .ccp(getString(e.getProperty("ccp"))) + .noticeNumber(getString(e.getProperty("noticeNumber"))) + .paymentToken(getString(e.getProperty("paymentToken"))) + .idDominio(getString(e.getProperty("idDominio"))) + .serviceIdentifier(getString(e.getProperty("serviceIdentifier"))) + .insertedTimestamp(getString(e.getProperty("insertedTimestamp"))) + .psp(getString(e.getProperty("psp"))) + .status(getString(e.getProperty("status"))) + .uniqueId(getString(e.getProperty("uniqueId"))) + .build(); } - public List findReByCiAndNN(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber){ - - String filter = String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and noticeNumber eq '%s' and esito eq 'CAMBIO_STATO'", - Util.format(datefrom),Util.format(dateTo),creditorInstitution, noticeNumber); - ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(filter) - .setSelect(propertiesToSelect); - return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + public List findReByCiAndNN( + LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber) { + + String filter = + String.format( + "PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and noticeNumber" + + " eq '%s' and esito eq 'CAMBIO_STATO'", + Util.format(datefrom), Util.format(dateTo), creditorInstitution, noticeNumber); + ListEntitiesOptions options = + new ListEntitiesOptions().setFilter(filter).setSelect(propertiesToSelect); + return getTableClient().listEntities(options, null, null).stream() + .map( + e -> { + return tableEntityToEventEntity(e); + }) + .collect(Collectors.toList()); } - public List findReByCiAndIUV(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv){ - ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and iuv eq '%s' and esito eq 'CAMBIO_STATO'", - Util.format(datefrom),Util.format(dateTo), creditorInstitution, iuv)) + + public List findReByCiAndIUV( + LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv) { + ListEntitiesOptions options = + new ListEntitiesOptions() + .setFilter( + String.format( + "PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and iuv eq" + + " '%s' and esito eq 'CAMBIO_STATO'", + Util.format(datefrom), Util.format(dateTo), creditorInstitution, iuv)) .setSelect(propertiesToSelect); - return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + return getTableClient().listEntities(options, null, null).stream() + .map( + e -> { + return tableEntityToEventEntity(e); + }) + .collect(Collectors.toList()); } - public List findReByCiAndNNAndToken(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String noticeNumber, String paymentToken){ - ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and noticeNumber eq '%s' and paymentToken eq '%s' and esito eq 'CAMBIO_STATO'", - Util.format(datefrom),Util.format(dateTo), creditorInstitution, noticeNumber,paymentToken)) + public List findReByCiAndNNAndToken( + LocalDate datefrom, + LocalDate dateTo, + String creditorInstitution, + String noticeNumber, + String paymentToken) { + ListEntitiesOptions options = + new ListEntitiesOptions() + .setFilter( + String.format( + "PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and" + + " noticeNumber eq '%s' and paymentToken eq '%s' and esito eq" + + " 'CAMBIO_STATO'", + Util.format(datefrom), + Util.format(dateTo), + creditorInstitution, + noticeNumber, + paymentToken)) .setSelect(propertiesToSelect); - return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + return getTableClient().listEntities(options, null, null).stream() + .map( + e -> { + return tableEntityToEventEntity(e); + }) + .collect(Collectors.toList()); } - public List findReByCiAndIUVAndCCP(LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv,String ccp){ - ListEntitiesOptions options = new ListEntitiesOptions() - .setFilter(String.format("PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and iuv eq '%s' and ccp eq '%s' and esito eq 'CAMBIO_STATO'", - Util.format(datefrom),Util.format(dateTo), creditorInstitution, iuv,ccp)) + public List findReByCiAndIUVAndCCP( + LocalDate datefrom, LocalDate dateTo, String creditorInstitution, String iuv, String ccp) { + ListEntitiesOptions options = + new ListEntitiesOptions() + .setFilter( + String.format( + "PartitionKey ge '%s' and PartitionKey le '%s' and idDominio eq '%s' and iuv eq" + + " '%s' and ccp eq '%s' and esito eq 'CAMBIO_STATO'", + Util.format(datefrom), Util.format(dateTo), creditorInstitution, iuv, ccp)) .setSelect(propertiesToSelect); - return getTableClient().listEntities(options, null, null).stream().map(e->{return tableEntityToEventEntity(e);}).collect(Collectors.toList()); + return getTableClient().listEntities(options, null, null).stream() + .map( + e -> { + return tableEntityToEventEntity(e); + }) + .collect(Collectors.toList()); } - private String getString(Object o){ - if(o==null) return null; - return (String)o; + private String getString(Object o) { + if (o == null) return null; + return (String) o; } - } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java index 2272212..5973733 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Count.java @@ -10,5 +10,5 @@ @NoArgsConstructor @AllArgsConstructor public class Count { - Long count; + Long count; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java index 11800d3..a51612c 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java @@ -4,12 +4,11 @@ import io.quarkus.mongodb.panache.PanacheQuery; import io.quarkus.mongodb.panache.common.MongoEntity; import io.quarkus.panache.common.Parameters; +import java.time.LocalDate; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; -import java.time.LocalDate; - @Data @EqualsAndHashCode(callSuper = true) @Builder @@ -52,26 +51,41 @@ public class EventEntity extends PanacheMongoEntity { public static PanacheQuery findByCIAndNAV( String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and status like 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("noticeNumber",nav)) - .project(EventEntity.class); + return find( + "idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and" + + " status like 'payment_'", + Parameters.with("idDominio", creditorInstitution).and("noticeNumber", nav)) + .project(EventEntity.class); } + public static PanacheQuery findByCIAndNAVAndToken( - String creditorInstitution, String nav,String paymentToken, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and status like 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("noticeNumber",nav)) - .project(EventEntity.class); + String creditorInstitution, + String nav, + String paymentToken, + LocalDate dateFrom, + LocalDate dateTo) { + return find( + "idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and" + + " status like 'payment_'", + Parameters.with("idDominio", creditorInstitution).and("noticeNumber", nav)) + .project(EventEntity.class); } + public static PanacheQuery findByCIAndIUV( - String creditorInstitution, String iuv, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("iuv",iuv)) - .project(EventEntity.class); + String creditorInstitution, String iuv, LocalDate dateFrom, LocalDate dateTo) { + return find( + "idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like" + + " 'payment_'", + Parameters.with("idDominio", creditorInstitution).and("iuv", iuv)) + .project(EventEntity.class); } + public static PanacheQuery findByCIAndIUVAndCCP( - String creditorInstitution, String iuv,String ccp, LocalDate dateFrom, LocalDate dateTo) { - return find("idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("iuv",iuv)) - .project(EventEntity.class); + String creditorInstitution, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { + return find( + "idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like" + + " 'payment_'", + Parameters.with("idDominio", creditorInstitution).and("iuv", iuv)) + .project(EventEntity.class); } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java index 2e8501b..f001b5c 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeBizEvent.java @@ -1,13 +1,12 @@ package it.gov.pagopa.nodetsworker.repository.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @Data @Builder @NoArgsConstructor diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativePaymentInfo.java index ff2821d..f52641e 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativePaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativePaymentInfo.java @@ -3,7 +3,6 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; - import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeTransfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeTransfer.java index 73b830f..b54d2cd 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeTransfer.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/NegativeTransfer.java @@ -1,7 +1,6 @@ package it.gov.pagopa.nodetsworker.repository.model; import java.math.BigDecimal; - import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PaymentInfo.java index 13e0c92..9961928 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PaymentInfo.java @@ -1,10 +1,8 @@ package it.gov.pagopa.nodetsworker.repository.model; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.math.BigDecimal; -import java.time.LocalDate; import java.time.LocalDateTime; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java index 4f179ee..236ace9 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/PositiveBizEvent.java @@ -1,21 +1,18 @@ package it.gov.pagopa.nodetsworker.repository.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import io.quarkus.mongodb.panache.common.MongoEntity; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.time.LocalDateTime; -import java.util.List; - @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) -public class PositiveBizEvent { +public class PositiveBizEvent { private String version; private String id; private String idPaymentManager; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Transfer.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Transfer.java index 24c5c53..45bf3ae 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Transfer.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/Transfer.java @@ -1,8 +1,7 @@ package it.gov.pagopa.nodetsworker.repository.model; -import java.math.BigDecimal; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.math.BigDecimal; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java index 330e5a2..aa51c80 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/InfoResource.java @@ -7,6 +7,7 @@ import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; +import java.util.Arrays; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.media.Content; @@ -16,8 +17,6 @@ import org.eclipse.microprofile.openapi.annotations.tags.Tag; import org.jboss.logging.Logger; -import java.util.Arrays; - @Path("/info") @Tag(name = "Info", description = "Info operations") public class InfoResource { diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java index 9e51b04..52cafb5 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java @@ -8,103 +8,171 @@ import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.io.Serializable; +import java.time.LocalDate; import org.eclipse.microprofile.openapi.annotations.media.Content; import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; -import java.io.Serializable; -import java.time.LocalDate; - @Path("/organizations") @Produces(value = MediaType.APPLICATION_JSON) public class WorkerResource implements Serializable { - @Inject - WorkerService workerService; - - /** - * ###### ######## ##### ####### - * ## ## ## ## ## ## ## ## - * ## ## ## ## ## ## - * ###### ######## ## ## ####### - * ## ## ## ## ## - * ## ## ## ## ## ## ## - * ###### ## ##### ####### - */ - @APIResponses(value = { - @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), - @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), - @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) - }) - @GET - @Path("/{organizationFiscalCode}/noticeNumber/{noticeNumber}") - public Response useCaseSP03_byNoticeNumber( - @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, - @PathParam("noticeNumber") @NotNull String noticeNumber, - @QueryParam("dateFrom") LocalDate dateFrom, - @QueryParam("dateTo") LocalDate dateTo - ) { - return Response.ok(workerService.getInfoByNoticeNumber(organizationFiscalCode, noticeNumber, dateFrom, dateTo)).build(); - } + @Inject WorkerService workerService; - @APIResponses(value = { - @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), - @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), - @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) - }) - @GET - @Path("/{organizationFiscalCode}/iuv/{iuv}") - public Response useCaseSP03_byIUV( - @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, - @PathParam("iuv") @NotNull String iuv, - @QueryParam("dateFrom") LocalDate dateFrom, - @QueryParam("dateTo") LocalDate dateTo - ) { - return Response.ok(workerService.getInfoByIUV(organizationFiscalCode, iuv, dateFrom, dateTo)).build(); - } + /** + * ###### ######## ##### ####### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ######## ## ## + * ####### ## ## ## ## ## ## ## ## ## ## ## ## ###### ## ##### ####### + */ + @APIResponses( + value = { + @APIResponse( + responseCode = "200", + description = "OK", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse( + responseCode = "400", + description = "Bad Request", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))), + @APIResponse( + responseCode = "500", + description = "Service unavailable.", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/noticeNumber/{noticeNumber}") + public Response useCaseSP03_byNoticeNumber( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("noticeNumber") @NotNull String noticeNumber, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo) { + return Response.ok( + workerService.getInfoByNoticeNumber( + organizationFiscalCode, noticeNumber, dateFrom, dateTo)) + .build(); + } - /** - * ###### ######## ##### ## - * ## ## ## ## ## ## ## ## - * ## ## ## ## ## ## ## - * ###### ######## ## ## ## ## - * ## ## ## ## ######### - * ## ## ## ## ## ## - * ###### ## ##### ## - */ + @APIResponses( + value = { + @APIResponse( + responseCode = "200", + description = "OK", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse( + responseCode = "400", + description = "Bad Request", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))), + @APIResponse( + responseCode = "500", + description = "Service unavailable.", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/iuv/{iuv}") + public Response useCaseSP03_byIUV( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("iuv") @NotNull String iuv, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo) { + return Response.ok(workerService.getInfoByIUV(organizationFiscalCode, iuv, dateFrom, dateTo)) + .build(); + } - @APIResponses(value = { - @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), - @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), - @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) - }) - @GET - @Path("/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}") - public Response useCaseSP04_byIUV_PaymentToken( - @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, - @PathParam("iuv") @NotNull String iuv, - @PathParam("paymentToken") @NotNull String paymentToken, - @QueryParam("dateFrom") LocalDate dateFrom, - @QueryParam("dateTo") LocalDate dateTo - ) { - return Response.ok(workerService.getAttemptByNoticeNumberAndPaymentToken(organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)).build(); - } + /** + * ###### ######## ##### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ######## ## ## ## + * ## ## ## ## ## ######### ## ## ## ## ## ## ###### ## ##### ## + */ + @APIResponses( + value = { + @APIResponse( + responseCode = "200", + description = "OK", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse( + responseCode = "400", + description = "Bad Request", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))), + @APIResponse( + responseCode = "500", + description = "Service unavailable.", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}") + public Response useCaseSP04_byIUV_PaymentToken( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("iuv") @NotNull String iuv, + @PathParam("paymentToken") @NotNull String paymentToken, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo) { + return Response.ok( + workerService.getAttemptByNoticeNumberAndPaymentToken( + organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)) + .build(); + } - @APIResponses(value = { - @APIResponse(responseCode = "200", description = "OK", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = TransactionResponse.class))), - @APIResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))), - @APIResponse(responseCode = "500", description = "Service unavailable.", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = ProblemJson.class))) - }) - @GET - @Path("/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}") - public Response useCaseSP04_byIUV_CCP( - @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, - @PathParam("iuv") @NotNull String iuv, - @PathParam("ccp") @NotNull String ccp, - @QueryParam("dateFrom") LocalDate dateFrom, - @QueryParam("dateTo") LocalDate dateTo - ) { - return Response.ok(workerService.getAttemptByIUVAndCCP(organizationFiscalCode, iuv, ccp, dateFrom, dateTo)).build(); - } + @APIResponses( + value = { + @APIResponse( + responseCode = "200", + description = "OK", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = TransactionResponse.class))), + @APIResponse( + responseCode = "400", + description = "Bad Request", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))), + @APIResponse( + responseCode = "500", + description = "Service unavailable.", + content = + @Content( + mediaType = MediaType.APPLICATION_JSON, + schema = @Schema(implementation = ProblemJson.class))) + }) + @GET + @Path("/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}") + public Response useCaseSP04_byIUV_CCP( + @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, + @PathParam("iuv") @NotNull String iuv, + @PathParam("ccp") @NotNull String ccp, + @QueryParam("dateFrom") LocalDate dateFrom, + @QueryParam("dateTo") LocalDate dateTo) { + return Response.ok( + workerService.getAttemptByIUVAndCCP(organizationFiscalCode, iuv, ccp, dateFrom, dateTo)) + .build(); + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java index ad892be..63d6f21 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java @@ -3,12 +3,11 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; import lombok.*; import lombok.extern.jackson.Jacksonized; import org.eclipse.microprofile.openapi.annotations.media.Schema; -import java.util.List; - @Getter @Builder @Jacksonized diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java index 7e533b4..3d64e7d 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java @@ -14,19 +14,17 @@ import jakarta.validation.UnexpectedTypeException; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Response; -import org.jboss.logging.Logger; -import org.jboss.resteasy.reactive.RestResponse; -import org.jboss.resteasy.reactive.server.ServerExceptionMapper; -import org.slf4j.MDC; - import java.time.Instant; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jboss.logging.Logger; +import org.jboss.resteasy.reactive.RestResponse; +import org.jboss.resteasy.reactive.server.ServerExceptionMapper; -//import static it.gov.pagopa.fdr.util.AppMessageUtil.logErrorMessage; -//import static it.gov.pagopa.fdr.util.MDCKeys.TRX_ID; +// import static it.gov.pagopa.fdr.util.AppMessageUtil.logErrorMessage; +// import static it.gov.pagopa.fdr.util.MDCKeys.TRX_ID; public class ExceptionMappers { @@ -219,8 +217,8 @@ public RestResponse mapUnexpectedTypeException(UnexpectedTypeExce @ServerExceptionMapper public RestResponse mapThrowable(Throwable exception) { -// String errorId = MDC.get(TRX_ID); -// log.errorf(logErrorMessage(exception.getMessage())); + // String errorId = MDC.get(TRX_ID); + // log.errorf(logErrorMessage(exception.getMessage())); AppException appEx = new AppException(exception, AppErrorCodeMessageEnum.ERROR); AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); @@ -228,7 +226,7 @@ public RestResponse mapThrowable(Throwable exception) { ErrorResponse errorResponse = ErrorResponse.builder() -// .errorId(errorId) + // .errorId(errorId) .httpStatusCode(status.getStatusCode()) .httpStatusDescription(status.getReasonPhrase()) .appErrorCode(codeMessage.errorCode()) diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java index cfb5a63..d24ab13 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/InfoResponse.java @@ -1,12 +1,11 @@ package it.gov.pagopa.nodetsworker.resources.response; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; import lombok.*; import lombok.extern.jackson.Jacksonized; import org.eclipse.microprofile.openapi.annotations.media.Schema; -import java.util.List; - @Getter @Builder @Jacksonized diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/TransactionResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/TransactionResponse.java index 23506f7..2a95d92 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/response/TransactionResponse.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/response/TransactionResponse.java @@ -3,10 +3,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import it.gov.pagopa.nodetsworker.models.BasePaymentInfo; -import lombok.*; - import java.time.LocalDate; import java.util.List; +import lombok.*; @Getter @Setter @@ -15,12 +14,13 @@ @Builder public class TransactionResponse { - private LocalDate dateFrom; - private LocalDate dateTo; - @JsonProperty("data") - @JsonSubTypes({ - @JsonSubTypes.Type(value = BasePaymentInfo.class, name = "car"), - @JsonSubTypes.Type(value = BasePaymentInfo.class, name = "truck") - }) - private List payments; + private LocalDate dateFrom; + private LocalDate dateTo; + + @JsonProperty("data") + @JsonSubTypes({ + @JsonSubTypes.Type(value = BasePaymentInfo.class, name = "car"), + @JsonSubTypes.Type(value = BasePaymentInfo.class, name = "truck") + }) + private List payments; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index 6d5cbdd..d488588 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -19,330 +19,369 @@ import it.gov.pagopa.nodetsworker.util.StatusUtil; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import org.jboss.logging.Logger; -import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; - import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; +import org.jboss.logging.Logger; +import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; @ApplicationScoped public class WorkerService { - private static String outcomeOK = "OK"; - private static String outcomeKO = "KO"; - - @Inject - Logger log; - - @Inject - Config configObject; - - @Inject - EventMapper eventsMapper; - - @Inject - CosmosBizEventClient positiveBizClient; - @Inject - CosmosNegBizEventClient negativeBizClient; - - @Inject - ReTableService reTableService; - - private PaymentInfo eventToPaymentInfo(ConfigDataV1 config,EventEntity ee){ - String brokerid = Optional.ofNullable(config.getChannels().get(ee.getCanale())).map(s->s.getBrokerPspCode()).orElse(null); - return PaymentInfo.builder() - .pspId(ee.getPsp()) - .nodeId(ee.getServiceIdentifier()) - .channelId(ee.getCanale()) - .brokerPspId(brokerid) - .insertedTimestamp(ee.getInsertedTimestamp()) - .paymentToken(ee.getPaymentToken()) - .noticeNumber(ee.getNoticeNumber()) - .iuv(ee.getIuv()) - .organizationFiscalCode(ee.getIdDominio()) - .status(StatusUtil.statoByReStatus(ee.getStatus())) - .build(); - } - - private PaymentAttemptInfo eventToPaymentAttemptInfo(ConfigDataV1 config,EventEntity ee){ - String brokerid = Optional.ofNullable(config.getChannels().get(ee.getCanale())).map(s->s.getBrokerPspCode()).orElse(null); - return PaymentAttemptInfo.builder() - .pspId(ee.getPsp()) - .nodeId(ee.getServiceIdentifier()) - .channelId(ee.getCanale()) - .brokerPspId(brokerid) - .insertedTimestamp(ee.getInsertedTimestamp()) - .paymentToken(ee.getPaymentToken()) - .noticeNumber(ee.getNoticeNumber()) - .iuv(ee.getIuv()) - .organizationFiscalCode(ee.getIdDominio()) - .status(StatusUtil.statoByReStatus(ee.getStatus())) - .stationId(ee.getStazione()) - .build(); + private static String outcomeOK = "OK"; + private static String outcomeKO = "KO"; + + @Inject Logger log; + + @Inject Config configObject; + + @Inject EventMapper eventsMapper; + + @Inject CosmosBizEventClient positiveBizClient; + @Inject CosmosNegBizEventClient negativeBizClient; + + @Inject ReTableService reTableService; + + private PaymentInfo eventToPaymentInfo(ConfigDataV1 config, EventEntity ee) { + String brokerid = + Optional.ofNullable(config.getChannels().get(ee.getCanale())) + .map(s -> s.getBrokerPspCode()) + .orElse(null); + return PaymentInfo.builder() + .pspId(ee.getPsp()) + .nodeId(ee.getServiceIdentifier()) + .channelId(ee.getCanale()) + .brokerPspId(brokerid) + .insertedTimestamp(ee.getInsertedTimestamp()) + .paymentToken(ee.getPaymentToken()) + .noticeNumber(ee.getNoticeNumber()) + .iuv(ee.getIuv()) + .organizationFiscalCode(ee.getIdDominio()) + .status(StatusUtil.statoByReStatus(ee.getStatus())) + .build(); + } + + private PaymentAttemptInfo eventToPaymentAttemptInfo(ConfigDataV1 config, EventEntity ee) { + String brokerid = + Optional.ofNullable(config.getChannels().get(ee.getCanale())) + .map(s -> s.getBrokerPspCode()) + .orElse(null); + return PaymentAttemptInfo.builder() + .pspId(ee.getPsp()) + .nodeId(ee.getServiceIdentifier()) + .channelId(ee.getCanale()) + .brokerPspId(brokerid) + .insertedTimestamp(ee.getInsertedTimestamp()) + .paymentToken(ee.getPaymentToken()) + .noticeNumber(ee.getNoticeNumber()) + .iuv(ee.getIuv()) + .organizationFiscalCode(ee.getIdDominio()) + .status(StatusUtil.statoByReStatus(ee.getStatus())) + .stationId(ee.getStazione()) + .build(); + } + + private void enrichPaymentAttemptInfo( + ConfigDataV1 config, PaymentAttemptInfo pai, PositiveBizEvent pbe) { + Long stationVersion = + Optional.ofNullable(config.getStations().get(pai.getStationId())) + .map(s -> s.getVersion()) + .orElse(null); + pai.setPaymentToken(pbe.getPaymentInfo().getPaymentToken()); + pai.setIsOldPaymentModel(pbe.getDebtorPosition().getModelType().equals("1")); + if (pai.getBrokerPspId() == null) { + pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); } - - private void enrichPaymentAttemptInfo(ConfigDataV1 config,PaymentAttemptInfo pai, PositiveBizEvent pbe){ - Long stationVersion = Optional.ofNullable(config.getStations().get(pai.getStationId())).map(s->s.getVersion()).orElse(null); - pai.setPaymentToken(pbe.getPaymentInfo().getPaymentToken()); - pai.setIsOldPaymentModel(pbe.getDebtorPosition().getModelType().equals("1")); - if(pai.getBrokerPspId()==null){ - pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); - } - pai.setStationVersion(stationVersion); - pai.setAmount(pbe.getPaymentInfo().getAmount()); - pai.setFee(pbe.getPaymentInfo().getFee()); - pai.setFeeOrganization(pbe.getPaymentInfo().getPrimaryCiIncurredFee()); - pai.setPaymentMethod(pbe.getPaymentInfo().getPaymentMethod()); - pai.setPmReceipt(pbe.getTransactionDetails()!=null); - pai.setPaymentChannel(pbe.getPaymentInfo().getTouchpoint()); - pai.setBundleId(pbe.getPaymentInfo().getIdBundle()); - pai.setBundleOrganizationId(pbe.getPaymentInfo().getIdCiBundle()); - pai.setApplicationDate(pbe.getPaymentInfo().getApplicationDate()); - pai.setTransferDate(pbe.getPaymentInfo().getTransferDate()); + pai.setStationVersion(stationVersion); + pai.setAmount(pbe.getPaymentInfo().getAmount()); + pai.setFee(pbe.getPaymentInfo().getFee()); + pai.setFeeOrganization(pbe.getPaymentInfo().getPrimaryCiIncurredFee()); + pai.setPaymentMethod(pbe.getPaymentInfo().getPaymentMethod()); + pai.setPmReceipt(pbe.getTransactionDetails() != null); + pai.setPaymentChannel(pbe.getPaymentInfo().getTouchpoint()); + pai.setBundleId(pbe.getPaymentInfo().getIdBundle()); + pai.setBundleOrganizationId(pbe.getPaymentInfo().getIdCiBundle()); + pai.setApplicationDate(pbe.getPaymentInfo().getApplicationDate()); + pai.setTransferDate(pbe.getPaymentInfo().getTransferDate()); + } + + private void enrichPaymentAttemptInfo( + ConfigDataV1 config, PaymentAttemptInfo pai, NegativeBizEvent nbe) { + Long stationVersion = + Optional.ofNullable(config.getStations().get(pai.getStationId())) + .map(s -> s.getVersion()) + .orElse(null); + pai.setIsOldPaymentModel(nbe.getDebtorPosition().getModelType().equals("1")); + if (pai.getBrokerPspId() == null) { + pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); } - - private void enrichPaymentAttemptInfo(ConfigDataV1 config,PaymentAttemptInfo pai, NegativeBizEvent nbe){ - Long stationVersion = Optional.ofNullable(config.getStations().get(pai.getStationId())).map(s->s.getVersion()).orElse(null); - pai.setIsOldPaymentModel(nbe.getDebtorPosition().getModelType().equals("1")); - if(pai.getBrokerPspId()==null) { - pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); - } - pai.setStationVersion(stationVersion); - pai.setAmount(nbe.getPaymentInfo().getAmount()); - pai.setPaymentMethod(nbe.getPaymentInfo().getPaymentMethod()); - pai.setPmReceipt(nbe.getTransactionDetails()!=null); - pai.setPaymentChannel(nbe.getPaymentInfo().getTouchpoint()); - } - - public TransactionResponse getInfoByNoticeNumber(String organizationFiscalCode, - String noticeNumber, - LocalDate dateFrom, - LocalDate dateTo){ - - log.infof("getInfoByNoticeNumber %s,%s,%s,%s",organizationFiscalCode,noticeNumber,dateFrom,dateTo); - - DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndNN(dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, noticeNumber); - - Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); - - log.infof("found %d different tokens",reGroups.size()); - - List collect = reGroups.keySet().stream().map(paymentToken->{ - List events = reGroups.get(paymentToken); - EventEntity lastEvent = events.get(events.size()-1); - PaymentInfo pi = eventToPaymentInfo(config,lastEvent); - - Optional pos = positiveBizClient.countEventsByCiAndNN( - lastEvent.getIdDominio(), - lastEvent.getNoticeNumber(), - dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if(pos.isPresent() && pos.get().getCount()>0){ - pi.setOutcome(outcomeOK); - }else{ - Optional neg = negativeBizClient.findEventsByCiAndNNAndToken( - lastEvent.getIdDominio(), - lastEvent.getNoticeNumber(), - paymentToken, - dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if(neg.isPresent()){ - if(!neg.get().getReAwakable()){ + pai.setStationVersion(stationVersion); + pai.setAmount(nbe.getPaymentInfo().getAmount()); + pai.setPaymentMethod(nbe.getPaymentInfo().getPaymentMethod()); + pai.setPmReceipt(nbe.getTransactionDetails() != null); + pai.setPaymentChannel(nbe.getPaymentInfo().getTouchpoint()); + } + + public TransactionResponse getInfoByNoticeNumber( + String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo) { + + log.infof( + "getInfoByNoticeNumber %s,%s,%s,%s", + organizationFiscalCode, noticeNumber, dateFrom, dateTo); + + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); + List reStorageEvents = + reTableService.findReByCiAndNN( + dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, noticeNumber); + + Map> reGroups = + reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getPaymentToken)); + + log.infof("found %d different tokens", reGroups.size()); + + List collect = + reGroups.keySet().stream() + .map( + paymentToken -> { + List events = reGroups.get(paymentToken); + EventEntity lastEvent = events.get(events.size() - 1); + PaymentInfo pi = eventToPaymentInfo(config, lastEvent); + + Optional pos = + positiveBizClient + .countEventsByCiAndNN( + lastEvent.getIdDominio(), + lastEvent.getNoticeNumber(), + dateRequest.getFrom(), + dateRequest.getTo()) + .stream() + .findFirst(); + if (pos.isPresent() && pos.get().getCount() > 0) { + pi.setOutcome(outcomeOK); + } else { + Optional neg = + negativeBizClient + .findEventsByCiAndNNAndToken( + lastEvent.getIdDominio(), + lastEvent.getNoticeNumber(), + paymentToken, + dateRequest.getFrom(), + dateRequest.getTo()) + .stream() + .findFirst(); + if (neg.isPresent()) { + if (!neg.get().getReAwakable()) { pi.setOutcome(outcomeKO); + } } - } - } - return pi; - }).collect(Collectors.toList()); - - return TransactionResponse.builder() - .dateFrom(dateRequest.getFrom()) - .dateTo(dateRequest.getTo()) - .payments(collect) - .build(); - - } - - public TransactionResponse getInfoByIUV(String organizationFiscalCode, - String iuv, - LocalDate dateFrom, - LocalDate dateTo){ - - log.infof("getInfoByIUV %s,%s,%s,%s",organizationFiscalCode,iuv,dateFrom,dateTo); - - DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); - List reStorageEvents = reTableService.findReByCiAndIUV(dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, iuv); - - Map> reGroups = reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); - - log.infof("found %d different ccps",reGroups.size()); - - List collect = reGroups.keySet().stream().map(ccp->{ - List events = reGroups.get(ccp); - EventEntity lastEvent = events.get(events.size()-1); - PaymentInfo pi = eventToPaymentInfo(config,lastEvent); - - Optional pos = positiveBizClient.countEventsByCiAndIUV( - lastEvent.getIdDominio(), - lastEvent.getIuv(), - dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if(pos.isPresent() && pos.get().getCount()>0){ - pi.setOutcome(outcomeOK); - }else{ - Optional neg = negativeBizClient.findEventsByCiAndIUVAndCCP( - lastEvent.getIdDominio(), - lastEvent.getIuv(), - ccp, - dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if(neg.isPresent()){ - if(!neg.get().getReAwakable()){ + } + return pi; + }) + .collect(Collectors.toList()); + + return TransactionResponse.builder() + .dateFrom(dateRequest.getFrom()) + .dateTo(dateRequest.getTo()) + .payments(collect) + .build(); + } + + public TransactionResponse getInfoByIUV( + String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo) { + + log.infof("getInfoByIUV %s,%s,%s,%s", organizationFiscalCode, iuv, dateFrom, dateTo); + + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); + List reStorageEvents = + reTableService.findReByCiAndIUV( + dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, iuv); + + Map> reGroups = + reStorageEvents.stream().collect(Collectors.groupingBy(EventEntity::getCcp)); + + log.infof("found %d different ccps", reGroups.size()); + + List collect = + reGroups.keySet().stream() + .map( + ccp -> { + List events = reGroups.get(ccp); + EventEntity lastEvent = events.get(events.size() - 1); + PaymentInfo pi = eventToPaymentInfo(config, lastEvent); + + Optional pos = + positiveBizClient + .countEventsByCiAndIUV( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + dateRequest.getFrom(), + dateRequest.getTo()) + .stream() + .findFirst(); + if (pos.isPresent() && pos.get().getCount() > 0) { + pi.setOutcome(outcomeOK); + } else { + Optional neg = + negativeBizClient + .findEventsByCiAndIUVAndCCP( + lastEvent.getIdDominio(), + lastEvent.getIuv(), + ccp, + dateRequest.getFrom(), + dateRequest.getTo()) + .stream() + .findFirst(); + if (neg.isPresent()) { + if (!neg.get().getReAwakable()) { pi.setOutcome(outcomeKO); + } } - } - } - - return pi; - }).collect(Collectors.toList()); - - return TransactionResponse.builder() - .dateFrom(dateFrom) - .dateTo(dateTo) - .payments(collect) - .build(); - - } - - public TransactionResponse getAttemptByNoticeNumberAndPaymentToken(String organizationFiscalCode, String noticeNumber, String paymentToken, LocalDate dateFrom, LocalDate dateTo) { - - log.infof("getInfoByNoticeNumberAndPaymentToken %s,%s,%s,%s,%s",organizationFiscalCode,noticeNumber,paymentToken,dateFrom,dateTo); - - DateRequest dateRequest = verifyDate(dateFrom, dateTo); - List events = reTableService.findReByCiAndNNAndToken(dateRequest.getFrom(),dateRequest.getTo(), organizationFiscalCode, noticeNumber,paymentToken); - List pais = new ArrayList<>(); - if(events.size()>0){ - EventEntity lastEvent = events.get(events.size()-1); - ConfigDataV1 config = configObject.getClonedCache(); - PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config,lastEvent); - - Optional pos = positiveBizClient.findEventsByCiAndNNAndToken( + } + + return pi; + }) + .collect(Collectors.toList()); + + return TransactionResponse.builder() + .dateFrom(dateFrom) + .dateTo(dateTo) + .payments(collect) + .build(); + } + + public TransactionResponse getAttemptByNoticeNumberAndPaymentToken( + String organizationFiscalCode, + String noticeNumber, + String paymentToken, + LocalDate dateFrom, + LocalDate dateTo) { + + log.infof( + "getInfoByNoticeNumberAndPaymentToken %s,%s,%s,%s,%s", + organizationFiscalCode, noticeNumber, paymentToken, dateFrom, dateTo); + + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + List events = + reTableService.findReByCiAndNNAndToken( + dateRequest.getFrom(), + dateRequest.getTo(), + organizationFiscalCode, + noticeNumber, + paymentToken); + List pais = new ArrayList<>(); + if (events.size() > 0) { + EventEntity lastEvent = events.get(events.size() - 1); + ConfigDataV1 config = configObject.getClonedCache(); + PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config, lastEvent); + + Optional pos = + positiveBizClient + .findEventsByCiAndNNAndToken( + organizationFiscalCode, + noticeNumber, + paymentToken, + dateRequest.getFrom(), + dateRequest.getTo()) + .stream() + .findFirst(); + if (pos.isPresent()) { + pai.setOutcome(outcomeOK); + enrichPaymentAttemptInfo(config, pai, pos.get()); + } else { + Optional neg = + negativeBizClient + .findEventsByCiAndNNAndToken( organizationFiscalCode, noticeNumber, paymentToken, dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if(pos.isPresent()){ - pai.setOutcome(outcomeOK); - enrichPaymentAttemptInfo(config,pai,pos.get()); - }else{ - Optional neg = negativeBizClient.findEventsByCiAndNNAndToken( - organizationFiscalCode, - noticeNumber, - paymentToken, - dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if(neg.isPresent()){ - if(!neg.get().getReAwakable()){ - pai.setOutcome(outcomeKO); - } - enrichPaymentAttemptInfo(config,pai,neg.get()); - } - } - pais.add(pai); + dateRequest.getTo()) + .stream() + .findFirst(); + if (neg.isPresent()) { + if (!neg.get().getReAwakable()) { + pai.setOutcome(outcomeKO); + } + enrichPaymentAttemptInfo(config, pai, neg.get()); } - - - return TransactionResponse.builder() - .dateFrom(dateFrom) - .dateTo(dateTo) - .payments(pais) - .build(); + } + pais.add(pai); } - - - public TransactionResponse getAttemptByIUVAndCCP(String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { - - log.infof("getAttemptByIUVAndCCP %s,%s,%s,%s,%s",organizationFiscalCode,iuv,ccp,dateFrom,dateTo); - - DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); - List events = reTableService.findReByCiAndIUVAndCCP(dateRequest.getFrom(),dateRequest.getTo(), organizationFiscalCode, iuv,ccp); - List pais = new ArrayList<>(); - if(events.size()>0) { - EventEntity lastEvent = events.get(events.size() - 1); - PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config, lastEvent); - String outcome = null; - - Optional pos = positiveBizClient.findEventsByCiAndIUVAndCCP( - organizationFiscalCode, - iuv, - ccp, - dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if (pos.isPresent()) { - pai.setOutcome(outcomeOK); - enrichPaymentAttemptInfo(config, pai, pos.get()); - } else { - Optional neg = negativeBizClient.findEventsByCiAndIUVAndCCP( - organizationFiscalCode, - iuv, - ccp, - dateRequest.getFrom(), - dateRequest.getTo() - ).stream().findFirst(); - if (neg.isPresent()) { - if (!neg.get().getReAwakable()) { - pai.setOutcome(outcomeKO); - } - enrichPaymentAttemptInfo(config, pai, neg.get()); - } - } - pais.add(pai); + return TransactionResponse.builder().dateFrom(dateFrom).dateTo(dateTo).payments(pais).build(); + } + + public TransactionResponse getAttemptByIUVAndCCP( + String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { + + log.infof( + "getAttemptByIUVAndCCP %s,%s,%s,%s,%s", organizationFiscalCode, iuv, ccp, dateFrom, dateTo); + + DateRequest dateRequest = verifyDate(dateFrom, dateTo); + ConfigDataV1 config = configObject.getClonedCache(); + List events = + reTableService.findReByCiAndIUVAndCCP( + dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, iuv, ccp); + List pais = new ArrayList<>(); + if (events.size() > 0) { + EventEntity lastEvent = events.get(events.size() - 1); + PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config, lastEvent); + String outcome = null; + + Optional pos = + positiveBizClient + .findEventsByCiAndIUVAndCCP( + organizationFiscalCode, iuv, ccp, dateRequest.getFrom(), dateRequest.getTo()) + .stream() + .findFirst(); + if (pos.isPresent()) { + pai.setOutcome(outcomeOK); + enrichPaymentAttemptInfo(config, pai, pos.get()); + } else { + Optional neg = + negativeBizClient + .findEventsByCiAndIUVAndCCP( + organizationFiscalCode, iuv, ccp, dateRequest.getFrom(), dateRequest.getTo()) + .stream() + .findFirst(); + if (neg.isPresent()) { + if (!neg.get().getReAwakable()) { + pai.setOutcome(outcomeKO); + } + enrichPaymentAttemptInfo(config, pai, neg.get()); } - - return TransactionResponse.builder() - .dateFrom(dateFrom) - .dateTo(dateTo) - .payments(pais) - .build(); + } + pais.add(pai); } - /** - * Check dates validity - * @param dateFrom - * @param dateTo - */ - private DateRequest verifyDate(LocalDate dateFrom, LocalDate dateTo) { - if (dateFrom == null && dateTo != null || dateFrom != null && dateTo == null) { - throw new AppException(AppErrorCodeMessageEnum.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from and date to must be both defined"); - } - else if (dateFrom != null && dateTo != null && dateFrom.isAfter(dateTo)) { - throw new AppException(AppErrorCodeMessageEnum.POSITION_SERVICE_DATE_BAD_REQUEST, "Date from must be before date to"); - } - if (dateFrom == null && dateTo == null) { - dateTo = LocalDate.now(); - dateFrom = dateTo.minusDays(10); - } - return DateRequest.builder() - .from(dateFrom) - .to(dateTo) - .build(); + return TransactionResponse.builder().dateFrom(dateFrom).dateTo(dateTo).payments(pais).build(); + } + + /** + * Check dates validity + * + * @param dateFrom + * @param dateTo + */ + private DateRequest verifyDate(LocalDate dateFrom, LocalDate dateTo) { + if (dateFrom == null && dateTo != null || dateFrom != null && dateTo == null) { + throw new AppException( + AppErrorCodeMessageEnum.POSITION_SERVICE_DATE_BAD_REQUEST, + "Date from and date to must be both defined"); + } else if (dateFrom != null && dateTo != null && dateFrom.isAfter(dateTo)) { + throw new AppException( + AppErrorCodeMessageEnum.POSITION_SERVICE_DATE_BAD_REQUEST, + "Date from must be before date to"); } - + if (dateFrom == null && dateTo == null) { + dateTo = LocalDate.now(); + dateFrom = dateTo.minusDays(10); + } + return DateRequest.builder().from(dateFrom).to(dateTo).build(); + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java b/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java index 0b9c077..a85a740 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java @@ -7,38 +7,37 @@ @EqualsAndHashCode public class EventDto { - private String insertedTimestamp; - private String componente; - private String categoriaEvento; - private String sottoTipoEvento; - private String idDominio; - private String iuv; - private String ccp; - private String psp; - private String tipoVersamento; - private String tipoEvento; - private String fruitore; - private String erogatore; - private String stazione; - private String canale; - private String parametriSpecificiInterfaccia; - private String esito; - private String sessionId; - private String status; - private String payload; - private String info; - private String businessProcess; - private String fruitoreDescr; - private String erogatoreDescr; - private String pspDescr; - private String noticeNumber; - private String creditorReferenceId; - private String paymentToken; - private String sessionIdOriginal; - private String dataOraEvento; - private String uniqueId; - private String version; - private Long timestamp; - private String serviceIdentifier; - + private String insertedTimestamp; + private String componente; + private String categoriaEvento; + private String sottoTipoEvento; + private String idDominio; + private String iuv; + private String ccp; + private String psp; + private String tipoVersamento; + private String tipoEvento; + private String fruitore; + private String erogatore; + private String stazione; + private String canale; + private String parametriSpecificiInterfaccia; + private String esito; + private String sessionId; + private String status; + private String payload; + private String info; + private String businessProcess; + private String fruitoreDescr; + private String erogatoreDescr; + private String pspDescr; + private String noticeNumber; + private String creditorReferenceId; + private String paymentToken; + private String sessionIdOriginal; + private String dataOraEvento; + private String uniqueId; + private String version; + private Long timestamp; + private String serviceIdentifier; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java index 1398274..6761296 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java @@ -2,18 +2,17 @@ import it.gov.pagopa.nodetsworker.repository.model.EventEntity; import it.gov.pagopa.nodetsworker.service.dto.EventDto; +import java.util.List; import org.mapstruct.Mapper; import org.mapstruct.MappingConstants.ComponentModel; import org.mapstruct.factory.Mappers; -import java.util.List; - @Mapper(componentModel = ComponentModel.JAKARTA) public interface EventMapper { EventMapper INSTANCE = Mappers.getMapper(EventMapper.class); EventDto map(EventEntity entity); - List map(List entities); + List map(List entities); } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java b/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java index ffc7df6..195b674 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/StatusUtil.java @@ -2,49 +2,46 @@ public class StatusUtil { - public static String statoByReStatus(String reStatus){ - if(reStatus == null) return null; - switch (reStatus) { - case "payment_PAID": - case "payment_PAID_NORPT": - case "payment_NOTICE_GENERATED": - case "payment_NOTICE_STORED": - case "payment_NOTICE_SENT": - case "payment_NOTIFIED": - case "RT_ACCETTATA_PA": - return "completed"; - case "payment_CANCELLED": - case "payment_CANCELLED_NORPT": - case "payment_PAYING": - case "payment_PAYING_RPT": - case "RPT_RISOLTA_OK": - case "RPT_RISOLTA_KO": - case "RPT_RICEVUTA_NODO": - case "RPT_ACCETTATA_NODO": - case "RPT_ERRORE_INVIO_A_PSP": - case "RPT_INVIATA_A_PSP": - case "RPT_ACCETTATA_PSP": - case "RT_GENERATA_NODO": - case "RT_RICEVUTA_NODO": - case "RT_RIFIUTATA_NODO": - case "RT_ACCETTATA_NODO": - case "RT_ESITO_SCONOSCIUTO_PA": - case "RT_INVIATA_PA": - case "RPT_ESITO_SCONOSCIUTO_PSP": - case "RPT_PARCHEGGIATA_NODO": - case "RPT_PARCHEGGIATA_NODO_MOD3": - case "RT_ERRORE_INVIO_A_PA": - return "in progress"; - case "RPT_RIFIUTATA_PSP": - case "RT_RIFIUTATA_PA": - case "RPT_RIFIUTATA_NODO": - case "payment_FAILED": - case "payment_FAILED_NORPT": - return "failed"; - - - - } - return null; + public static String statoByReStatus(String reStatus) { + if (reStatus == null) return null; + switch (reStatus) { + case "payment_PAID": + case "payment_PAID_NORPT": + case "payment_NOTICE_GENERATED": + case "payment_NOTICE_STORED": + case "payment_NOTICE_SENT": + case "payment_NOTIFIED": + case "RT_ACCETTATA_PA": + return "completed"; + case "payment_CANCELLED": + case "payment_CANCELLED_NORPT": + case "payment_PAYING": + case "payment_PAYING_RPT": + case "RPT_RISOLTA_OK": + case "RPT_RISOLTA_KO": + case "RPT_RICEVUTA_NODO": + case "RPT_ACCETTATA_NODO": + case "RPT_ERRORE_INVIO_A_PSP": + case "RPT_INVIATA_A_PSP": + case "RPT_ACCETTATA_PSP": + case "RT_GENERATA_NODO": + case "RT_RICEVUTA_NODO": + case "RT_RIFIUTATA_NODO": + case "RT_ACCETTATA_NODO": + case "RT_ESITO_SCONOSCIUTO_PA": + case "RT_INVIATA_PA": + case "RPT_ESITO_SCONOSCIUTO_PSP": + case "RPT_PARCHEGGIATA_NODO": + case "RPT_PARCHEGGIATA_NODO_MOD3": + case "RT_ERRORE_INVIO_A_PA": + return "in progress"; + case "RPT_RIFIUTATA_PSP": + case "RT_RIFIUTATA_PA": + case "RPT_RIFIUTATA_NODO": + case "payment_FAILED": + case "payment_FAILED_NORPT": + return "failed"; } + return null; + } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java index 0e8f381..f516b91 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java @@ -1,6 +1,5 @@ package it.gov.pagopa.nodetsworker.util; -import jakarta.ejb.Local; import java.time.LocalDate; import java.time.LocalDateTime; @@ -9,24 +8,25 @@ import java.util.function.Function; public class Util { - public static String ifNotNull(Object o,String s){ - if(o!=null){ - return s; - }else{ - return ""; - } - } - public static void ifNotNull(Object o, Function func){ - if(o!=null){ - func.apply(null); - } + public static String ifNotNull(Object o, String s) { + if (o != null) { + return s; + } else { + return ""; } + } - public static Long toMillis(LocalDateTime d){ - return d.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + public static void ifNotNull(Object o, Function func) { + if (o != null) { + func.apply(null); } + } - public static String format(LocalDate d){ - return d.format(DateTimeFormatter.ISO_DATE); - } + public static Long toMillis(LocalDateTime d) { + return d.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + } + + public static String format(LocalDate d) { + return d.format(DateTimeFormatter.ISO_DATE); + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index fad6fd1..102cd5a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -71,10 +71,16 @@ biz.key=${COSMOS_BIZ_KEY:${mockserver.biz.key}} bizneg.endpoint=${COSMOS_NEG_BIZ_ENDPOINT:${mockserver.biz.endpoint}} bizneg.key=${COSMOS_NEG_BIZ_KEY:${mockserver.biz.key}} + re-table-storage.table-name=events re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING:${mockserver.azurite.connection-string}} %dev.re-table-storage.connection-string=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1; +%openapi.biz.endpoint=nn +%openapi.biz.key=nn +%openapi.bizneg.endpoint=nn +%openapi.bizneg.key=nn +%openapi.re-table-storage.connection-string=nn ################### ## ADAPTER API CONFIG CACHE diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/GenericTest.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/GenericTest.java index da063f2..3b4625e 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/GenericTest.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/GenericTest.java @@ -1,22 +1,16 @@ package it.gov.pagopa.nodetsworker.resources; +import static io.restassured.RestAssured.given; import io.quarkus.test.junit.QuarkusTest; -import org.junit.jupiter.api.Test; - import jakarta.ws.rs.core.MediaType; - -import static io.restassured.RestAssured.given; +import org.junit.jupiter.api.Test; @QuarkusTest class GenericTest { - @Test - public void info(){ - given() - .when().get("/info") - .then() - .statusCode(200) - .contentType(MediaType.APPLICATION_JSON); - } + @Test + public void info() { + given().when().get("/info").then().statusCode(200).contentType(MediaType.APPLICATION_JSON); + } } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java index 88261ad..ebf7e1b 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java @@ -1,5 +1,11 @@ package it.gov.pagopa.nodetsworker.resources; +import static io.restassured.RestAssured.given; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; + import com.azure.cosmos.CosmosClient; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.models.CosmosItemRequestOptions; @@ -11,28 +17,21 @@ import io.quarkus.test.junit.QuarkusTest; import io.restassured.common.mapper.TypeRef; import it.gov.pagopa.nodetsworker.models.PaymentInfo; -import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; +import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; import it.gov.pagopa.nodetsworker.util.AppConstantTestHelper; import it.gov.pagopa.nodetsworker.util.AzuriteResource; import it.gov.pagopa.nodetsworker.util.CosmosResource; import it.gov.pagopa.nodetsworker.util.Util; +import java.time.Instant; +import java.time.LocalDate; +import java.util.Random; import lombok.SneakyThrows; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.time.Instant; -import java.time.LocalDate; -import java.util.Random; - -import static io.restassured.RestAssured.given; -import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; - @QuarkusTest @QuarkusTestResource(MockServerTestResource.class) @QuarkusTestResource(AzuriteResource.class) @@ -51,24 +50,28 @@ class Sp03Test { private TableClient tableClient; private CosmosClient clientbiz; - private TableClient getTableClient(){ - if(tableClient==null){ - TableServiceClient tableServiceClient = new TableServiceClientBuilder().connectionString(connString).buildClient(); + private TableClient getTableClient() { + if (tableClient == null) { + TableServiceClient tableServiceClient = + new TableServiceClientBuilder().connectionString(connString).buildClient(); tableServiceClient.createTableIfNotExists("events"); tableClient = tableServiceClient.getTableClient("events"); } return tableClient; } - private CosmosClient getCosmosClient(){ - if(clientbiz==null) { + private CosmosClient getCosmosClient() { + if (clientbiz == null) { clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); clientbiz.createDatabaseIfNotExists(CosmosBizEventClient.dbname); - clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosBizEventClient.tablename,"/timestamp"); - clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosNegBizEventClient.tablename,"/timestamp"); + clientbiz + .getDatabase(CosmosBizEventClient.dbname) + .createContainerIfNotExists(CosmosBizEventClient.tablename, "/timestamp"); + clientbiz + .getDatabase(CosmosBizEventClient.dbname) + .createContainerIfNotExists(CosmosNegBizEventClient.tablename, "/timestamp"); } return clientbiz; - } @SneakyThrows @@ -78,28 +81,32 @@ void test1() { String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_NN.formatted(PA_CODE, noticeNumber); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( - AppConstantTestHelper.newPositiveBiz(PA_CODE, noticeNumber,null),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) - .when() - .get(url) - .then() - .statusCode(200) - .extract() - .as(new TypeRef>() {}); + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber, null)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, noticeNumber, null), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentInfo o = (PaymentInfo)res.getPayments().get(0); - assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentInfo o = (PaymentInfo) res.getPayments().get(0); + assertThat(o.getNoticeNumber(), equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -109,14 +116,18 @@ void test2() { String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_NN.formatted(PA_CODE, noticeNumber); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( - AppConstantTestHelper.newNegBiz(PA_CODE, noticeNumber,null,false),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber, null)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosNegBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, noticeNumber, null, false), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) .when() .get(url) .then() @@ -124,13 +135,13 @@ void test2() { .extract() .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentInfo o = (PaymentInfo)res.getPayments().get(0); - assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentInfo o = (PaymentInfo) res.getPayments().get(0); + assertThat(o.getNoticeNumber(), equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -140,14 +151,18 @@ void test3() { String iuv = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_IUV.formatted(PA_CODE, iuv); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( - AppConstantTestHelper.newPositiveBiz(PA_CODE, null, iuv),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null, iuv)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, null, iuv), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) .when() .get(url) .then() @@ -155,13 +170,13 @@ void test3() { .extract() .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentInfo o = (PaymentInfo)res.getPayments().get(0); - assertThat(o.getIuv(),equalTo(iuv)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentInfo o = (PaymentInfo) res.getPayments().get(0); + assertThat(o.getIuv(), equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -171,14 +186,18 @@ void test4() { String iuv = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_IUV.formatted(PA_CODE, iuv); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( - AppConstantTestHelper.newNegBiz(PA_CODE, null,iuv,false),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null, iuv)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosNegBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, null, iuv, false), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) .when() .get(url) .then() @@ -186,13 +205,13 @@ void test4() { .extract() .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentInfo o = (PaymentInfo)res.getPayments().get(0); - assertThat(o.getIuv(),equalTo(iuv)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentInfo o = (PaymentInfo) res.getPayments().get(0); + assertThat(o.getIuv(), equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -202,12 +221,7 @@ void test5() { String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); String url = SP03_IUV.formatted(PA_CODE, iuv); - given() - .param("dateFrom",Util.format(LocalDate.now())) - .when() - .get(url) - .then() - .statusCode(400); + given().param("dateFrom", Util.format(LocalDate.now())).when().get(url).then().statusCode(400); } @SneakyThrows @@ -217,12 +231,6 @@ void test6() { String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); String url = SP03_IUV.formatted(PA_CODE, iuv); - given() - .param("dateTo",Util.format(LocalDate.now())) - .when() - .get(url) - .then() - .statusCode(400); + given().param("dateTo", Util.format(LocalDate.now())).when().get(url).then().statusCode(400); } - } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java index 7e63397..9f72bed 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java @@ -1,5 +1,11 @@ package it.gov.pagopa.nodetsworker.resources; +import static io.restassured.RestAssured.given; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; + import com.azure.cosmos.CosmosClient; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.models.CosmosItemRequestOptions; @@ -18,21 +24,14 @@ import it.gov.pagopa.nodetsworker.util.AzuriteResource; import it.gov.pagopa.nodetsworker.util.CosmosResource; import it.gov.pagopa.nodetsworker.util.Util; +import java.time.Instant; +import java.time.LocalDate; +import java.util.Random; import lombok.SneakyThrows; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.time.Instant; -import java.time.LocalDate; -import java.util.Random; - -import static io.restassured.RestAssured.given; -import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; - @QuarkusTest @QuarkusTestResource(MockServerTestResource.class) @QuarkusTestResource(AzuriteResource.class) @@ -51,24 +50,28 @@ class Sp04Test { private TableClient tableClient; private CosmosClient clientbiz; - private TableClient getTableClient(){ - if(tableClient==null){ - TableServiceClient tableServiceClient = new TableServiceClientBuilder().connectionString(connString).buildClient(); + private TableClient getTableClient() { + if (tableClient == null) { + TableServiceClient tableServiceClient = + new TableServiceClientBuilder().connectionString(connString).buildClient(); tableServiceClient.createTableIfNotExists("events"); tableClient = tableServiceClient.getTableClient("events"); } return tableClient; } - private CosmosClient getCosmosClient(){ - if(clientbiz==null) { + private CosmosClient getCosmosClient() { + if (clientbiz == null) { clientbiz = new CosmosClientBuilder().endpoint(bizendpoint).key(bizkey).buildClient(); clientbiz.createDatabaseIfNotExists(CosmosBizEventClient.dbname); - clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosBizEventClient.tablename,"/timestamp"); - clientbiz.getDatabase(CosmosBizEventClient.dbname).createContainerIfNotExists(CosmosNegBizEventClient.tablename,"/timestamp"); + clientbiz + .getDatabase(CosmosBizEventClient.dbname) + .createContainerIfNotExists(CosmosBizEventClient.tablename, "/timestamp"); + clientbiz + .getDatabase(CosmosBizEventClient.dbname) + .createContainerIfNotExists(CosmosNegBizEventClient.tablename, "/timestamp"); } return clientbiz; - } @SneakyThrows @@ -76,31 +79,35 @@ private CosmosClient getCosmosClient(){ @DisplayName("sp04 by ci,nn,token with positive") void test1() { String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); - String token = "pt_"+noticeNumber; - String url = SP04_NN.formatted(PA_CODE, noticeNumber,token); - - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( - AppConstantTestHelper.newPositiveBiz(PA_CODE, noticeNumber,null),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) - .when() - .get(url) - .then() - .statusCode(200) - .extract() - .as(new TypeRef>() {}); + String token = "pt_" + noticeNumber; + String url = SP04_NN.formatted(PA_CODE, noticeNumber, token); + + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber, null)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, noticeNumber, null), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) + .when() + .get(url) + .then() + .statusCode(200) + .extract() + .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); - assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentAttemptInfo o = (PaymentAttemptInfo) res.getPayments().get(0); + assertThat(o.getNoticeNumber(), equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -108,17 +115,21 @@ void test1() { @DisplayName("sp04 by ci,nn,token with negative") void test2() { String noticeNumber = String.valueOf(Instant.now().toEpochMilli()); - String token = "pt_"+noticeNumber; + String token = "pt_" + noticeNumber; String url = SP04_NN.formatted(PA_CODE, noticeNumber, token); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber,null)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( - AppConstantTestHelper.newNegBiz(PA_CODE, noticeNumber,null,false),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, noticeNumber, null)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosNegBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, noticeNumber, null, false), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) .when() .get(url) .then() @@ -126,13 +137,13 @@ void test2() { .extract() .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); - assertThat(o.getNoticeNumber(),equalTo(noticeNumber)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentAttemptInfo o = (PaymentAttemptInfo) res.getPayments().get(0); + assertThat(o.getNoticeNumber(), equalTo(noticeNumber)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -140,17 +151,21 @@ void test2() { @DisplayName("sp04 by ci,iuv,ccp with positive") void test3() { String iuv = String.valueOf(Instant.now().toEpochMilli()); - String ccp = "ccp_"+iuv; + String ccp = "ccp_" + iuv; String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosBizEventClient.tablename).createItem( - AppConstantTestHelper.newPositiveBiz(PA_CODE, null, iuv),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null, iuv)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newPositiveBiz(PA_CODE, null, iuv), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) .when() .get(url) .then() @@ -158,13 +173,13 @@ void test3() { .extract() .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); - assertThat(o.getIuv(),equalTo(iuv)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeOK)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentAttemptInfo o = (PaymentAttemptInfo) res.getPayments().get(0); + assertThat(o.getIuv(), equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeOK)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -172,17 +187,21 @@ void test3() { @DisplayName("sp04 by ci,iuv,ccp with negative") void test4() { String iuv = String.valueOf(Instant.now().toEpochMilli()); - String ccp = "ccp_"+iuv; + String ccp = "ccp_" + iuv; String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); - getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null,iuv)); - getCosmosClient().getDatabase(CosmosBizEventClient.dbname).getContainer(CosmosNegBizEventClient.tablename).createItem( - AppConstantTestHelper.newNegBiz(PA_CODE, null,iuv,false),new CosmosItemRequestOptions() - ); - - TransactionResponse res = given() - .param("dateFrom",Util.format(LocalDate.now())) - .param("dateTo",Util.format(LocalDate.now())) + getTableClient().createEntity(AppConstantTestHelper.newRe(PA_CODE, null, iuv)); + getCosmosClient() + .getDatabase(CosmosBizEventClient.dbname) + .getContainer(CosmosNegBizEventClient.tablename) + .createItem( + AppConstantTestHelper.newNegBiz(PA_CODE, null, iuv, false), + new CosmosItemRequestOptions()); + + TransactionResponse res = + given() + .param("dateFrom", Util.format(LocalDate.now())) + .param("dateTo", Util.format(LocalDate.now())) .when() .get(url) .then() @@ -190,13 +209,13 @@ void test4() { .extract() .as(new TypeRef>() {}); assertThat(res.getPayments().size(), greaterThan(0)); - PaymentAttemptInfo o = (PaymentAttemptInfo)res.getPayments().get(0); - assertThat(o.getIuv(),equalTo(iuv)); - assertThat(o.getOrganizationFiscalCode(),equalTo(PA_CODE)); - assertThat(o.getOutcome(),equalTo(AppConstantTestHelper.outcomeKO)); - assertThat(o.getPspId(),equalTo("pspTest")); - assertThat(o.getChannelId(),equalTo("canaleTest")); - assertThat(o.getBrokerPspId(),equalTo("intTest")); + PaymentAttemptInfo o = (PaymentAttemptInfo) res.getPayments().get(0); + assertThat(o.getIuv(), equalTo(iuv)); + assertThat(o.getOrganizationFiscalCode(), equalTo(PA_CODE)); + assertThat(o.getOutcome(), equalTo(AppConstantTestHelper.outcomeKO)); + assertThat(o.getPspId(), equalTo("pspTest")); + assertThat(o.getChannelId(), equalTo("canaleTest")); + assertThat(o.getBrokerPspId(), equalTo("intTest")); } @SneakyThrows @@ -204,15 +223,10 @@ void test4() { @DisplayName("dateFrom 400") void test5() { String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); - String ccp = "ccp_"+iuv; + String ccp = "ccp_" + iuv; String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); - given() - .param("dateFrom",Util.format(LocalDate.now())) - .when() - .get(url) - .then() - .statusCode(400); + given().param("dateFrom", Util.format(LocalDate.now())).when().get(url).then().statusCode(400); } @SneakyThrows @@ -220,15 +234,9 @@ void test5() { @DisplayName("dateTo 400") void test6() { String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); - String ccp = "ccp_"+iuv; + String ccp = "ccp_" + iuv; String url = SP04_IUV.formatted(PA_CODE, iuv, ccp); - given() - .param("dateTo",Util.format(LocalDate.now())) - .when() - .get(url) - .then() - .statusCode(400); + given().param("dateTo", Util.format(LocalDate.now())).when().get(url).then().statusCode(400); } - } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java index e9af8c5..4133476 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java @@ -3,19 +3,17 @@ import com.azure.data.tables.models.TableEntity; import io.restassured.http.Header; import it.gov.pagopa.nodetsworker.repository.model.*; - import java.time.LocalDate; import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; import java.util.Optional; import java.util.UUID; public class AppConstantTestHelper { - public static final String SP03_NN = "/organizations/%s/noticeNumber/%s"; + public static final String SP03_NN = "/organizations/%s/noticeNumber/%s"; public static final String SP03_IUV = "/organizations/%s/iuv/%s"; - public static final String SP04_NN = "/organizations/%s/iuv/%s/paymentToken/%s"; + public static final String SP04_NN = "/organizations/%s/iuv/%s/paymentToken/%s"; public static final String SP04_IUV = "/organizations/%s/iuv/%s/ccp/%s"; public static final String PA_CODE = "12345678900"; @@ -24,55 +22,56 @@ public class AppConstantTestHelper { public static final Header HEADER = new Header("Content-Type", "application/json"); - public static final TableEntity newRe(String pa,String noticeNumber,String iuv){ - TableEntity entity = new TableEntity(Util.format(LocalDate.now()), String.valueOf(Optional.ofNullable(noticeNumber).orElse(iuv))); - entity.addProperty("idDominio",pa); - entity.addProperty("noticeNumber",noticeNumber); - entity.addProperty("iuv",iuv); - entity.addProperty("esito","CAMBIO_STATO"); - entity.addProperty("paymentToken","pt_"+noticeNumber); - entity.addProperty("ccp","ccp_"+iuv); - entity.addProperty("stazione","77777777777_01"); - entity.addProperty("psp","pspTest"); - entity.addProperty("canale","canaleTest"); - entity.addProperty("status","PAID"); + public static final TableEntity newRe(String pa, String noticeNumber, String iuv) { + TableEntity entity = + new TableEntity( + Util.format(LocalDate.now()), + String.valueOf(Optional.ofNullable(noticeNumber).orElse(iuv))); + entity.addProperty("idDominio", pa); + entity.addProperty("noticeNumber", noticeNumber); + entity.addProperty("iuv", iuv); + entity.addProperty("esito", "CAMBIO_STATO"); + entity.addProperty("paymentToken", "pt_" + noticeNumber); + entity.addProperty("ccp", "ccp_" + iuv); + entity.addProperty("stazione", "77777777777_01"); + entity.addProperty("psp", "pspTest"); + entity.addProperty("canale", "canaleTest"); + entity.addProperty("status", "PAID"); return entity; } - public static final PositiveBizEvent newPositiveBiz(String pa,String noticeNumber, String iuv){ - PositiveBizEvent p = PositiveBizEvent.builder() + public static final PositiveBizEvent newPositiveBiz(String pa, String noticeNumber, String iuv) { + PositiveBizEvent p = + PositiveBizEvent.builder() .id(UUID.randomUUID().toString()) .timestamp(Util.toMillis(LocalDateTime.now())) - .psp( - Psp.builder() - .psp("pspTest") - .idChannel("canaleTest") - .build() - ) - .creditor( - Creditor.builder().idPA(pa).build() - ).debtorPosition( - DebtorPosition.builder().modelType("1").iuv(iuv).noticeNumber(noticeNumber).build() - ).paymentInfo( - PaymentInfo.builder().paymentToken(noticeNumber!=null?"pt_"+noticeNumber:"ccp_"+iuv).paymentDateTime(LocalDateTime.now()).build() - ) + .psp(Psp.builder().psp("pspTest").idChannel("canaleTest").build()) + .creditor(Creditor.builder().idPA(pa).build()) + .debtorPosition( + DebtorPosition.builder().modelType("1").iuv(iuv).noticeNumber(noticeNumber).build()) + .paymentInfo( + PaymentInfo.builder() + .paymentToken(noticeNumber != null ? "pt_" + noticeNumber : "ccp_" + iuv) + .paymentDateTime(LocalDateTime.now()) + .build()) .build(); return p; } - public static final NegativeBizEvent newNegBiz(String pa, String noticeNumber, String iuv,boolean reawakable){ - NegativeBizEvent p = NegativeBizEvent.builder() + + public static final NegativeBizEvent newNegBiz( + String pa, String noticeNumber, String iuv, boolean reawakable) { + NegativeBizEvent p = + NegativeBizEvent.builder() .id(UUID.randomUUID().toString()) .timestamp(Util.toMillis(LocalDateTime.now())) - .creditor( - Creditor.builder().idPA(pa).build() - ).debtorPosition( - DebtorPosition.builder().iuv(iuv).noticeNumber(noticeNumber).modelType("1").build() - ).paymentInfo( - NegativePaymentInfo.builder() - .paymentToken(noticeNumber!=null?"pt_"+noticeNumber:"ccp_"+iuv) - .paymentDateTime(LocalDateTime.now()) - .build() - ) + .creditor(Creditor.builder().idPA(pa).build()) + .debtorPosition( + DebtorPosition.builder().iuv(iuv).noticeNumber(noticeNumber).modelType("1").build()) + .paymentInfo( + NegativePaymentInfo.builder() + .paymentToken(noticeNumber != null ? "pt_" + noticeNumber : "ccp_" + iuv) + .paymentDateTime(LocalDateTime.now()) + .build()) .reAwakable(reawakable) .build(); return p; diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java index c7746f7..b7ac4b6 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AzuriteResource.java @@ -1,13 +1,12 @@ package it.gov.pagopa.nodetsworker.util; import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; +import java.util.HashMap; +import java.util.Map; import lombok.SneakyThrows; import org.testcontainers.containers.GenericContainer; import org.testcontainers.utility.DockerImageName; -import java.util.HashMap; -import java.util.Map; - public class AzuriteResource implements QuarkusTestResourceLifecycleManager { private GenericContainer azurite; diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java index ffaeb1a..ebcca57 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/CosmosResource.java @@ -3,10 +3,6 @@ import com.github.terma.javaniotcpproxy.StaticTcpProxyConfig; import com.github.terma.javaniotcpproxy.TcpProxy; import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; -import lombok.SneakyThrows; -import org.testcontainers.containers.CosmosDBEmulatorContainer; -import org.testcontainers.utility.DockerImageName; - import java.io.File; import java.io.FileOutputStream; import java.net.InetAddress; @@ -16,10 +12,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.SneakyThrows; +import org.testcontainers.containers.CosmosDBEmulatorContainer; +import org.testcontainers.utility.DockerImageName; public class CosmosResource implements QuarkusTestResourceLifecycleManager { - private static final Integer[] exposedPorts = {8081, 10251, 10252, 10253, 10254}; private static CosmosDBEmulatorContainer cosmos = null; @@ -30,21 +28,24 @@ public class CosmosResource implements QuarkusTestResourceLifecycleManager { @Override public Map start() { - cosmos = new CosmosDBEmulatorContainer( - DockerImageName.parse("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator") - ) - .withEnv("AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE", InetAddress.getLocalHost().getHostAddress()) - .withEnv("AZURE_COSMOS_EMULATOR_PARTITION_COUNT", "3") - .withEnv("AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE", "false") - .withExposedPorts(exposedPorts); + cosmos = + new CosmosDBEmulatorContainer( + DockerImageName.parse("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator")) + .withEnv( + "AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE", + InetAddress.getLocalHost().getHostAddress()) + .withEnv("AZURE_COSMOS_EMULATOR_PARTITION_COUNT", "3") + .withEnv("AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE", "false") + .withExposedPorts(exposedPorts); cosmos.start(); CosmosResource.startTcpProxy(exposedPorts); - Path keyStoreFile = File.createTempFile("azure-cosmos-emulator",".keystore").toPath(); + Path keyStoreFile = File.createTempFile("azure-cosmos-emulator", ".keystore").toPath(); KeyStore keyStore = cosmos.buildNewKeyStore(); - keyStore.store(new FileOutputStream(keyStoreFile.toFile()), cosmos.getEmulatorKey().toCharArray()); + keyStore.store( + new FileOutputStream(keyStoreFile.toFile()), cosmos.getEmulatorKey().toCharArray()); System.setProperty("javax.net.ssl.trustStore", keyStoreFile.toString()); System.setProperty("javax.net.ssl.trustStorePassword", cosmos.getEmulatorKey()); @@ -59,12 +60,13 @@ public Map start() { @Override public void stop() { cosmos.stop(); - startedProxies.forEach(p->p.shutdown()); + startedProxies.forEach(p -> p.shutdown()); } private static void startTcpProxy(Integer... ports) { - for (Integer port: ports) { - StaticTcpProxyConfig tcpProxyConfig = new StaticTcpProxyConfig(port, cosmos.getHost(), cosmos.getMappedPort(port)); + for (Integer port : ports) { + StaticTcpProxyConfig tcpProxyConfig = + new StaticTcpProxyConfig(port, cosmos.getHost(), cosmos.getMappedPort(port)); tcpProxyConfig.setWorkerCount(1); TcpProxy tcpProxy = new TcpProxy(tcpProxyConfig); tcpProxy.start(); From b0e63f17e918e2a73856be4a037a45a075824e52 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 5 Jul 2023 18:48:45 +0200 Subject: [PATCH 10/29] wip --- .devops/deploy-pipelines.yml | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/.devops/deploy-pipelines.yml b/.devops/deploy-pipelines.yml index e7921eb..6b33bd4 100644 --- a/.devops/deploy-pipelines.yml +++ b/.devops/deploy-pipelines.yml @@ -85,7 +85,7 @@ variables: WEU_value_file: "helm/weu-${{ parameters['ENV'] }}/values-${{ parameters['ENV'] }}.yaml" NEU_value_file: "helm/neu-${{ parameters['ENV'] }}/values-${{ parameters['ENV'] }}.yaml" - appName: 'pagopafdr' + appName: 'pagopatechsupport' ${{ if eq(parameters['ENV'], 'dev') }}: WEU_dockerRegistryServiceConnection: $(DEV_CONTAINER_REGISTRY_SERVICE_CONN) @@ -136,14 +136,14 @@ stages: if [[ "${{ parameters.WEU }}" = "True" ]]; then VALUES_FILE="$(WEU_value_file)" if [[ -f "$VALUES_FILE" ]]; then - yq -i ".fdr.image.tag = \"$(next_version.value)\"" "$VALUES_FILE" + yq -i ".pagopa-tech-support.image.tag = \"$(next_version.value)\"" "$VALUES_FILE" git add "$VALUES_FILE" fi fi if [[ "${{ parameters.NEU }}" = "True" ]]; then VALUES_FILE="$(NEU_value_file)" if [[ -f "$VALUES_FILE" ]]; then - yq -i ".fdr.image.tag = \"$(next_version.value)\"" "$VALUES_FILE" + yq -i ".pagopa-tech-support.image.tag = \"$(next_version.value)\"" "$VALUES_FILE" git add "$VALUES_FILE" fi fi @@ -172,13 +172,6 @@ stages: git checkout $(sourceBranch) displayName: Checkout and update branch -# - task: AzureKeyVault@2 -# displayName: "Get secrets" -# inputs: -# azureSubscription: $(AZURE_SERVICE_CONNECTION) -# keyVaultName: 'pagopa-d-fdr-kv' -# secretsFilter: 'api-config-cache-subscription-key-string' - - template: templates/docker-release/template.yaml@pagopaCommons parameters: CONTAINER_REGISTRY_SERVICE_CONN: $(WEU_dockerRegistryServiceConnection) @@ -193,7 +186,7 @@ stages: # Deploy Canary if prod or uat - ${{ if and( parameters.WEU , in( parameters.ENV, 'prod', 'uat') ) }}: - ${{ each step in split(variables.weight_steps, ',')}}: - - stage: deploy_fdr_${{ step }} + - stage: deploy_pagopa_tech_support_${{ step }} displayName: "Deploy ${{ parameters.ENV }} canary ${{ step }}%" jobs: - job: get_release_version @@ -263,12 +256,12 @@ stages: #APPINSIGHTS_RESOURCE_ID: ${{ variables.WEU_appInsightsResourceId }} CHART_PATH: "helm" ARGUMENTS: >- - --set fdr.image.tag="$(current_version)" - --set fdr.canaryDelivery.create="true" - --set fdr.forceRedeploy=${{ parameters.FORCE_REDEPLOY }} - --set fdr.canaryDelivery.ingress.weightPercent="${{ step }}" + --set pagopa-tech-support.image.tag="$(current_version)" + --set pagopa-tech-support.canaryDelivery.create="true" + --set pagopa-tech-support.forceRedeploy=${{ parameters.FORCE_REDEPLOY }} + --set pagopa-tech-support.canaryDelivery.ingress.weightPercent="${{ step }}" # Deploy stable - - stage: deploy_fdr_stable + - stage: deploy_pagopa_tech_support_stable displayName: "Deploy ${{ parameters.ENV }} stable" jobs: - job: get_release_version @@ -340,8 +333,8 @@ stages: #APPINSIGHTS_RESOURCE_ID: ${{ variables.WEU_appInsightsResourceId }} CHART_PATH: "helm" ARGUMENTS: >- - --set fdr.image.tag="$(current_version)" - --set fdr.forceRedeploy=${{ parameters.FORCE_REDEPLOY }} + --set pagopa-tech-support.image.tag="$(current_version)" + --set pagopa-tech-support.forceRedeploy=${{ parameters.FORCE_REDEPLOY }} - ${{ if in( parameters.ENV, 'prod', 'uat') }}: - bash: | @@ -394,5 +387,5 @@ stages: DEPLOY_VERSION: $(current_version) #APPINSIGHTS_SERVICE_CONN: ${{ variables.WEU_appInsightsServiceConn }} #APPINSIGHTS_RESOURCE_ID: ${{ variables.WEU_appInsightsResourceId }} - CHART_PATH: "helm/fdr" + CHART_PATH: "helm" ARGUMENTS: "$(appName)-canary" From 03dc0edc488a7968b333e6f5c80533695202a083 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Fri, 7 Jul 2023 08:41:53 +0200 Subject: [PATCH 11/29] wip --- .devops/deploy-pipelines.yml | 10 +- helm/Chart.yaml | 4 +- helm/weu-dev/values-dev.yaml | 9 +- pom.xml | 20 +-- .../nodetsworker/models/PaymentInfo.java | 3 +- .../nodetsworker/models/RPTAttemptInfo.java | 26 ---- .../repository/CosmosBizEventClient.java | 2 +- .../repository/CosmosNegBizEventClient.java | 2 +- .../repository/model/EventEntity.java | 50 +------ .../resources/WorkerResource.java | 10 +- .../exceptionmapper/ErrorResponse.java | 48 ------- .../exceptionmapper/ExceptionMappers.java | 136 ++++++------------ .../resources/filter/RequestFilter.java | 32 +++++ .../resources/filter/ResponseFilter.java | 33 +++++ .../nodetsworker/service/WorkerService.java | 38 +++-- .../nodetsworker/service/dto/EventDto.java | 86 +++++------ .../service/mapper/EventMapper.java | 36 ++--- .../it/gov/pagopa/nodetsworker/util/Util.java | 1 - src/main/resources/application.properties | 2 +- .../nodetsworker/resources/Sp03Test.java | 19 ++- .../nodetsworker/resources/Sp04Test.java | 4 + .../util/AppConstantTestHelper.java | 6 +- 22 files changed, 243 insertions(+), 334 deletions(-) delete mode 100644 src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java delete mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/filter/RequestFilter.java create mode 100644 src/main/java/it/gov/pagopa/nodetsworker/resources/filter/ResponseFilter.java diff --git a/.devops/deploy-pipelines.yml b/.devops/deploy-pipelines.yml index 6b33bd4..0f5eece 100644 --- a/.devops/deploy-pipelines.yml +++ b/.devops/deploy-pipelines.yml @@ -119,8 +119,6 @@ stages: buildname="$(Build.BuildNumber) ${{ parameters.ENV }}" echo "##vso[build.addbuildtag]${{ parameters.ENV }}" echo "##vso[build.updatebuildnumber]$buildname" - - bash: | - echo "##vso[task.setvariable variable=LIGHTBEND_KEY]$(lightbend_key_secret)" - checkout: self clean: true persistCredentials: true @@ -248,7 +246,7 @@ stages: DO_DEPLOY: true ENV: ${{ parameters['ENV'] }} KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} - NAMESPACE: "fdr" + NAMESPACE: $(nameSpace) APP_NAME: "$(appName)-canary" VALUE_FILE: $(WEU_value_file) DEPLOY_VERSION: $(current_version) @@ -325,7 +323,7 @@ stages: DO_DEPLOY: true ENV: ${{ parameters['ENV'] }} KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} - NAMESPACE: "fdr" + NAMESPACE: $(nameSpace) APP_NAME: $(appName) VALUE_FILE: $(WEU_value_file) DEPLOY_VERSION: $(current_version) @@ -345,7 +343,7 @@ stages: DO_DEPLOY: true ENV: ${{ parameters['ENV'] }} KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} - NAMESPACE: "fdr" + NAMESPACE: $(nameSpace) APP_NAME: "$(appName)-canary" VALUE_FILE: $(WEU_value_file) DEPLOY_VERSION: $(current_version) @@ -381,7 +379,7 @@ stages: DO_DEPLOY: true ENV: ${{ parameters['ENV'] }} KUBERNETES_SERVICE_CONN: ${{ variables.WEU_kubernetesServiceConnection }} - NAMESPACE: "fdr" + NAMESPACE: $(nameSpace) APP_NAME: "$(appName)-canary" VALUE_FILE: $(WEU_value_file) DEPLOY_VERSION: $(current_version) diff --git a/helm/Chart.yaml b/helm/Chart.yaml index 2814a30..57b9e21 100644 --- a/helm/Chart.yaml +++ b/helm/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 -name: pagopa-tech-support +name: pagopa-tech-support-api description: Technical support api type: application version: "0.0.0-SNAPSHOT" @@ -8,4 +8,4 @@ dependencies: - name: microservice-chart version: 3.0.0 repository: "https://pagopa.github.io/aks-microservice-chart-blueprint" - alias: pagopa-tech-support + alias: pagopa-tech-support-api diff --git a/helm/weu-dev/values-dev.yaml b/helm/weu-dev/values-dev.yaml index 439678d..4500603 100644 --- a/helm/weu-dev/values-dev.yaml +++ b/helm/weu-dev/values-dev.yaml @@ -1,4 +1,4 @@ -pagopa-tech-support: +pagopa-tech-support-api: namespace: "techsupport" image: repository: pagopadcommonacr.azurecr.io/pagopanodetechnicalsupportworker @@ -22,6 +22,8 @@ pagopa-tech-support: TZ: "Europe/Rome" OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" ADAPTER_API_CONFIG_CACHE_URL: "https://api.dev.platform.pagopa.it/api-config-cache/p/v1" + COSMOS_BIZ_ENDPOINT: + COSMOS_NEG_BIZ_ENDPOINT: envFieldRef: APP_NAME: "metadata.labels['app.kubernetes.io/instance']" APP_VERSION: "metadata.labels['app.kubernetes.io/version']" @@ -33,8 +35,11 @@ pagopa-tech-support: MONGODB_CONNECTION_STRING: "mongodb-connection-string" QUEUE_CONVERSION_CONNECTION_STRING: "azure-queue-conversion-connection-string" EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" + COSMOS_BIZ_KEY: "" + COSMOS_NEG_BIZ_KEY: "" + RE_TABLE_STORAGE_CONN_STRING: keyvault: - name: "pagopa-d-fdr-kv" + name: "pagopa-d-techsupportapi-kv" tenantId: "7788edaf-0346-4068-9d79-c868aed15b3d" tmpVolumeMount: create: true diff --git a/pom.xml b/pom.xml index add3fb6..7e30703 100644 --- a/pom.xml +++ b/pom.xml @@ -103,10 +103,10 @@ ${org.mapstruct.version} provided - - io.quarkus - quarkus-mongodb-panache - + + + + com.azure azure-cosmos @@ -132,12 +132,12 @@ 1.16.0 test - - org.testcontainers - mongodb - 1.18.1 - test - + + + + + + org.testcontainers azure diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java index d3c77df..cf080f1 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java @@ -13,6 +13,5 @@ @SuperBuilder public class PaymentInfo extends BasePaymentInfo { - private String - paymentToken; // for new payment model is payment token and for old payment model is ccp + private String paymentToken; // for new payment model is payment token and for old payment model is ccp } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java deleted file mode 100644 index 6c0547e..0000000 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/RPTAttemptInfo.java +++ /dev/null @@ -1,26 +0,0 @@ -package it.gov.pagopa.nodetsworker.models; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.experimental.SuperBuilder; - -@Getter -@Setter -@NoArgsConstructor -@AllArgsConstructor -@SuperBuilder -public class RPTAttemptInfo extends BasePaymentAttemptInfo { - - private String ccp; - private Long numberOfPayments; - private Boolean retriedRPT; - private Boolean isOldPaymentModel = true; - private Boolean wispInitialization; - private Boolean pmReceipt; - - @JsonProperty("iuv") - private String noticeNumber; -} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java index 6b68821..c57052c 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -7,10 +7,10 @@ import com.azure.cosmos.models.SqlParameter; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; +import io.quarkus.runtime.Startup; import it.gov.pagopa.nodetsworker.repository.model.Count; import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; import it.gov.pagopa.nodetsworker.util.Util; -import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.time.*; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java index af6bdec..c6581e1 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosNegBizEventClient.java @@ -7,9 +7,9 @@ import com.azure.cosmos.models.SqlParameter; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.util.CosmosPagedIterable; +import io.quarkus.runtime.Startup; import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; import it.gov.pagopa.nodetsworker.util.Util; -import jakarta.ejb.Startup; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.time.LocalDate; diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java index a51612c..cf8d717 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/model/EventEntity.java @@ -1,19 +1,13 @@ package it.gov.pagopa.nodetsworker.repository.model; -import io.quarkus.mongodb.panache.PanacheMongoEntity; -import io.quarkus.mongodb.panache.PanacheQuery; -import io.quarkus.mongodb.panache.common.MongoEntity; -import io.quarkus.panache.common.Parameters; -import java.time.LocalDate; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; @Data -@EqualsAndHashCode(callSuper = true) +@EqualsAndHashCode @Builder -@MongoEntity(collection = "events", clientName = "events") -public class EventEntity extends PanacheMongoEntity { +public class EventEntity { private String insertedTimestamp; private String componente; @@ -48,44 +42,4 @@ public class EventEntity extends PanacheMongoEntity { private String version; private Long timestamp; private String serviceIdentifier; - - public static PanacheQuery findByCIAndNAV( - String creditorInstitution, String nav, LocalDate dateFrom, LocalDate dateTo) { - return find( - "idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and" - + " status like 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("noticeNumber", nav)) - .project(EventEntity.class); - } - - public static PanacheQuery findByCIAndNAVAndToken( - String creditorInstitution, - String nav, - String paymentToken, - LocalDate dateFrom, - LocalDate dateTo) { - return find( - "idDominio = :idDominio and noticeNumber = :noticeNumber and esito = 'CAMBIO_STATO' and" - + " status like 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("noticeNumber", nav)) - .project(EventEntity.class); - } - - public static PanacheQuery findByCIAndIUV( - String creditorInstitution, String iuv, LocalDate dateFrom, LocalDate dateTo) { - return find( - "idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like" - + " 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("iuv", iuv)) - .project(EventEntity.class); - } - - public static PanacheQuery findByCIAndIUVAndCCP( - String creditorInstitution, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { - return find( - "idDominio = :idDominio and iuv = :iuv and esito = 'CAMBIO_STATO' and status like" - + " 'payment_'", - Parameters.with("idDominio", creditorInstitution).and("iuv", iuv)) - .project(EventEntity.class); - } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java index 52cafb5..1016011 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java @@ -21,10 +21,7 @@ public class WorkerResource implements Serializable { @Inject WorkerService workerService; - /** - * ###### ######## ##### ####### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ######## ## ## - * ####### ## ## ## ## ## ## ## ## ## ## ## ## ###### ## ##### ####### - */ + /** SP03 */ @APIResponses( value = { @APIResponse( @@ -97,10 +94,7 @@ public Response useCaseSP03_byIUV( .build(); } - /** - * ###### ######## ##### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ######## ## ## ## - * ## ## ## ## ## ######### ## ## ## ## ## ## ###### ## ##### ## - */ + /** SP04 */ @APIResponses( value = { @APIResponse( diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java deleted file mode 100644 index 63d6f21..0000000 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ErrorResponse.java +++ /dev/null @@ -1,48 +0,0 @@ -package it.gov.pagopa.nodetsworker.resources.exceptionmapper; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import io.quarkus.runtime.annotations.RegisterForReflection; -import java.util.List; -import lombok.*; -import lombok.extern.jackson.Jacksonized; -import org.eclipse.microprofile.openapi.annotations.media.Schema; - -@Getter -@Builder -@Jacksonized -@JsonPropertyOrder({"errorId", "httpStatusCode", "httpStatusDescription", "appErrorCode", "errors"}) -@RegisterForReflection -public class ErrorResponse { - - @JsonInclude(JsonInclude.Include.NON_NULL) - @Schema(example = "50905466-1881-457b-b42f-fb7b2bfb1610") - private String errorId; - - @Schema(example = "500") - private int httpStatusCode; - - @Schema(example = "Internal Server Error") - private String httpStatusDescription; - - @Schema(example = "FDR-500") - private String appErrorCode; - - private List errors; - - @Builder - @Data - @AllArgsConstructor - @NoArgsConstructor - @JsonPropertyOrder({"path", "message"}) - @RegisterForReflection - public static class ErrorMessage { - - @Schema(example = "demo.test") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String path; - - @Schema(example = "An unexpected error has occurred. Please contact support.") - private String message; - } -} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java index 3d64e7d..f7f21f7 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/exceptionmapper/ExceptionMappers.java @@ -8,7 +8,7 @@ import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageEnum; import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageInterface; import it.gov.pagopa.nodetsworker.exceptions.AppException; -import it.gov.pagopa.nodetsworker.util.AppMessageUtil; +import it.gov.pagopa.nodetsworker.models.ProblemJson; import jakarta.inject.Inject; import jakarta.validation.ConstraintViolationException; import jakarta.validation.UnexpectedTypeException; @@ -23,9 +23,6 @@ import org.jboss.resteasy.reactive.RestResponse; import org.jboss.resteasy.reactive.server.ServerExceptionMapper; -// import static it.gov.pagopa.fdr.util.AppMessageUtil.logErrorMessage; -// import static it.gov.pagopa.fdr.util.MDCKeys.TRX_ID; - public class ExceptionMappers { @Inject Logger log; @@ -43,23 +40,22 @@ public Response mapWebApplicationException(WebApplicationException webApplicatio } @ServerExceptionMapper - public RestResponse mapAppException(AppException appEx) { + public RestResponse mapAppException(AppException appEx) { AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); RestResponse.Status status = codeMessage.httpStatus(); String message = codeMessage.message(appEx.getArgs()); - ErrorResponse errorResponse = - ErrorResponse.builder() - .httpStatusCode(status.getStatusCode()) - .httpStatusDescription(status.getReasonPhrase()) - .appErrorCode(codeMessage.errorCode()) - .errors(List.of(ErrorResponse.ErrorMessage.builder().message(message).build())) + ProblemJson errorResponse = + ProblemJson.builder() + .status(status.getStatusCode()) + .details(codeMessage.message(appEx.getArgs())) + .title(codeMessage.errorCode()) .build(); return RestResponse.status(codeMessage.httpStatus(), errorResponse); } - private RestResponse mapJsonMappingException( + private RestResponse mapJsonMappingException( JsonMappingException jsonMappingException) { // quando jackson riesce a parsare il messaggio perchè non formato json valido AppException appEx = @@ -69,22 +65,17 @@ private RestResponse mapJsonMappingException( AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); RestResponse.Status status = codeMessage.httpStatus(); - ErrorResponse errorResponse = - ErrorResponse.builder() - .httpStatusCode(status.getStatusCode()) - .httpStatusDescription(status.getReasonPhrase()) - .appErrorCode(codeMessage.errorCode()) - .errors( - List.of( - ErrorResponse.ErrorMessage.builder() - .message(codeMessage.message(appEx.getArgs())) - .build())) + ProblemJson errorResponse = + ProblemJson.builder() + .status(status.getStatusCode()) + .details(codeMessage.message(appEx.getArgs())) + .title(codeMessage.errorCode()) .build(); return RestResponse.status(codeMessage.httpStatus(), errorResponse); } - private RestResponse mapJsonParseException(JsonParseException jsonParseException) { + private RestResponse mapJsonParseException(JsonParseException jsonParseException) { // quando jackson riesce a parsare il messaggio perchè non formato json valido AppException appEx = @@ -94,16 +85,11 @@ private RestResponse mapJsonParseException(JsonParseException jso AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); RestResponse.Status status = codeMessage.httpStatus(); - ErrorResponse errorResponse = - ErrorResponse.builder() - .httpStatusCode(status.getStatusCode()) - .httpStatusDescription(status.getReasonPhrase()) - .appErrorCode(codeMessage.errorCode()) - .errors( - List.of( - ErrorResponse.ErrorMessage.builder() - .message(codeMessage.message(appEx.getArgs())) - .build())) + ProblemJson errorResponse = + ProblemJson.builder() + .status(status.getStatusCode()) + .details(codeMessage.message(appEx.getArgs())) + .title(codeMessage.errorCode()) .build(); return RestResponse.status(codeMessage.httpStatus(), errorResponse); @@ -111,7 +97,7 @@ private RestResponse mapJsonParseException(JsonParseException jso @SuppressWarnings("unchecked") @ServerExceptionMapper - public RestResponse mapInvalidFormatException( + public RestResponse mapInvalidFormatException( InvalidFormatException invalidFormatException) { // quando jackson riesce a parsare il messaggio per popolare il bean ma i valori NON sono // corretti @@ -162,23 +148,18 @@ public RestResponse mapInvalidFormatException( AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); RestResponse.Status status = codeMessage.httpStatus(); - ErrorResponse errorResponse = - ErrorResponse.builder() - .httpStatusCode(status.getStatusCode()) - .httpStatusDescription(status.getReasonPhrase()) - .appErrorCode(codeMessage.errorCode()) - .errors( - List.of( - ErrorResponse.ErrorMessage.builder() - .message(codeMessage.message(appEx.getArgs())) - .build())) + ProblemJson errorResponse = + ProblemJson.builder() + .status(status.getStatusCode()) + .details(codeMessage.message(appEx.getArgs())) + .title(codeMessage.errorCode()) .build(); return RestResponse.status(codeMessage.httpStatus(), errorResponse); } @ServerExceptionMapper - public RestResponse mapMismatchedInputException( + public RestResponse mapMismatchedInputException( MismatchedInputException mismatchedInputException) { // quando jackson NON riesce a parsare il messaggio per popolare il bean String field = @@ -195,53 +176,39 @@ public RestResponse mapMismatchedInputException( AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); RestResponse.Status status = codeMessage.httpStatus(); - ErrorResponse errorResponse = - ErrorResponse.builder() - .httpStatusCode(status.getStatusCode()) - .httpStatusDescription(status.getReasonPhrase()) - .appErrorCode(codeMessage.errorCode()) - .errors( - List.of( - ErrorResponse.ErrorMessage.builder() - .message(codeMessage.message(appEx.getArgs())) - .build())) + ProblemJson errorResponse = + ProblemJson.builder() + .status(status.getStatusCode()) + .details(codeMessage.message(appEx.getArgs())) + .title(codeMessage.errorCode()) .build(); return RestResponse.status(codeMessage.httpStatus(), errorResponse); } @ServerExceptionMapper - public RestResponse mapUnexpectedTypeException(UnexpectedTypeException exception) { + public RestResponse mapUnexpectedTypeException(UnexpectedTypeException exception) { return mapThrowable(exception); } @ServerExceptionMapper - public RestResponse mapThrowable(Throwable exception) { - // String errorId = MDC.get(TRX_ID); - // log.errorf(logErrorMessage(exception.getMessage())); - + public RestResponse mapThrowable(Throwable exception) { AppException appEx = new AppException(exception, AppErrorCodeMessageEnum.ERROR); AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); RestResponse.Status status = codeMessage.httpStatus(); - ErrorResponse errorResponse = - ErrorResponse.builder() - // .errorId(errorId) - .httpStatusCode(status.getStatusCode()) - .httpStatusDescription(status.getReasonPhrase()) - .appErrorCode(codeMessage.errorCode()) - .errors( - List.of( - ErrorResponse.ErrorMessage.builder() - .message(codeMessage.message(appEx.getArgs())) - .build())) + ProblemJson errorResponse = + ProblemJson.builder() + .status(status.getStatusCode()) + .details(codeMessage.message(appEx.getArgs())) + .title(codeMessage.errorCode()) .build(); return RestResponse.status(codeMessage.httpStatus(), errorResponse); } @ServerExceptionMapper - public RestResponse mapConstraintViolationException( + public RestResponse mapConstraintViolationException( ConstraintViolationException constraintViolationException) { AppException appEx = @@ -249,26 +216,11 @@ public RestResponse mapConstraintViolationException( AppErrorCodeMessageInterface codeMessage = appEx.getCodeMessage(); RestResponse.Status status = codeMessage.httpStatus(); - ErrorResponse errorResponse = - ErrorResponse.builder() - .httpStatusCode(status.getStatusCode()) - .httpStatusDescription(status.getReasonPhrase()) - .appErrorCode(codeMessage.errorCode()) - .errors( - constraintViolationException.getConstraintViolations().stream() - .sorted( - (a, b) -> - b.getPropertyPath() - .toString() - .compareTo(a.getPropertyPath().toString())) - .map( - constraintViolation -> - ErrorResponse.ErrorMessage.builder() - .path(constraintViolation.getPropertyPath().toString()) - .message( - AppMessageUtil.getMessage(constraintViolation.getMessage())) - .build()) - .toList()) + ProblemJson errorResponse = + ProblemJson.builder() + .status(status.getStatusCode()) + .details(codeMessage.message(appEx.getArgs())) + .title(codeMessage.errorCode()) .build(); return RestResponse.status(codeMessage.httpStatus(), errorResponse); diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/filter/RequestFilter.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/filter/RequestFilter.java new file mode 100644 index 0000000..244ae2a --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/filter/RequestFilter.java @@ -0,0 +1,32 @@ +package it.gov.pagopa.nodetsworker.resources.filter; + +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.ext.Provider; +import java.io.IOException; +import java.util.UUID; +import org.jboss.logging.Logger; + +@Provider +public class RequestFilter implements ContainerRequestFilter { + + @Inject Logger log; + + @Override + public void filter(ContainerRequestContext containerRequestContext) throws IOException { + long requestStartTime = System.nanoTime(); + containerRequestContext.setProperty("requestStartTime", requestStartTime); + + String sessionId = UUID.randomUUID().toString(); + + String requestMethod = containerRequestContext.getMethod(); + String requestPath = containerRequestContext.getUriInfo().getPath(); + + MultivaluedMap queryParameters = + containerRequestContext.getUriInfo().getQueryParameters(); + + log.infof("REQ --> %s [uri:%s] [params:%s]", requestMethod, requestPath, queryParameters); + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/filter/ResponseFilter.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/filter/ResponseFilter.java new file mode 100644 index 0000000..3d24254 --- /dev/null +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/filter/ResponseFilter.java @@ -0,0 +1,33 @@ +package it.gov.pagopa.nodetsworker.resources.filter; + +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerResponseContext; +import jakarta.ws.rs.container.ContainerResponseFilter; +import jakarta.ws.rs.ext.Provider; +import java.util.concurrent.TimeUnit; +import org.jboss.logging.Logger; +import org.slf4j.MDC; + +@Provider +public class ResponseFilter implements ContainerResponseFilter { + + @Inject Logger log; + + @Override + public void filter( + ContainerRequestContext requestContext, ContainerResponseContext responseContext) { + if (requestContext.getPropertyNames().contains("requestStartTime")) { + long requestStartTime = (long) requestContext.getProperty("requestStartTime"); + long requestFinishTime = System.nanoTime(); + long elapsed = TimeUnit.NANOSECONDS.toMillis(requestFinishTime - requestStartTime); + String requestPath = requestContext.getUriInfo().getAbsolutePath().getPath(); + String requestMethod = requestContext.getMethod(); + int httpStatus = responseContext.getStatus(); + log.infof( + "RES --> %s [uri:%s] [elapsed:%dms] [statusCode:%d]", + requestMethod, requestPath, elapsed, httpStatus); + MDC.clear(); + } + } +} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index d488588..bcc63b4 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -15,7 +15,7 @@ import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; -import it.gov.pagopa.nodetsworker.service.mapper.EventMapper; +//import it.gov.pagopa.nodetsworker.service.mapper.EventMapper; import it.gov.pagopa.nodetsworker.util.StatusUtil; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -38,7 +38,7 @@ public class WorkerService { @Inject Config configObject; - @Inject EventMapper eventsMapper; +// @Inject EventMapper eventsMapper; @Inject CosmosBizEventClient positiveBizClient; @Inject CosmosNegBizEventClient negativeBizClient; @@ -56,7 +56,7 @@ private PaymentInfo eventToPaymentInfo(ConfigDataV1 config, EventEntity ee) { .channelId(ee.getCanale()) .brokerPspId(brokerid) .insertedTimestamp(ee.getInsertedTimestamp()) - .paymentToken(ee.getPaymentToken()) + .paymentToken(ee.getPaymentToken()!=null?ee.getPaymentToken():ee.getCcp()) .noticeNumber(ee.getNoticeNumber()) .iuv(ee.getIuv()) .organizationFiscalCode(ee.getIdDominio()) @@ -75,8 +75,8 @@ private PaymentAttemptInfo eventToPaymentAttemptInfo(ConfigDataV1 config, EventE .channelId(ee.getCanale()) .brokerPspId(brokerid) .insertedTimestamp(ee.getInsertedTimestamp()) - .paymentToken(ee.getPaymentToken()) .noticeNumber(ee.getNoticeNumber()) + .paymentToken(ee.getPaymentToken()!=null?ee.getPaymentToken():ee.getCcp()) .iuv(ee.getIuv()) .organizationFiscalCode(ee.getIdDominio()) .status(StatusUtil.statoByReStatus(ee.getStatus())) @@ -118,6 +118,7 @@ private void enrichPaymentAttemptInfo( if (pai.getBrokerPspId() == null) { pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); } + pai.setPaymentToken(nbe.getPaymentInfo().getPaymentToken()); pai.setStationVersion(stationVersion); pai.setAmount(nbe.getPaymentInfo().getAmount()); pai.setPaymentMethod(nbe.getPaymentInfo().getPaymentMethod()); @@ -128,10 +129,6 @@ private void enrichPaymentAttemptInfo( public TransactionResponse getInfoByNoticeNumber( String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo) { - log.infof( - "getInfoByNoticeNumber %s,%s,%s,%s", - organizationFiscalCode, noticeNumber, dateFrom, dateTo); - DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = @@ -193,8 +190,6 @@ public TransactionResponse getInfoByNoticeNumber( public TransactionResponse getInfoByIUV( String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo) { - log.infof("getInfoByIUV %s,%s,%s,%s", organizationFiscalCode, iuv, dateFrom, dateTo); - DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = @@ -248,8 +243,8 @@ public TransactionResponse getInfoByIUV( .collect(Collectors.toList()); return TransactionResponse.builder() - .dateFrom(dateFrom) - .dateTo(dateTo) + .dateFrom(dateRequest.getFrom()) + .dateTo(dateRequest.getTo()) .payments(collect) .build(); } @@ -261,10 +256,6 @@ public TransactionResponse getAttemptByNoticeNumberAndPaymentToken( LocalDate dateFrom, LocalDate dateTo) { - log.infof( - "getInfoByNoticeNumberAndPaymentToken %s,%s,%s,%s,%s", - organizationFiscalCode, noticeNumber, paymentToken, dateFrom, dateTo); - DateRequest dateRequest = verifyDate(dateFrom, dateTo); List events = reTableService.findReByCiAndNNAndToken( @@ -313,15 +304,16 @@ public TransactionResponse getAttemptByNoticeNumberAndPaymentToken( pais.add(pai); } - return TransactionResponse.builder().dateFrom(dateFrom).dateTo(dateTo).payments(pais).build(); + return TransactionResponse.builder() + .dateFrom(dateRequest.getFrom()) + .dateTo(dateRequest.getTo()) + .payments(pais) + .build(); } public TransactionResponse getAttemptByIUVAndCCP( String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { - log.infof( - "getAttemptByIUVAndCCP %s,%s,%s,%s,%s", organizationFiscalCode, iuv, ccp, dateFrom, dateTo); - DateRequest dateRequest = verifyDate(dateFrom, dateTo); ConfigDataV1 config = configObject.getClonedCache(); List events = @@ -359,7 +351,11 @@ public TransactionResponse getAttemptByIUVAndCCP( pais.add(pai); } - return TransactionResponse.builder().dateFrom(dateFrom).dateTo(dateTo).payments(pais).build(); + return TransactionResponse.builder() + .dateFrom(dateRequest.getFrom()) + .dateTo(dateRequest.getTo()) + .payments(pais) + .build(); } /** diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java b/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java index a85a740..1356984 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/dto/EventDto.java @@ -1,43 +1,43 @@ -package it.gov.pagopa.nodetsworker.service.dto; - -import lombok.Data; -import lombok.EqualsAndHashCode; - -@Data -@EqualsAndHashCode -public class EventDto { - - private String insertedTimestamp; - private String componente; - private String categoriaEvento; - private String sottoTipoEvento; - private String idDominio; - private String iuv; - private String ccp; - private String psp; - private String tipoVersamento; - private String tipoEvento; - private String fruitore; - private String erogatore; - private String stazione; - private String canale; - private String parametriSpecificiInterfaccia; - private String esito; - private String sessionId; - private String status; - private String payload; - private String info; - private String businessProcess; - private String fruitoreDescr; - private String erogatoreDescr; - private String pspDescr; - private String noticeNumber; - private String creditorReferenceId; - private String paymentToken; - private String sessionIdOriginal; - private String dataOraEvento; - private String uniqueId; - private String version; - private Long timestamp; - private String serviceIdentifier; -} +//package it.gov.pagopa.nodetsworker.service.dto; +// +//import lombok.Data; +//import lombok.EqualsAndHashCode; +// +//@Data +//@EqualsAndHashCode +//public class EventDto { +// +// private String insertedTimestamp; +// private String componente; +// private String categoriaEvento; +// private String sottoTipoEvento; +// private String idDominio; +// private String iuv; +// private String ccp; +// private String psp; +// private String tipoVersamento; +// private String tipoEvento; +// private String fruitore; +// private String erogatore; +// private String stazione; +// private String canale; +// private String parametriSpecificiInterfaccia; +// private String esito; +// private String sessionId; +// private String status; +// private String payload; +// private String info; +// private String businessProcess; +// private String fruitoreDescr; +// private String erogatoreDescr; +// private String pspDescr; +// private String noticeNumber; +// private String creditorReferenceId; +// private String paymentToken; +// private String sessionIdOriginal; +// private String dataOraEvento; +// private String uniqueId; +// private String version; +// private Long timestamp; +// private String serviceIdentifier; +//} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java index 6761296..06d1823 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/mapper/EventMapper.java @@ -1,18 +1,18 @@ -package it.gov.pagopa.nodetsworker.service.mapper; - -import it.gov.pagopa.nodetsworker.repository.model.EventEntity; -import it.gov.pagopa.nodetsworker.service.dto.EventDto; -import java.util.List; -import org.mapstruct.Mapper; -import org.mapstruct.MappingConstants.ComponentModel; -import org.mapstruct.factory.Mappers; - -@Mapper(componentModel = ComponentModel.JAKARTA) -public interface EventMapper { - - EventMapper INSTANCE = Mappers.getMapper(EventMapper.class); - - EventDto map(EventEntity entity); - - List map(List entities); -} +//package it.gov.pagopa.nodetsworker.service.mapper; +// +//import it.gov.pagopa.nodetsworker.repository.model.EventEntity; +//import it.gov.pagopa.nodetsworker.service.dto.EventDto; +//import java.util.List; +//import org.mapstruct.Mapper; +//import org.mapstruct.MappingConstants.ComponentModel; +//import org.mapstruct.factory.Mappers; +// +//@Mapper(componentModel = ComponentModel.JAKARTA) +//public interface EventMapper { +// +// EventMapper INSTANCE = Mappers.getMapper(EventMapper.class); +// +// EventDto map(EventEntity entity); +// +// List map(List entities); +//} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java index f516b91..052fc15 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/util/Util.java @@ -1,6 +1,5 @@ package it.gov.pagopa.nodetsworker.util; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 102cd5a..add7988 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -120,4 +120,4 @@ operations.filter=".*" quarkus.test.continuous-testing=disabled -quarkus.http.test-port=8083 \ No newline at end of file +quarkus.http.test-port=8083 diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java index ebf7e1b..5e3422b 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java @@ -15,7 +15,10 @@ import io.quarkiverse.mockserver.test.MockServerTestResource; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; import io.restassured.common.mapper.TypeRef; +import io.restassured.filter.log.RequestLoggingFilter; +import io.restassured.filter.log.ResponseLoggingFilter; import it.gov.pagopa.nodetsworker.models.PaymentInfo; import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; @@ -218,7 +221,7 @@ void test4() { @Test @DisplayName("dateFrom 400") void test5() { - String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String iuv = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_IUV.formatted(PA_CODE, iuv); given().param("dateFrom", Util.format(LocalDate.now())).when().get(url).then().statusCode(400); @@ -228,9 +231,21 @@ void test5() { @Test @DisplayName("dateTo 400") void test6() { - String iuv = String.valueOf(new Random().nextLong(11111111111l, 99999999999l)); + String iuv = String.valueOf(Instant.now().toEpochMilli()); String url = SP03_IUV.formatted(PA_CODE, iuv); given().param("dateTo", Util.format(LocalDate.now())).when().get(url).then().statusCode(400); } + + @SneakyThrows + @Test + @DisplayName("bad date 400") + void test7() { + String iuv = String.valueOf(Instant.now().toEpochMilli()); + String url = SP03_IUV.formatted(PA_CODE, iuv); + + RestAssured.filters(new RequestLoggingFilter(), new ResponseLoggingFilter()); + + given().param("dateTo", "aaa").when().get(url).then().statusCode(404); + } } diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java index 9f72bed..334a2c2 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java @@ -108,6 +108,7 @@ void test1() { assertThat(o.getPspId(), equalTo("pspTest")); assertThat(o.getChannelId(), equalTo("canaleTest")); assertThat(o.getBrokerPspId(), equalTo("intTest")); + assertThat(o.getPaymentToken(), equalTo(token)); } @SneakyThrows @@ -144,6 +145,7 @@ void test2() { assertThat(o.getPspId(), equalTo("pspTest")); assertThat(o.getChannelId(), equalTo("canaleTest")); assertThat(o.getBrokerPspId(), equalTo("intTest")); + assertThat(o.getPaymentToken(), equalTo(token)); } @SneakyThrows @@ -180,6 +182,7 @@ void test3() { assertThat(o.getPspId(), equalTo("pspTest")); assertThat(o.getChannelId(), equalTo("canaleTest")); assertThat(o.getBrokerPspId(), equalTo("intTest")); + assertThat(o.getPaymentToken(), equalTo(ccp)); } @SneakyThrows @@ -216,6 +219,7 @@ void test4() { assertThat(o.getPspId(), equalTo("pspTest")); assertThat(o.getChannelId(), equalTo("canaleTest")); assertThat(o.getBrokerPspId(), equalTo("intTest")); + assertThat(o.getPaymentToken(), equalTo(ccp)); } @SneakyThrows diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java index 4133476..43f454c 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java @@ -31,8 +31,10 @@ public static final TableEntity newRe(String pa, String noticeNumber, String iuv entity.addProperty("noticeNumber", noticeNumber); entity.addProperty("iuv", iuv); entity.addProperty("esito", "CAMBIO_STATO"); - entity.addProperty("paymentToken", "pt_" + noticeNumber); - entity.addProperty("ccp", "ccp_" + iuv); + if(noticeNumber!=null) + entity.addProperty("paymentToken", "pt_" + noticeNumber); + if(iuv!=null) + entity.addProperty("ccp", "ccp_" + iuv); entity.addProperty("stazione", "77777777777_01"); entity.addProperty("psp", "pspTest"); entity.addProperty("canale", "canaleTest"); From d0c1569a7d70b37274d14d5044f7d2e99baf9318 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Fri, 7 Jul 2023 08:52:37 +0200 Subject: [PATCH 12/29] wip --- helm/weu-dev/values-dev.yaml | 15 ++++++--------- src/main/resources/application.properties | 16 +++++++--------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/helm/weu-dev/values-dev.yaml b/helm/weu-dev/values-dev.yaml index 4500603..f118c0a 100644 --- a/helm/weu-dev/values-dev.yaml +++ b/helm/weu-dev/values-dev.yaml @@ -22,8 +22,8 @@ pagopa-tech-support-api: TZ: "Europe/Rome" OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" ADAPTER_API_CONFIG_CACHE_URL: "https://api.dev.platform.pagopa.it/api-config-cache/p/v1" - COSMOS_BIZ_ENDPOINT: - COSMOS_NEG_BIZ_ENDPOINT: + COSMOS_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-ds-cosmos-account.documents.azure.com:443/" + COSMOS_NEG_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/" envFieldRef: APP_NAME: "metadata.labels['app.kubernetes.io/instance']" APP_VERSION: "metadata.labels['app.kubernetes.io/version']" @@ -31,15 +31,12 @@ pagopa-tech-support-api: create: true envSecrets: ADAPTER_API_CONFIG_CACHE_API_KEY: "api-config-cache-subscription-key-string" - OTEL_AUTH_BEARER: "otel-auth-bearer" - MONGODB_CONNECTION_STRING: "mongodb-connection-string" - QUEUE_CONVERSION_CONNECTION_STRING: "azure-queue-conversion-connection-string" EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" - COSMOS_BIZ_KEY: "" - COSMOS_NEG_BIZ_KEY: "" - RE_TABLE_STORAGE_CONN_STRING: + COSMOS_BIZ_KEY: "cosmos-biz-account-key" + COSMOS_NEG_BIZ_KEY: "cosmos-neg-biz-account-key" + RE_TABLE_STORAGE_CONN_STRING: "re-datastore-connection-string" keyvault: - name: "pagopa-d-techsupportapi-kv" + name: "pagopa-d-nodo-kv" tenantId: "7788edaf-0346-4068-9d79-c868aed15b3d" tmpVolumeMount: create: true diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index add7988..e863f13 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -37,8 +37,8 @@ quarkus.otel.enabled=false %dev.quarkus.otel.enabled=false %test.quarkus.otel.enabled=false %openapi.quarkus.otel.enabled=false -quarkus.otel.exporter.otlp.traces.endpoint=${OTEL_ENDPOINT} -quarkus.otel.exporter.otlp.traces.headers=${OTEL_AUTH_BEARER} +quarkus.otel.exporter.otlp.traces.endpoint=${OTEL_ENDPOINT:http://localhost:4317} +quarkus.otel.exporter.otlp.traces.headers=${OTEL_AUTH_BEARER:Authorization=Bearer my-token} %dev.quarkus.otel.exporter.otlp.traces.endpoint=http://localhost:4317 %dev.quarkus.otel.exporter.otlp.traces.headers=Authorization=Bearer my-token %test.quarkus.otel.exporter.otlp.traces.endpoint=http://localhost:4317 @@ -61,10 +61,10 @@ quarkus.smallrye-openapi.servers=\\$\{host\}/tenchinal-support/api/v1 - APIM ## DATABASE ################### -%test.quarkus.mongodb.connection-string=${mockserver.mongodb.connection-string} - -quarkus.mongodb.events.connection-string=${MONGODB_EVENTS_CONNECTION_STRING} -quarkus.mongodb.events.database=nodo_re +#%test.quarkus.mongodb.connection-string=${mockserver.mongodb.connection-string} +# +#quarkus.mongodb.events.connection-string=${MONGODB_EVENTS_CONNECTION_STRING} +#quarkus.mongodb.events.database=nodo_re biz.endpoint=${COSMOS_BIZ_ENDPOINT:${mockserver.biz.endpoint}} biz.key=${COSMOS_BIZ_KEY:${mockserver.biz.key}} @@ -118,6 +118,4 @@ operations.filter=".*" %test.quarkus.mockserver.devservices.log=false quarkus.test.continuous-testing=disabled - - -quarkus.http.test-port=8083 +quarkus.http.test-port=8083 \ No newline at end of file From e5053d7c4c6a2f43f2a6e6ee83d5e07ef7924023 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Fri, 7 Jul 2023 11:11:11 +0200 Subject: [PATCH 13/29] wip --- .../workflows/deploy_with_github_runner.yml | 126 ++++++++++++++++++ .github/workflows/release_deploy.yml | 102 +++++++------- 2 files changed, 174 insertions(+), 54 deletions(-) create mode 100644 .github/workflows/deploy_with_github_runner.yml diff --git a/.github/workflows/deploy_with_github_runner.yml b/.github/workflows/deploy_with_github_runner.yml new file mode 100644 index 0000000..fd1b2ef --- /dev/null +++ b/.github/workflows/deploy_with_github_runner.yml @@ -0,0 +1,126 @@ +name: Deploy on AKS + +on: + workflow_call: + inputs: + environment: + required: true + description: The name of the environment where to deploy + type: string + target: + required: true + description: The environment target of the job + type: string + +env: + APP_NAME: # TODO + + +permissions: + id-token: write + contents: read + +jobs: + create_runner: + name: Create Runner + runs-on: ubuntu-22.04 + environment: + name: ${{ inputs.environment }} + if: ${{ inputs.target == inputs.environment || inputs.target == 'all' }} + outputs: + runner_name: ${{ steps.create_github_runner.outputs.runner_name }} + steps: + - name: Create GitHub Runner + id: create_github_runner + # from https://github.com/pagopa/eng-github-actions-iac-template/tree/main/azure/github-self-hosted-runner-azure-create-action + uses: pagopa/eng-github-actions-iac-template/azure/github-self-hosted-runner-azure-create-action@main + with: + client_id: ${{ secrets.CLIENT_ID }} + tenant_id: ${{ secrets.TENANT_ID }} + subscription_id: ${{ secrets.SUBSCRIPTION_ID }} + container_app_environment_name: ${{ vars.CONTAINER_APP_ENVIRONMENT_NAME }} + resource_group_name: ${{ vars.CONTAINER_APP_ENVIRONMENT_RESOURCE_GROUP_NAME }} # RG of the runner + pat_token: ${{ secrets.BOT_TOKEN_GITHUB }} + self_hosted_runner_image_tag: "v1.4.1" + + deploy: + needs: [ create_runner ] + runs-on: [ self-hosted, "${{ needs.create_runner.outputs.runner_name }}" ] + if: ${{ inputs.target == inputs.environment || inputs.target == 'all' }} + name: Deploy on AKS + environment: ${{ inputs.environment }} + steps: + - name: Deploy + uses: pagopa/github-actions-template/aks-deploy@main + with: + branch: ${{ github.ref_name }} + client_id: ${{ secrets.CLIENT_ID }} + subscription_id: ${{ secrets.SUBSCRIPTION_ID }} + tenant_id: ${{ secrets.TENANT_ID }} + env: ${{ inputs.environment }} + namespace: ${{ vars.NAMESPACE }} + cluster_name: ${{ vars.CLUSTER_NAME }} + resource_group: ${{ vars.CLUSTER_RESOURCE_GROUP }} + app_name: ${{ env.APP_NAME }} + helm_upgrade_options: "--debug" + + cleanup_runner: + name: Cleanup Runner + needs: [ create_runner, deploy ] + if: ${{ success() || failure() && inputs.target == inputs.environment || inputs.target == 'all' }} + runs-on: ubuntu-22.04 + environment: ${{ inputs.environment }} + steps: + - name: Cleanup GitHub Runner + id: cleanup_github_runner + # from https://github.com/pagopa/eng-github-actions-iac-template/tree/main/azure/github-self-hosted-runner-azure-cleanup-action + uses: pagopa/eng-github-actions-iac-template/azure/github-self-hosted-runner-azure-cleanup-action@0ee2f58fd46d10ac7f00bce4304b98db3dbdbe9a + with: + client_id: ${{ secrets.CLIENT_ID }} + tenant_id: ${{ secrets.TENANT_ID }} + subscription_id: ${{ secrets.SUBSCRIPTION_ID }} + resource_group_name: ${{ vars.CONTAINER_APP_ENVIRONMENT_RESOURCE_GROUP_NAME }} + runner_name: ${{ needs.create_runner.outputs.runner_name }} + pat_token: ${{ secrets.BOT_TOKEN_GITHUB }} + + update_openapi: + needs: [ deploy ] + runs-on: ubuntu-latest + name: Update OpenAPI + if: ${{ inputs.target == inputs.environment || inputs.target == 'all' }} + environment: ${{ inputs.environment }} + steps: + - name: Checkout + id: checkout + # from https://github.com/actions/checkout/commits/main + uses: actions/checkout@1f9a0c22da41e6ebfa534300ef656657ea2c6707 + with: + persist-credentials: false + + - name: Setup Terraform + # from https://github.com/hashicorp/setup-terraform/commits/main + uses: hashicorp/setup-terraform@8feba2b913ea459066180f9cb177f58a881cf146 + with: + terraform_version: "1.3.6" + + - name: Login + id: login + # from https://github.com/Azure/login/commits/master + uses: azure/login@92a5484dfaf04ca78a94597f4f19fea633851fa2 + with: + client-id: ${{ secrets.CLIENT_ID }} + tenant-id: ${{ secrets.TENANT_ID }} + subscription-id: ${{ secrets.SUBSCRIPTION_ID }} + + + - name: Terraform Apply + shell: bash + run: | + cd ./infra + export ARM_CLIENT_ID="${{ secrets.CLIENT_ID }}" + export ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) + export ARM_TENANT_ID=$(az account show --query tenantId --output tsv) + export ARM_USE_OIDC=true + export ARM_ACCESS_KEY=$(az storage account keys list --resource-group io-infra-rg --account-name pagopainfraterraform${{inputs.environment}} --query '[0].value' -o tsv) + bash ./terraform.sh init weu-${{ inputs.environment }} + bash ./terraform.sh apply weu-${{ inputs.environment }} -auto-approve diff --git a/.github/workflows/release_deploy.yml b/.github/workflows/release_deploy.yml index 2684f4e..577eef3 100644 --- a/.github/workflows/release_deploy.yml +++ b/.github/workflows/release_deploy.yml @@ -3,8 +3,6 @@ name: Release And Deploy # Controls when the workflow will run on: pull_request: - branches: - - main types: [ closed ] # Allows you to run this workflow manually from the Actions tab @@ -19,37 +17,18 @@ on: - uat - prod - all - semver: - required: true - type: choice - description: Select the new Semantic Version - options: - - major - - minor - - patch - - buildNumber - - skip - default: skip beta: required: false type: boolean description: deploy beta version on AKS default: false - workflow_call: - inputs: - environment: - required: true - type: string - semver: - required: true - type: string - default: skip - beta: + skip_release: required: false type: boolean - description: deploy beta version on AKS + description: skip the release. Only deploy default: false + permissions: packages: write contents: write @@ -65,28 +44,45 @@ jobs: runs-on: ubuntu-latest outputs: semver: ${{ steps.get_semver.outputs.semver }} - environment: ${{ steps.output.outputs.environment }} + environment: ${{ steps.get_env.outputs.environment }} steps: - - name: Get semver - id: get_semver - uses: pagopa/github-actions-template/semver-setup@1.3.0 + - name: pull request rejected + if: github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.merged != true + run: | + echo "❌ PR was closed without a merge" + exit 1 - - if: ${{ github.event.inputs.environment == null || github.event.inputs.environment == 'dev' }} - run: echo "ENVIRNOMENT=dev" >> $GITHUB_ENV + # Set Semvar + - run: echo "SEMVER=patch" >> $GITHUB_ENV + + - if: ${{ (github.event.pull_request.merged && contains(github.event.pull_request.labels.*.name, 'breaking-change')) }} + run: echo "SEMVER=major" >> $GITHUB_ENV + + - if: ${{ inputs.environment == 'uat' }} + run: echo "SEMVER=minor" >> $GITHUB_ENV - - if: ${{ github.event.inputs.environment == 'uat' }} - run: echo "ENVIRNOMENT=uat" >> $GITHUB_ENV + - if: ${{ inputs.environment == 'prod' }} + run: echo "SEMVER=skip" >> $GITHUB_ENV - - if: ${{ github.event.inputs.environment == 'prod' }} - run: echo "ENVIRNOMENT=prod" >> $GITHUB_ENV + - if: ${{ github.ref_name != 'main' }} + run: echo "SEMVER=buildNumber" >> $GITHUB_ENV - - if: ${{ github.event.inputs.environment == 'all' }} - run: echo "ENVIRNOMENT=all" >> $GITHUB_ENV + - if: ${{ inputs.skip_release }} + run: echo "SEMVER=skip" >> $GITHUB_ENV - - id: output + - id: get_semver name: Set Output - run: | - echo "environment=${{env.ENVIRNOMENT}}" >> $GITHUB_OUTPUT + run: echo "semver=${{env.SEMVER}}" >> $GITHUB_OUTPUT + + # Set Environment + - run: echo "ENVIRNOMENT=${{ inputs.environment}}" >> $GITHUB_ENV + + - if: ${{ inputs.environment == null }} + run: echo "ENVIRNOMENT=dev" >> $GITHUB_ENV + + - id: get_env + name: Set Output + run: echo "environment=${{env.ENVIRNOMENT}}" >> $GITHUB_OUTPUT release: @@ -98,12 +94,12 @@ jobs: steps: - name: Make Release id: release - uses: pagopa/github-actions-template/maven-release@v1.4.1 + uses: pagopa/github-actions-template/maven-release@v1.5.4 with: semver: ${{ needs.setup.outputs.semver }} github_token: ${{ secrets.BOT_TOKEN_GITHUB }} beta: ${{ inputs.beta }} - skip_ci: ${{ inputs.beta }} + skip_ci: false image: needs: [ setup, release ] @@ -113,11 +109,10 @@ jobs: steps: - name: Build and Push id: semver - uses: pagopa/github-actions-template/ghcr-build-push@main + uses: pagopa/github-actions-template/ghcr-build-push@v1.5.4 with: - file: src/main/docker/Dockerfile.multistage - github_token: ${{ secrets.GITHUB_TOKEN }} branch: ${{ github.ref_name}} + github_token: ${{ secrets.GITHUB_TOKEN }} tag: ${{ needs.release.outputs.version }} deploy_aks: @@ -127,28 +122,27 @@ jobs: strategy: matrix: environment: [ dev, uat, prod ] - uses: ./.github/workflows/self_hosted.yml + uses: ./.github/workflows/deploy_with_github_runner.yml with: - target: ${{ matrix.environment }} - environment: ${{ needs.setup.outputs.environment }} - beta: ${{ inputs.beta }} + environment: ${{ matrix.environment }} + target: ${{ needs.setup.outputs.environment }} secrets: inherit notify: - needs: [ deploy_aks ] + needs: [ setup, release, deploy_aks ] runs-on: ubuntu-latest name: Notify if: always() steps: - name: Report Status - if: always() + if: ${{ needs.setup.outputs.environment == 'prod' || needs.setup.outputs.environment == 'all' }} uses: ravsamhq/notify-slack-action@v2 with: status: ${{ needs.deploy_aks.result }} token: ${{ secrets.GITHUB_TOKEN }} - notify_when: 'failure,skipped' - notification_title: '{workflow} has {status_message}' - message_format: '{emoji} <{workflow_url}|{workflow}> {status_message} in <{repo_url}|{repo}>' - footer: 'Linked to Repo <{repo_url}|{repo}>' + notification_title: 'New Release on Production ${{ needs.release.outputs.version }} has {status_message}' + message_format: '{emoji} <{run_url}|{workflow}> {status_message} in <{repo_url}|{repo}>' + footer: 'Linked to <{workflow_url}| workflow file>' + icon_success: ':white_check_mark:' env: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} From 05e14c5058f2074c196b89d36eda77a78bdc6a82 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Fri, 7 Jul 2023 11:32:45 +0200 Subject: [PATCH 14/29] wip --- .github/workflows/release_deploy.yml | 3 +++ Dockerfile | 34 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 Dockerfile diff --git a/.github/workflows/release_deploy.yml b/.github/workflows/release_deploy.yml index 577eef3..63bd6e0 100644 --- a/.github/workflows/release_deploy.yml +++ b/.github/workflows/release_deploy.yml @@ -114,6 +114,9 @@ jobs: branch: ${{ github.ref_name}} github_token: ${{ secrets.GITHUB_TOKEN }} tag: ${{ needs.release.outputs.version }} + build_args: + - APP_NAME=nodetechnicalsupport + - QUARKUS_PROFILE=prod deploy_aks: name: Deploy on AKS diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c627c29 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +## Stage 1 : build with maven builder image with native capabilities +FROM quay.io/quarkus/ubi-quarkus-graalvmce-builder-image:22.3-java17 AS build +COPY --chown=quarkus:quarkus mvnw /code/mvnw +COPY --chown=quarkus:quarkus .mvn /code/.mvn +COPY --chown=quarkus:quarkus pom.xml /code/ +USER quarkus +WORKDIR /code +RUN ./mvnw -B org.apache.maven.plugins:maven-dependency-plugin:3.1.2:go-offline +COPY src /code/src +ARG QUARKUS_PROFILE +ARG APP_NAME + +RUN ./mvnw package -DskipTests=true -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE + +FROM registry.access.redhat.com/ubi8/openjdk-17:1.14 + +ENV LANGUAGE='en_US:en' + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --from=build /code/target/quarkus-app/lib/ /deployments/lib/ +COPY --from=build /code/target/quarkus-app/*.jar /deployments/ +COPY --from=build /code/target/quarkus-app/app/ /deployments/app/ +COPY --from=build /code/target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 185 + +ARG QUARKUS_PROFILE +ARG APP_NAME + +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" + + From ccb23b481fbe269de06daabd4ff3025021285c44 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Fri, 7 Jul 2023 14:45:05 +0200 Subject: [PATCH 15/29] wip --- .dockerignore | 1 + .identity/00_locals.tf | 4 ++-- Dockerfile | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.dockerignore b/.dockerignore index 3977568..bdf0de3 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,3 +2,4 @@ !target/*-runner.jar !target/lib/* !target/quarkus-app/* +target/ \ No newline at end of file diff --git a/.identity/00_locals.tf b/.identity/00_locals.tf index 7155bb5..ccbc830 100644 --- a/.identity/00_locals.tf +++ b/.identity/00_locals.tf @@ -1,14 +1,14 @@ locals { github = { org = "pagopa" - repository = "" # TODO set the project repository + repository = "pagopa-node-technical-support-worker" } prefix = "pagopa" product = "${local.prefix}-${var.env_short}" project = "${local.prefix}-${var.env_short}-${local.location_short}-${local.domain}" runner = "${local.prefix}-${var.env_short}-${local.location_short}" - domain = "project-domain" # TODO set the project domain (i.e. namespace) + domain = "nodo" location_short = "weu" aks_name = "${local.product}-${local.location_short}-${var.env}-aks" diff --git a/Dockerfile b/Dockerfile index c627c29..4b62991 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ COPY --chown=quarkus:quarkus .mvn /code/.mvn COPY --chown=quarkus:quarkus pom.xml /code/ USER quarkus WORKDIR /code -RUN ./mvnw -B org.apache.maven.plugins:maven-dependency-plugin:3.1.2:go-offline +RUN chmod +x ./mvnw && ./mvnw -B org.apache.maven.plugins:maven-dependency-plugin:3.1.2:go-offline COPY src /code/src ARG QUARKUS_PROFILE ARG APP_NAME From 9fbefd25f91c4c186cc8848e1237b4108e734dc6 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Fri, 7 Jul 2023 15:35:56 +0200 Subject: [PATCH 16/29] wip --- helm/weu-dev/values-dev.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helm/weu-dev/values-dev.yaml b/helm/weu-dev/values-dev.yaml index f118c0a..c005bb1 100644 --- a/helm/weu-dev/values-dev.yaml +++ b/helm/weu-dev/values-dev.yaml @@ -1,7 +1,7 @@ pagopa-tech-support-api: namespace: "techsupport" image: - repository: pagopadcommonacr.azurecr.io/pagopanodetechnicalsupportworker + repository: ghcr.io/pagopa/pagopanodetechnicalsupportworker tag: '1.0.0-SNAPSHOT' readinessProbe: httpGet: From f29c9cecf25a37f8864551c040a8df6e00d92781 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Fri, 7 Jul 2023 16:03:10 +0200 Subject: [PATCH 17/29] .identity folder --- .identity/00_data.tf | 52 +++++++ .identity/00_locals.tf | 19 --- .identity/00_variables.tf | 29 ---- .identity/01_data.tf | 49 ------- .identity/02_application_action.tf | 102 +++++++++++--- .identity/02_application_action_auth.tf | 23 ---- .identity/03_github_environment.tf | 130 +++++++----------- .identity/{00_main.tf => 99_main.tf} | 16 +-- .identity/99_outputs.tf | 7 - .identity/99_variables.tf | 56 ++++++++ .identity/README.md | 4 - .identity/env/dev/backend.ini | 1 + .identity/env/dev/backend.tfvars | 4 + .identity/env/dev/terraform.tfvars | 11 ++ .identity/env/prod/backend.ini | 1 + .identity/env/prod/backend.tfvars | 4 + .identity/env/prod/terraform.tfvars | 11 ++ .identity/env/uat/backend.ini | 1 + .identity/env/uat/backend.tfvars | 4 + .identity/env/uat/terraform.tfvars | 11 ++ .quarkus/cli/plugins/quarkus-cli-catalog.json | 5 + 21 files changed, 302 insertions(+), 238 deletions(-) create mode 100644 .identity/00_data.tf delete mode 100644 .identity/00_locals.tf delete mode 100644 .identity/00_variables.tf delete mode 100644 .identity/01_data.tf delete mode 100644 .identity/02_application_action_auth.tf rename .identity/{00_main.tf => 99_main.tf} (57%) delete mode 100644 .identity/99_outputs.tf create mode 100644 .identity/99_variables.tf delete mode 100644 .identity/README.md create mode 100644 .identity/env/dev/backend.ini create mode 100644 .identity/env/dev/backend.tfvars create mode 100644 .identity/env/dev/terraform.tfvars create mode 100644 .identity/env/prod/backend.ini create mode 100644 .identity/env/prod/backend.tfvars create mode 100644 .identity/env/prod/terraform.tfvars create mode 100644 .identity/env/uat/backend.ini create mode 100644 .identity/env/uat/backend.tfvars create mode 100644 .identity/env/uat/terraform.tfvars create mode 100644 .quarkus/cli/plugins/quarkus-cli-catalog.json diff --git a/.identity/00_data.tf b/.identity/00_data.tf new file mode 100644 index 0000000..8273e72 --- /dev/null +++ b/.identity/00_data.tf @@ -0,0 +1,52 @@ +data "azurerm_storage_account" "tf_storage_account"{ + name = "pagopainfraterraform${var.env}" + resource_group_name = "io-infra-rg" +} + +data "azurerm_resource_group" "dashboards" { + name = "dashboards" +} + +data "azurerm_kubernetes_cluster" "aks" { + name = local.aks_cluster.name + resource_group_name = local.aks_cluster.resource_group_name +} + +data "github_organization_teams" "all" { + root_teams_only = true + summary_only = true +} + +data "azurerm_key_vault" "key_vault" { + name = "pagopa-${var.env_short}-kv" + resource_group_name = "pagopa-${var.env_short}-sec-rg" +} + +data "azurerm_key_vault" "domain_key_vault" { + name = "pagopa-${var.env_short}-${local.domain}-kv" + resource_group_name = "pagopa-${var.env_short}-${local.domain}-sec-rg" +} + +data "azurerm_resource_group" "apim_resource_group" { + name = "${local.product}-api-rg" +} + +data "azurerm_key_vault_secret" "key_vault_sonar" { + name = "sonar-token" + key_vault_id = data.azurerm_key_vault.key_vault.id +} + +data "azurerm_key_vault_secret" "key_vault_bot_token" { + name = "bot-token-github" + key_vault_id = data.azurerm_key_vault.key_vault.id +} + +data "azurerm_key_vault_secret" "key_vault_cucumber_token" { + name = "cucumber-token" + key_vault_id = data.azurerm_key_vault.key_vault.id +} + +data "azurerm_key_vault_secret" "key_vault_integration_test_subkey" { + name = "integration-test-subkey" + key_vault_id = data.azurerm_key_vault.key_vault.id +} diff --git a/.identity/00_locals.tf b/.identity/00_locals.tf deleted file mode 100644 index ccbc830..0000000 --- a/.identity/00_locals.tf +++ /dev/null @@ -1,19 +0,0 @@ -locals { - github = { - org = "pagopa" - repository = "pagopa-node-technical-support-worker" - } - prefix = "pagopa" - product = "${local.prefix}-${var.env_short}" - project = "${local.prefix}-${var.env_short}-${local.location_short}-${local.domain}" - runner = "${local.prefix}-${var.env_short}-${local.location_short}" - - domain = "nodo" - location_short = "weu" - - aks_name = "${local.product}-${local.location_short}-${var.env}-aks" - aks_resource_group_name = "${local.product}-${local.location_short}-${var.env}-aks-rg" - - pagopa_apim_name = "${local.product}-apim" - pagopa_apim_rg = "${local.product}-api-rg" -} diff --git a/.identity/00_variables.tf b/.identity/00_variables.tf deleted file mode 100644 index 3f77901..0000000 --- a/.identity/00_variables.tf +++ /dev/null @@ -1,29 +0,0 @@ -variable "env" { - type = string -} - -variable "env_short" { - type = string -} - - -variable "github_repository_environment" { - type = object({ - protected_branches = bool - custom_branch_policies = bool - reviewers_teams = list(string) - }) - description = "GitHub Continuous Integration roles" - default = { - protected_branches = false - custom_branch_policies = true - reviewers_teams = ["pagopa-tech"] - } - -} - - -variable "k8s_kube_config_path_prefix" { - type = string - default = "~/.kube" -} diff --git a/.identity/01_data.tf b/.identity/01_data.tf deleted file mode 100644 index 6a7d4a3..0000000 --- a/.identity/01_data.tf +++ /dev/null @@ -1,49 +0,0 @@ -data "azurerm_storage_account" "tfstate_app" { - name = "pagopainfraterraform${var.env}" - resource_group_name = "io-infra-rg" -} - -data "azurerm_resource_group" "dashboards" { - name = "dashboards" -} - -data "azurerm_key_vault" "key_vault" { - count = var.env_short == "d" ? 1 : 0 - - name = "pagopa-${var.env_short}-kv" - resource_group_name = "pagopa-${var.env_short}-sec-rg" -} - -data "azurerm_key_vault_secret" "key_vault_sonar" { - count = var.env_short == "d" ? 1 : 0 - - name = "sonar-token" - key_vault_id = data.azurerm_key_vault.key_vault[0].id -} - -data "azurerm_key_vault_secret" "key_vault_bot_token" { - count = var.env_short == "d" ? 1 : 0 - - name = "bot-token-github" - key_vault_id = data.azurerm_key_vault.key_vault[0].id -} -data "azurerm_key_vault_secret" "key_vault_cucumber_token" { - count = var.env_short == "d" ? 1 : 0 - - name = "cucumber-token" - key_vault_id = data.azurerm_key_vault.key_vault[0].id -} - -data "azurerm_kubernetes_cluster" "aks" { - name = local.aks_name - resource_group_name = local.aks_resource_group_name -} - -data "azurerm_resource_group" "github_runner_rg" { - name = "${local.runner}-github-runner-rg" -} - -data "github_organization_teams" "all" { - root_teams_only = true - summary_only = true -} diff --git a/.identity/02_application_action.tf b/.identity/02_application_action.tf index 02dc4f4..d6a7a24 100644 --- a/.identity/02_application_action.tf +++ b/.identity/02_application_action.tf @@ -1,28 +1,96 @@ -resource "azuread_application" "action" { - display_name = "github-${local.github.org}-${local.github.repository}-${var.env}" +module "github_runner_app" { + source = "git::https://github.com/pagopa/github-actions-tf-modules.git//app-github-runner-creator?ref=main" + + app_name = local.app_name + + subscription_id = data.azurerm_subscription.current.id + + github_org = local.github.org + github_repository = local.github.repository + github_environment_name = var.env + + container_app_github_runner_env_rg = local.container_app_environment.resource_group +} + +resource "null_resource" "github_runner_app_permissions_to_namespace" { + triggers = { + aks_id = data.azurerm_kubernetes_cluster.aks.id + service_principal_id = module.github_runner_app.client_id + namespace = local.domain + version = "v2" + } + + provisioner "local-exec" { + command = < Date: Tue, 18 Jul 2023 11:50:23 +0200 Subject: [PATCH 18/29] uat files --- .devops/deploy-pipelines.yml | 1 - helm/weu-uat/values-uat.yaml | 85 ++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 helm/weu-uat/values-uat.yaml diff --git a/.devops/deploy-pipelines.yml b/.devops/deploy-pipelines.yml index 0f5eece..d41c5f0 100644 --- a/.devops/deploy-pipelines.yml +++ b/.devops/deploy-pipelines.yml @@ -93,7 +93,6 @@ variables: WEU_kubernetesServiceConnection: '$(DEV_KUBERNETES_SERVICE_CONN)' WEU_poolImage: '$(DEPLOY-POOL-DEV)' - ${{ if eq(parameters['ENV'], 'uat') }}: WEU_dockerRegistryServiceConnection: $(UAT_CONTAINER_REGISTRY_SERVICE_CONN) WEU_dockerRegistryFqdn: $(UAT_CONTAINER_NAMESPACE) diff --git a/helm/weu-uat/values-uat.yaml b/helm/weu-uat/values-uat.yaml new file mode 100644 index 0000000..678b7c4 --- /dev/null +++ b/helm/weu-uat/values-uat.yaml @@ -0,0 +1,85 @@ +pagopa-tech-support-api: + namespace: "techsupport" + image: + repository: ghcr.io/pagopa/pagopanodetechnicalsupportworker + tag: '1.0.0-SNAPSHOT' + readinessProbe: + httpGet: + path: /q/health/ready + port: 8080 + initialDelaySeconds: 8 + failureThreshold: 10 + periodSeconds: 2 + livenessProbe: + httpGet: + path: /q/health/live + port: 8080 + initialDelaySeconds: 8 + failureThreshold: 10 + periodSeconds: 2 + envConfig: + APP_ENVIRONMENT: "uat" + TZ: "Europe/Rome" + OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" + ADAPTER_API_CONFIG_CACHE_URL: "https://api.uat.platform.pagopa.it/api-config-cache/p/v1" + COSMOS_BIZ_ENDPOINT: "https://pagopa-u-weu-bizevents-ds-cosmos-account.documents.azure.com:443/" + COSMOS_NEG_BIZ_ENDPOINT: "https://pagopa-u-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/" + envFieldRef: + APP_NAME: "metadata.labels['app.kubernetes.io/instance']" + APP_VERSION: "metadata.labels['app.kubernetes.io/version']" + secretProvider: + create: true + envSecrets: + ADAPTER_API_CONFIG_CACHE_API_KEY: "api-config-cache-subscription-key-string" + EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" + COSMOS_BIZ_KEY: "cosmos-biz-account-key" + COSMOS_NEG_BIZ_KEY: "cosmos-neg-biz-account-key" + RE_TABLE_STORAGE_CONN_STRING: "re-datastore-connection-string" + keyvault: + name: "pagopa-u-nodo-kv" + tenantId: "7788edaf-0346-4068-9d79-c868aed15b3d" + tmpVolumeMount: + create: true + resources: + requests: + memory: "2Gi" + cpu: "200m" + limits: + memory: "3Gi" + cpu: "400m" + autoscaling: + enable: true + minReplica: 1 + maxReplica: 2 + pollingInterval: 10 # seconds + cooldownPeriod: 50 # seconds + triggers: + - type: cpu + metadata: + type: Utilization + value: "75" + - type: memory + metadata: + type: Utilization + value: "75" + affinity: + nodeAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + - matchExpressions: + - key: node_type + operator: In + values: + - user + serviceMonitor: + create: true + endpoints: + - interval: 5s + targetPort: 8080 + path: /q/metrics + service: + create: true + ingress: + create: true + host: "weuuat.techsupport.internal.uat.platform.pagopa.it" + path: /pagopa-tech-support(/|$)(.*) From b98d5d4564c07fbafd1cef51d2c1521e1b6b7757 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Tue, 18 Jul 2023 11:55:01 +0200 Subject: [PATCH 19/29] uat files --- .github/workflows/release_deploy.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/release_deploy.yml b/.github/workflows/release_deploy.yml index 63bd6e0..8006792 100644 --- a/.github/workflows/release_deploy.yml +++ b/.github/workflows/release_deploy.yml @@ -114,9 +114,7 @@ jobs: branch: ${{ github.ref_name}} github_token: ${{ secrets.GITHUB_TOKEN }} tag: ${{ needs.release.outputs.version }} - build_args: - - APP_NAME=nodetechnicalsupport - - QUARKUS_PROFILE=prod + build_args: "APP_NAME=nodetechnicalsupport QUARKUS_PROFILE=prod" deploy_aks: name: Deploy on AKS From 2f2df0b5698edff65d325b233b67454d803325f1 Mon Sep 17 00:00:00 2001 From: pagopa-github-bot Date: Tue, 18 Jul 2023 09:56:32 +0000 Subject: [PATCH 20/29] Bump to version 1.0.0-1-implementing [skip ci] --- helm/Chart.yaml | 4 +- openapi/openapi.json | 716 +++++++++++++++++++++++-------------------- pom.xml | 2 +- 3 files changed, 379 insertions(+), 343 deletions(-) diff --git a/helm/Chart.yaml b/helm/Chart.yaml index 57b9e21..b239754 100644 --- a/helm/Chart.yaml +++ b/helm/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: pagopa-tech-support-api description: Technical support api type: application -version: "0.0.0-SNAPSHOT" -appVersion: "0.0.0-SNAPSHOT" +version: "0.1.0" +appVersion: "1.0.0-1-implementing" dependencies: - name: microservice-chart version: 3.0.0 diff --git a/openapi/openapi.json b/openapi/openapi.json index e700d89..b9f52fe 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -1,32 +1,38 @@ { - "openapi" : "3.0.3", - "info" : { - "title" : "Node technical support - Api (local) ${service}", - "termsOfService" : "https://www.pagopa.gov.it/", - "version" : "1.0.0-SNAPSHOT" + "openapi": "3.0.3", + "info": { + "title": "Node technical support - Api (local) ${service}", + "termsOfService": "https://www.pagopa.gov.it/", + "version": "1.0.0-1-implementing" }, - "servers" : [ { - "url" : "${host}/tenchinal-support/api/v1 - APIM" - } ], - "tags" : [ { - "name" : "Info", - "description" : "Info operations" - } ], - "paths" : { - "/info" : { - "get" : { - "tags" : [ "Info" ], - "summary" : "Get info of FDR", - "responses" : { - "default" : { - "$ref" : "#/components/responses/InternalServerError" - }, - "200" : { - "description" : "Success", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/InfoResponse" + "servers": [ + { + "url": "${host}/tenchinal-support/api/v1 - APIM" + } + ], + "tags": [ + { + "name": "Info", + "description": "Info operations" + } + ], + "paths": { + "/info": { + "get": { + "tags": [ + "Info" + ], + "summary": "Get info of FDR", + "responses": { + "default": { + "$ref": "#/components/responses/InternalServerError" + }, + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InfoResponse" } } } @@ -34,63 +40,70 @@ } } }, - "/organizations/{organizationFiscalCode}/iuv/{iuv}" : { - "get" : { - "tags" : [ "Worker Resource" ], - "parameters" : [ { - "name" : "iuv", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "organizationFiscalCode", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "dateFrom", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" - } - }, { - "name" : "dateTo", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" + "/organizations/{organizationFiscalCode}/iuv/{iuv}": { + "get": { + "tags": [ + "Worker Resource" + ], + "parameters": [ + { + "name": "iuv", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "organizationFiscalCode", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "dateFrom", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } + }, + { + "name": "dateTo", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TransactionResponse" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TransactionResponse" } } } }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } }, - "500" : { - "description" : "Service unavailable.", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "500": { + "description": "Service unavailable.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } @@ -98,70 +111,78 @@ } } }, - "/organizations/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}" : { - "get" : { - "tags" : [ "Worker Resource" ], - "parameters" : [ { - "name" : "ccp", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "iuv", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "organizationFiscalCode", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "dateFrom", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" - } - }, { - "name" : "dateTo", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" + "/organizations/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}": { + "get": { + "tags": [ + "Worker Resource" + ], + "parameters": [ + { + "name": "ccp", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "iuv", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "organizationFiscalCode", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "dateFrom", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } + }, + { + "name": "dateTo", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TransactionResponse" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TransactionResponse" } } } }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } }, - "500" : { - "description" : "Service unavailable.", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "500": { + "description": "Service unavailable.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } @@ -169,70 +190,78 @@ } } }, - "/organizations/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}" : { - "get" : { - "tags" : [ "Worker Resource" ], - "parameters" : [ { - "name" : "iuv", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "organizationFiscalCode", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "paymentToken", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "dateFrom", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" - } - }, { - "name" : "dateTo", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" + "/organizations/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}": { + "get": { + "tags": [ + "Worker Resource" + ], + "parameters": [ + { + "name": "iuv", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "organizationFiscalCode", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "paymentToken", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "dateFrom", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } + }, + { + "name": "dateTo", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TransactionResponse" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TransactionResponse" } } } }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } }, - "500" : { - "description" : "Service unavailable.", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "500": { + "description": "Service unavailable.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } @@ -240,63 +269,70 @@ } } }, - "/organizations/{organizationFiscalCode}/noticeNumber/{noticeNumber}" : { - "get" : { - "tags" : [ "Worker Resource" ], - "parameters" : [ { - "name" : "noticeNumber", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "organizationFiscalCode", - "in" : "path", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "name" : "dateFrom", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" - } - }, { - "name" : "dateTo", - "in" : "query", - "schema" : { - "$ref" : "#/components/schemas/LocalDate" + "/organizations/{organizationFiscalCode}/noticeNumber/{noticeNumber}": { + "get": { + "tags": [ + "Worker Resource" + ], + "parameters": [ + { + "name": "noticeNumber", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "organizationFiscalCode", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "dateFrom", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } + }, + { + "name": "dateTo", + "in": "query", + "schema": { + "$ref": "#/components/schemas/LocalDate" + } } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TransactionResponse" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TransactionResponse" } } } }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "400": { + "description": "Bad Request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } }, - "500" : { - "description" : "Service unavailable.", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ProblemJson" + "500": { + "description": "Service unavailable.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemJson" } } } @@ -305,145 +341,145 @@ } } }, - "components" : { - "schemas" : { - "BasePaymentInfo" : { - "type" : "object", - "properties" : { - "organizationFiscalCode" : { - "type" : "string" + "components": { + "schemas": { + "BasePaymentInfo": { + "type": "object", + "properties": { + "organizationFiscalCode": { + "type": "string" }, - "noticeNumber" : { - "type" : "string" + "noticeNumber": { + "type": "string" }, - "iuv" : { - "type" : "string" + "iuv": { + "type": "string" }, - "pspId" : { - "type" : "string" + "pspId": { + "type": "string" }, - "brokerPspId" : { - "type" : "string" + "brokerPspId": { + "type": "string" }, - "channelId" : { - "type" : "string" + "channelId": { + "type": "string" }, - "outcome" : { - "type" : "string" + "outcome": { + "type": "string" }, - "status" : { - "type" : "string" + "status": { + "type": "string" }, - "insertedTimestamp" : { - "type" : "string" + "insertedTimestamp": { + "type": "string" }, - "updatedTimestamp" : { - "type" : "string" + "updatedTimestamp": { + "type": "string" }, - "isOldPaymentModel" : { - "type" : "boolean" + "isOldPaymentModel": { + "type": "boolean" }, - "nodeId" : { - "type" : "string" + "nodeId": { + "type": "string" } } }, - "ErrorCode" : { - "type" : "object", - "properties" : { - "code" : { - "type" : "string", - "example" : "FDR-0500" - }, - "description" : { - "type" : "string", - "example" : "An unexpected error has occurred. Please contact support." - }, - "statusCode" : { - "format" : "int32", - "type" : "integer", - "example" : 500 + "ErrorCode": { + "type": "object", + "properties": { + "code": { + "type": "string", + "example": "FDR-0500" + }, + "description": { + "type": "string", + "example": "An unexpected error has occurred. Please contact support." + }, + "statusCode": { + "format": "int32", + "type": "integer", + "example": 500 } } }, - "InfoResponse" : { - "type" : "object", - "properties" : { - "name" : { - "type" : "string", - "example" : "pagopa-fdr" - }, - "version" : { - "type" : "string", - "example" : "1.2.3" - }, - "environment" : { - "type" : "string", - "example" : "dev" - }, - "description" : { - "type" : "string", - "example" : "FDR - Flussi di rendicontazione" - }, - "errorCodes" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/ErrorCode" + "InfoResponse": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "pagopa-fdr" + }, + "version": { + "type": "string", + "example": "1.2.3" + }, + "environment": { + "type": "string", + "example": "dev" + }, + "description": { + "type": "string", + "example": "FDR - Flussi di rendicontazione" + }, + "errorCodes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ErrorCode" } } } }, - "LocalDate" : { - "format" : "date", - "type" : "string", - "example" : "2022-03-10" + "LocalDate": { + "format": "date", + "type": "string", + "example": "2022-03-10" }, - "ProblemJson" : { - "type" : "object", - "properties" : { - "title" : { - "description" : "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable", - "type" : "string" - }, - "status" : { - "format" : "int32", - "description" : "The HTTP status code generated by the origin server for this occurrence of the problem.", - "maximum" : 600, - "minimum" : 100, - "type" : "integer", - "example" : 200 - }, - "details" : { - "description" : "A human readable explanation specific to this occurrence of the problem.", - "type" : "string", - "example" : "There was an error processing the request" + "ProblemJson": { + "type": "object", + "properties": { + "title": { + "description": "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable", + "type": "string" + }, + "status": { + "format": "int32", + "description": "The HTTP status code generated by the origin server for this occurrence of the problem.", + "maximum": 600, + "minimum": 100, + "type": "integer", + "example": 200 + }, + "details": { + "description": "A human readable explanation specific to this occurrence of the problem.", + "type": "string", + "example": "There was an error processing the request" } } }, - "TransactionResponse" : { - "type" : "object", - "properties" : { - "dateFrom" : { - "$ref" : "#/components/schemas/LocalDate" + "TransactionResponse": { + "type": "object", + "properties": { + "dateFrom": { + "$ref": "#/components/schemas/LocalDate" }, - "dateTo" : { - "$ref" : "#/components/schemas/LocalDate" + "dateTo": { + "$ref": "#/components/schemas/LocalDate" }, - "data" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/BasePaymentInfo" + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BasePaymentInfo" } } } } }, - "securitySchemes" : { - "SecurityScheme" : { - "type" : "http", - "description" : "Authentication", - "scheme" : "basic" + "securitySchemes": { + "SecurityScheme": { + "type": "http", + "description": "Authentication", + "scheme": "basic" } } } -} \ No newline at end of file +} diff --git a/pom.xml b/pom.xml index 7e30703..4a24896 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 it.gov.pagopa node-techical-support-worker - 1.0.0-SNAPSHOT + 1.0.0-1-implementing 3.11.0 1.18.26 From 0457036bb41509590fb00aeb3bf661e4b5c3c134 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Tue, 18 Jul 2023 12:07:27 +0200 Subject: [PATCH 21/29] uat files --- .github/workflows/release_deploy.yml | 1 - Dockerfile | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/release_deploy.yml b/.github/workflows/release_deploy.yml index 8006792..577eef3 100644 --- a/.github/workflows/release_deploy.yml +++ b/.github/workflows/release_deploy.yml @@ -114,7 +114,6 @@ jobs: branch: ${{ github.ref_name}} github_token: ${{ secrets.GITHUB_TOKEN }} tag: ${{ needs.release.outputs.version }} - build_args: "APP_NAME=nodetechnicalsupport QUARKUS_PROFILE=prod" deploy_aks: name: Deploy on AKS diff --git a/Dockerfile b/Dockerfile index 4b62991..4ed4fe1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,8 +7,8 @@ USER quarkus WORKDIR /code RUN chmod +x ./mvnw && ./mvnw -B org.apache.maven.plugins:maven-dependency-plugin:3.1.2:go-offline COPY src /code/src -ARG QUARKUS_PROFILE -ARG APP_NAME +ENV APP_NAME=nodetechnicalsupport +ENV QUARKUS_PROFILE=prod RUN ./mvnw package -DskipTests=true -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE @@ -25,8 +25,8 @@ COPY --from=build /code/target/quarkus-app/quarkus/ /deployments/quarkus/ EXPOSE 8080 USER 185 -ARG QUARKUS_PROFILE -ARG APP_NAME +ENV APP_NAME=nodetechnicalsupport +ENV QUARKUS_PROFILE=prod ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Dquarkus.application.name=$APP_NAME -Dquarkus.profile=$QUARKUS_PROFILE -Djava.util.logging.manager=org.jboss.logmanager.LogManager" ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" From cf147651135bb6869034c37cbc02a924621220dd Mon Sep 17 00:00:00 2001 From: pagopa-github-bot Date: Tue, 18 Jul 2023 10:09:05 +0000 Subject: [PATCH 22/29] Bump to version 1.0.0-2-implementing [skip ci] --- helm/Chart.yaml | 4 ++-- openapi/openapi.json | 2 +- pom.xml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/helm/Chart.yaml b/helm/Chart.yaml index b239754..65e3daa 100644 --- a/helm/Chart.yaml +++ b/helm/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: pagopa-tech-support-api description: Technical support api type: application -version: "0.1.0" -appVersion: "1.0.0-1-implementing" +version: "0.2.0" +appVersion: "1.0.0-2-implementing" dependencies: - name: microservice-chart version: 3.0.0 diff --git a/openapi/openapi.json b/openapi/openapi.json index b9f52fe..a3e811f 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "Node technical support - Api (local) ${service}", "termsOfService": "https://www.pagopa.gov.it/", - "version": "1.0.0-1-implementing" + "version": "1.0.0-2-implementing" }, "servers": [ { diff --git a/pom.xml b/pom.xml index 4a24896..da76091 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 it.gov.pagopa node-techical-support-worker - 1.0.0-1-implementing + 1.0.0-2-implementing 3.11.0 1.18.26 From f4fe23ae3a50ac4e22c048bdcf581e910f409e3c Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Tue, 18 Jul 2023 16:24:51 +0200 Subject: [PATCH 23/29] uat files --- .../workflows/deploy_with_github_runner.yml | 2 +- helm/values-dev.yaml | 85 +++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 helm/values-dev.yaml diff --git a/.github/workflows/deploy_with_github_runner.yml b/.github/workflows/deploy_with_github_runner.yml index fd1b2ef..7e2fe75 100644 --- a/.github/workflows/deploy_with_github_runner.yml +++ b/.github/workflows/deploy_with_github_runner.yml @@ -13,7 +13,7 @@ on: type: string env: - APP_NAME: # TODO + APP_NAME: node_technicalsupport permissions: diff --git a/helm/values-dev.yaml b/helm/values-dev.yaml new file mode 100644 index 0000000..c005bb1 --- /dev/null +++ b/helm/values-dev.yaml @@ -0,0 +1,85 @@ +pagopa-tech-support-api: + namespace: "techsupport" + image: + repository: ghcr.io/pagopa/pagopanodetechnicalsupportworker + tag: '1.0.0-SNAPSHOT' + readinessProbe: + httpGet: + path: /q/health/ready + port: 8080 + initialDelaySeconds: 8 + failureThreshold: 10 + periodSeconds: 2 + livenessProbe: + httpGet: + path: /q/health/live + port: 8080 + initialDelaySeconds: 8 + failureThreshold: 10 + periodSeconds: 2 + envConfig: + APP_ENVIRONMENT: "dev" + TZ: "Europe/Rome" + OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" + ADAPTER_API_CONFIG_CACHE_URL: "https://api.dev.platform.pagopa.it/api-config-cache/p/v1" + COSMOS_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-ds-cosmos-account.documents.azure.com:443/" + COSMOS_NEG_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/" + envFieldRef: + APP_NAME: "metadata.labels['app.kubernetes.io/instance']" + APP_VERSION: "metadata.labels['app.kubernetes.io/version']" + secretProvider: + create: true + envSecrets: + ADAPTER_API_CONFIG_CACHE_API_KEY: "api-config-cache-subscription-key-string" + EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" + COSMOS_BIZ_KEY: "cosmos-biz-account-key" + COSMOS_NEG_BIZ_KEY: "cosmos-neg-biz-account-key" + RE_TABLE_STORAGE_CONN_STRING: "re-datastore-connection-string" + keyvault: + name: "pagopa-d-nodo-kv" + tenantId: "7788edaf-0346-4068-9d79-c868aed15b3d" + tmpVolumeMount: + create: true + resources: + requests: + memory: "2Gi" + cpu: "200m" + limits: + memory: "3Gi" + cpu: "400m" + autoscaling: + enable: true + minReplica: 1 + maxReplica: 2 + pollingInterval: 10 # seconds + cooldownPeriod: 50 # seconds + triggers: + - type: cpu + metadata: + type: Utilization + value: "75" + - type: memory + metadata: + type: Utilization + value: "75" + affinity: + nodeAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + - matchExpressions: + - key: node_type + operator: In + values: + - user + serviceMonitor: + create: true + endpoints: + - interval: 5s + targetPort: 8080 + path: /q/metrics + service: + create: true + ingress: + create: true + host: "weudev.techsupport.internal.dev.platform.pagopa.it" + path: /pagopa-tech-support(/|$)(.*) From 6f4c0d61ff7d988cd1f827367f9821e6458c7075 Mon Sep 17 00:00:00 2001 From: pagopa-github-bot Date: Tue, 18 Jul 2023 14:26:21 +0000 Subject: [PATCH 24/29] Bump to version 1.0.0-3-implementing [skip ci] --- helm/Chart.yaml | 4 ++-- helm/values-dev.yaml | 7 +++++++ openapi/openapi.json | 2 +- pom.xml | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/helm/Chart.yaml b/helm/Chart.yaml index 65e3daa..64a7255 100644 --- a/helm/Chart.yaml +++ b/helm/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: pagopa-tech-support-api description: Technical support api type: application -version: "0.2.0" -appVersion: "1.0.0-2-implementing" +version: "0.3.0" +appVersion: "1.0.0-3-implementing" dependencies: - name: microservice-chart version: 3.0.0 diff --git a/helm/values-dev.yaml b/helm/values-dev.yaml index c005bb1..1801bf9 100644 --- a/helm/values-dev.yaml +++ b/helm/values-dev.yaml @@ -83,3 +83,10 @@ pagopa-tech-support-api: create: true host: "weudev.techsupport.internal.dev.platform.pagopa.it" path: /pagopa-tech-support(/|$)(.*) +microservice-chart: + image: + tag: 1.0.0-3-implementing + canaryDelivery: + deployment: + image: + tag: 1.0.0-3-implementing diff --git a/openapi/openapi.json b/openapi/openapi.json index a3e811f..1b27b7b 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "Node technical support - Api (local) ${service}", "termsOfService": "https://www.pagopa.gov.it/", - "version": "1.0.0-2-implementing" + "version": "1.0.0-3-implementing" }, "servers": [ { diff --git a/pom.xml b/pom.xml index da76091..d1e753c 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 it.gov.pagopa node-techical-support-worker - 1.0.0-2-implementing + 1.0.0-3-implementing 3.11.0 1.18.26 From 7ed3ba43b5bd890368e3b0fbb65b376798896673 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Tue, 18 Jul 2023 16:31:21 +0200 Subject: [PATCH 25/29] uat files --- .github/workflows/deploy_with_github_runner.yml | 2 +- .github/workflows/self_hosted.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/deploy_with_github_runner.yml b/.github/workflows/deploy_with_github_runner.yml index 7e2fe75..72ec64e 100644 --- a/.github/workflows/deploy_with_github_runner.yml +++ b/.github/workflows/deploy_with_github_runner.yml @@ -13,7 +13,7 @@ on: type: string env: - APP_NAME: node_technicalsupport + APP_NAME: node-technicalsupport permissions: diff --git a/.github/workflows/self_hosted.yml b/.github/workflows/self_hosted.yml index e6bf0a5..b3c7d61 100644 --- a/.github/workflows/self_hosted.yml +++ b/.github/workflows/self_hosted.yml @@ -14,8 +14,8 @@ on: env: - NAMESPACE: # TODO set namespace - APP_NAME: # TODO set project name + NAMESPACE: nodo + APP_NAME: node-technicalsupport permissions: From 2052964f5097c474e767a6a7a57f1f043554aee7 Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Tue, 18 Jul 2023 16:37:45 +0200 Subject: [PATCH 26/29] fix helm files --- .devops/deploy-pipelines.yml | 2 +- helm/values-dev.yaml | 2 +- helm/weu-dev/values-dev.yaml | 2 +- helm/weu-uat/values-uat.yaml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.devops/deploy-pipelines.yml b/.devops/deploy-pipelines.yml index d41c5f0..6bbf548 100644 --- a/.devops/deploy-pipelines.yml +++ b/.devops/deploy-pipelines.yml @@ -85,7 +85,7 @@ variables: WEU_value_file: "helm/weu-${{ parameters['ENV'] }}/values-${{ parameters['ENV'] }}.yaml" NEU_value_file: "helm/neu-${{ parameters['ENV'] }}/values-${{ parameters['ENV'] }}.yaml" - appName: 'pagopatechsupport' + appName: 'node-technicalsupport' ${{ if eq(parameters['ENV'], 'dev') }}: WEU_dockerRegistryServiceConnection: $(DEV_CONTAINER_REGISTRY_SERVICE_CONN) diff --git a/helm/values-dev.yaml b/helm/values-dev.yaml index 1801bf9..ab19d0d 100644 --- a/helm/values-dev.yaml +++ b/helm/values-dev.yaml @@ -1,5 +1,5 @@ pagopa-tech-support-api: - namespace: "techsupport" + namespace: "nodo" image: repository: ghcr.io/pagopa/pagopanodetechnicalsupportworker tag: '1.0.0-SNAPSHOT' diff --git a/helm/weu-dev/values-dev.yaml b/helm/weu-dev/values-dev.yaml index c005bb1..824bddf 100644 --- a/helm/weu-dev/values-dev.yaml +++ b/helm/weu-dev/values-dev.yaml @@ -1,5 +1,5 @@ pagopa-tech-support-api: - namespace: "techsupport" + namespace: "nodo" image: repository: ghcr.io/pagopa/pagopanodetechnicalsupportworker tag: '1.0.0-SNAPSHOT' diff --git a/helm/weu-uat/values-uat.yaml b/helm/weu-uat/values-uat.yaml index 678b7c4..f5352d7 100644 --- a/helm/weu-uat/values-uat.yaml +++ b/helm/weu-uat/values-uat.yaml @@ -1,5 +1,5 @@ pagopa-tech-support-api: - namespace: "techsupport" + namespace: "nodo" image: repository: ghcr.io/pagopa/pagopanodetechnicalsupportworker tag: '1.0.0-SNAPSHOT' From 7d0d5451a5df7f333b5dde79b7a3b787a871c24e Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 19 Jul 2023 18:25:13 +0200 Subject: [PATCH 27/29] fix by design --- pom.xml | 5 - .../gov/pagopa/nodetsworker/AppStartup.java | 30 - .../it/gov/pagopa/nodetsworker/Config.java | 84 - .../nodetsworker/models/BasePaymentInfo.java | 5 +- .../models/PaymentAttemptInfo.java | 11 +- .../nodetsworker/models/PaymentInfo.java | 1 + .../repository/CosmosBizEventClient.java | 12 +- .../resources/WorkerResource.java | 6 +- .../nodetsworker/service/WorkerService.java | 153 +- src/main/resources/application.properties | 2 +- .../nodetsworker/resources/Sp03Test.java | 20 +- .../nodetsworker/resources/Sp04Test.java | 21 +- .../util/AppConstantTestHelper.java | 8 +- src/test/resources/mockserver.properties | 3 - src/test/resources/mockserver/cache.json | 1701 ----------------- 15 files changed, 112 insertions(+), 1950 deletions(-) delete mode 100644 src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java delete mode 100644 src/main/java/it/gov/pagopa/nodetsworker/Config.java delete mode 100644 src/test/resources/mockserver.properties delete mode 100644 src/test/resources/mockserver/cache.json diff --git a/pom.xml b/pom.xml index d1e753c..ff157ce 100644 --- a/pom.xml +++ b/pom.xml @@ -116,11 +116,6 @@ io.quarkus quarkus-scheduler - - io.quarkiverse.mockserver - quarkus-mockserver-test - 1.0.0 - com.azure azure-data-tables diff --git a/src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java b/src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java deleted file mode 100644 index e597bc4..0000000 --- a/src/main/java/it/gov/pagopa/nodetsworker/AppStartup.java +++ /dev/null @@ -1,30 +0,0 @@ -package it.gov.pagopa.nodetsworker; - -import io.quarkus.runtime.Startup; -import jakarta.annotation.PostConstruct; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; -import org.eclipse.microprofile.config.inject.ConfigProperty; -import org.jboss.logging.Logger; - -@Startup -@ApplicationScoped -public class AppStartup { - - @ConfigProperty(name = "startconfig.enabled") - boolean startconfig; - - @Inject Logger log; - - @Inject Config config; - - @PostConstruct - public void init() { - if (startconfig) { - log.info("Start Cache ENABLED"); - config.init(); - } else { - log.info("Start Cache DISABLED"); - } - } -} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/Config.java b/src/main/java/it/gov/pagopa/nodetsworker/Config.java deleted file mode 100644 index e4d6f95..0000000 --- a/src/main/java/it/gov/pagopa/nodetsworker/Config.java +++ /dev/null @@ -1,84 +0,0 @@ -package it.gov.pagopa.nodetsworker; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.quarkus.scheduler.Scheduled; -import io.quarkus.scheduler.ScheduledExecution; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; -import jakarta.ws.rs.client.ClientRequestFilter; -import java.net.URI; -import java.util.Collections; -import lombok.SneakyThrows; -import org.eclipse.microprofile.config.inject.ConfigProperty; -import org.eclipse.microprofile.rest.client.RestClientBuilder; -import org.jboss.logging.Logger; -import org.openapi.quarkus.api_config_cache_json.api.NodeCacheApi; -import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; - -@ApplicationScoped -public class Config { - - @ConfigProperty(name = "adapter.api_config_cache.url") - String url; - - @ConfigProperty(name = "adapter.api_config_cache.api-key-name") - String apiKeyName; - - @ConfigProperty(name = "adapter.api_config_cache.api-key-value") - String apiKeyValue; - - private NodeCacheApi nodeCacheApi; - - // @PostConstruct - @SneakyThrows - public void init() { - nodeCacheApi = - RestClientBuilder.newBuilder() - .baseUri(new URI(url)) - .register( - (ClientRequestFilter) - context -> - context - .getHeaders() - .put(apiKeyName, Collections.singletonList(apiKeyValue))) - .build(NodeCacheApi.class); - - ConfigDataV1 newCache = nodeCacheApi.cache(null); - log.debugf("Cache init. Version [%s]", newCache.getVersion()); - this.cache = newCache; - } - - @Inject ObjectMapper objectMapper; - - ConfigDataV1 cache; - - @SneakyThrows - public ConfigDataV1 getClonedCache() { - if (this.cache == null) { - log.debug("Api config cache NOT INITIALIZED"); - return null; - } else { - return objectMapper.readValue( - objectMapper.writeValueAsString(this.cache), ConfigDataV1.class); - } - } - - @Inject Logger log; - - @Scheduled(cron = "{api_config_cache.cron.expr}") - void cronJobApiconfigCache(ScheduledExecution execution) { - if (this.cache == null) { - log.debug("Api config cache NOT INITIALIZED"); - } else { - log.debugf("Schedule api-config-cache %s", execution.getScheduledFireTime()); - String version = cache.getVersion(); - String newVersion = nodeCacheApi.idV1().getVersion(); - if (version.equals(newVersion)) { - log.debugf("Cache NOT updated. Version [%s]", cache.getVersion()); - } else { - log.debugf("Cache updated. Version [%s] -> [%s]", version, newVersion); - this.cache = nodeCacheApi.cache(null); - } - } - } -} diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java index d50b4f6..ee3741c 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/BasePaymentInfo.java @@ -24,5 +24,8 @@ public class BasePaymentInfo { private String insertedTimestamp; private String updatedTimestamp; private Boolean isOldPaymentModel; - private String nodeId; + private String serviceIdentifier; + + private String positiveBizEvtId; + private String negativeBizEvtId; } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java index 7189ba8..a25d546 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentAttemptInfo.java @@ -15,14 +15,11 @@ public class PaymentAttemptInfo extends BasePaymentAttemptInfo { private String paymentToken; - private Boolean pmReceipt; + private String ccp; + private String pmReceipt; private String paymentMethod; - private String paymentChannel; - private Long stationVersion; + private String touchPoint; private BigDecimal fee; private BigDecimal feeOrganization; - private String bundleId; - private String bundleOrganizationId; - private String applicationDate; - private String transferDate; + } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java index cf080f1..ea9290c 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/models/PaymentInfo.java @@ -14,4 +14,5 @@ public class PaymentInfo extends BasePaymentInfo { private String paymentToken; // for new payment model is payment token and for old payment model is ccp + private String ccp; // for new payment model is payment token and for old payment model is ccp } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java index c57052c..71fb8d2 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/repository/CosmosBizEventClient.java @@ -101,7 +101,7 @@ public CosmosPagedIterable findEventsByCiAndIUVAndCCP( return query(q); } - public CosmosPagedIterable countEventsByCiAndNN( + public CosmosPagedIterable getEventsByCiAndNN( String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo) { List paramList = Arrays.asList( @@ -112,16 +112,16 @@ public CosmosPagedIterable countEventsByCiAndNN( SqlQuerySpec q = new SqlQuerySpec( - "SELECT count(1) as count FROM c where" + "SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.noticeNumber = @noticeNumber" + " and c.timestamp > @from" + " and c.timestamp < @to") .setParameters(paramList); - return queryCount(q); + return query(q); } - public CosmosPagedIterable countEventsByCiAndIUV( + public CosmosPagedIterable getEventsByCiAndIUV( String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo) { List paramList = Arrays.asList( @@ -132,12 +132,12 @@ public CosmosPagedIterable countEventsByCiAndIUV( SqlQuerySpec q = new SqlQuerySpec( - "SELECT count(1) as count FROM c where" + "SELECT * FROM c where" + " c.creditor.idPA = @organizationFiscalCode" + " and c.debtorPosition.iuv = @iuv" + " and c.timestamp > @from" + " and c.timestamp < @to") .setParameters(paramList); - return queryCount(q); + return query(q); } } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java index 1016011..ad98083 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/resources/WorkerResource.java @@ -120,16 +120,16 @@ public Response useCaseSP03_byIUV( schema = @Schema(implementation = ProblemJson.class))) }) @GET - @Path("/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}") + @Path("/{organizationFiscalCode}/noticeNumber/{noticeNumber}/paymentToken/{paymentToken}") public Response useCaseSP04_byIUV_PaymentToken( @PathParam("organizationFiscalCode") @NotNull String organizationFiscalCode, - @PathParam("iuv") @NotNull String iuv, + @PathParam("noticeNumber") @NotNull String noticeNumber, @PathParam("paymentToken") @NotNull String paymentToken, @QueryParam("dateFrom") LocalDate dateFrom, @QueryParam("dateTo") LocalDate dateTo) { return Response.ok( workerService.getAttemptByNoticeNumberAndPaymentToken( - organizationFiscalCode, iuv, paymentToken, dateFrom, dateTo)) + organizationFiscalCode, noticeNumber, paymentToken, dateFrom, dateTo)) .build(); } diff --git a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java index bcc63b4..99e502e 100644 --- a/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java +++ b/src/main/java/it/gov/pagopa/nodetsworker/service/WorkerService.java @@ -1,6 +1,5 @@ package it.gov.pagopa.nodetsworker.service; -import it.gov.pagopa.nodetsworker.Config; import it.gov.pagopa.nodetsworker.exceptions.AppErrorCodeMessageEnum; import it.gov.pagopa.nodetsworker.exceptions.AppException; import it.gov.pagopa.nodetsworker.models.BasePaymentInfo; @@ -10,23 +9,21 @@ import it.gov.pagopa.nodetsworker.repository.CosmosBizEventClient; import it.gov.pagopa.nodetsworker.repository.CosmosNegBizEventClient; import it.gov.pagopa.nodetsworker.repository.ReTableService; -import it.gov.pagopa.nodetsworker.repository.model.Count; import it.gov.pagopa.nodetsworker.repository.model.EventEntity; import it.gov.pagopa.nodetsworker.repository.model.NegativeBizEvent; import it.gov.pagopa.nodetsworker.repository.model.PositiveBizEvent; import it.gov.pagopa.nodetsworker.resources.response.TransactionResponse; -//import it.gov.pagopa.nodetsworker.service.mapper.EventMapper; import it.gov.pagopa.nodetsworker.util.StatusUtil; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import org.jboss.logging.Logger; + import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; -import org.jboss.logging.Logger; -import org.openapi.quarkus.api_config_cache_json.model.ConfigDataV1; @ApplicationScoped public class WorkerService { @@ -36,8 +33,6 @@ public class WorkerService { @Inject Logger log; - @Inject Config configObject; - // @Inject EventMapper eventsMapper; @Inject CosmosBizEventClient positiveBizClient; @@ -45,92 +40,71 @@ public class WorkerService { @Inject ReTableService reTableService; - private PaymentInfo eventToPaymentInfo(ConfigDataV1 config, EventEntity ee) { - String brokerid = - Optional.ofNullable(config.getChannels().get(ee.getCanale())) - .map(s -> s.getBrokerPspCode()) - .orElse(null); + private PaymentInfo eventToPaymentInfo(EventEntity firstEvent,EventEntity lastEvent) { return PaymentInfo.builder() - .pspId(ee.getPsp()) - .nodeId(ee.getServiceIdentifier()) - .channelId(ee.getCanale()) - .brokerPspId(brokerid) - .insertedTimestamp(ee.getInsertedTimestamp()) - .paymentToken(ee.getPaymentToken()!=null?ee.getPaymentToken():ee.getCcp()) - .noticeNumber(ee.getNoticeNumber()) - .iuv(ee.getIuv()) - .organizationFiscalCode(ee.getIdDominio()) - .status(StatusUtil.statoByReStatus(ee.getStatus())) + .pspId(lastEvent.getPsp()) + .serviceIdentifier(lastEvent.getServiceIdentifier()) + .channelId(lastEvent.getCanale()) + .insertedTimestamp(firstEvent.getInsertedTimestamp()) + .updatedTimestamp(lastEvent.getInsertedTimestamp()) + .paymentToken(lastEvent.getPaymentToken()) + .ccp(lastEvent.getCcp()) + .noticeNumber(lastEvent.getNoticeNumber()) + .iuv(lastEvent.getIuv()) + .organizationFiscalCode(lastEvent.getIdDominio()) + .status(StatusUtil.statoByReStatus(lastEvent.getStatus())) .build(); } - private PaymentAttemptInfo eventToPaymentAttemptInfo(ConfigDataV1 config, EventEntity ee) { - String brokerid = - Optional.ofNullable(config.getChannels().get(ee.getCanale())) - .map(s -> s.getBrokerPspCode()) - .orElse(null); + private PaymentAttemptInfo eventToPaymentAttemptInfo(EventEntity firstEvent, EventEntity lastEvent) { return PaymentAttemptInfo.builder() - .pspId(ee.getPsp()) - .nodeId(ee.getServiceIdentifier()) - .channelId(ee.getCanale()) - .brokerPspId(brokerid) - .insertedTimestamp(ee.getInsertedTimestamp()) - .noticeNumber(ee.getNoticeNumber()) - .paymentToken(ee.getPaymentToken()!=null?ee.getPaymentToken():ee.getCcp()) - .iuv(ee.getIuv()) - .organizationFiscalCode(ee.getIdDominio()) - .status(StatusUtil.statoByReStatus(ee.getStatus())) - .stationId(ee.getStazione()) + .pspId(lastEvent.getPsp()) + .serviceIdentifier(lastEvent.getServiceIdentifier()) + .channelId(lastEvent.getCanale()) + .insertedTimestamp(lastEvent.getInsertedTimestamp()) + .updatedTimestamp(lastEvent.getInsertedTimestamp()) + .noticeNumber(lastEvent.getNoticeNumber()) + .paymentToken(lastEvent.getPaymentToken()) + .ccp(lastEvent.getCcp()) + .iuv(lastEvent.getIuv()) + .organizationFiscalCode(lastEvent.getIdDominio()) + .status(StatusUtil.statoByReStatus(lastEvent.getStatus())) + .stationId(lastEvent.getStazione()) .build(); } - private void enrichPaymentAttemptInfo( - ConfigDataV1 config, PaymentAttemptInfo pai, PositiveBizEvent pbe) { - Long stationVersion = - Optional.ofNullable(config.getStations().get(pai.getStationId())) - .map(s -> s.getVersion()) - .orElse(null); + private void enrichPaymentAttemptInfo(PaymentAttemptInfo pai, PositiveBizEvent pbe) { pai.setPaymentToken(pbe.getPaymentInfo().getPaymentToken()); pai.setIsOldPaymentModel(pbe.getDebtorPosition().getModelType().equals("1")); - if (pai.getBrokerPspId() == null) { - pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); - } - pai.setStationVersion(stationVersion); + pai.setBrokerPspId(pbe.getPsp().getIdBrokerPsp()); pai.setAmount(pbe.getPaymentInfo().getAmount()); pai.setFee(pbe.getPaymentInfo().getFee()); pai.setFeeOrganization(pbe.getPaymentInfo().getPrimaryCiIncurredFee()); pai.setPaymentMethod(pbe.getPaymentInfo().getPaymentMethod()); - pai.setPmReceipt(pbe.getTransactionDetails() != null); - pai.setPaymentChannel(pbe.getPaymentInfo().getTouchpoint()); - pai.setBundleId(pbe.getPaymentInfo().getIdBundle()); - pai.setBundleOrganizationId(pbe.getPaymentInfo().getIdCiBundle()); - pai.setApplicationDate(pbe.getPaymentInfo().getApplicationDate()); - pai.setTransferDate(pbe.getPaymentInfo().getTransferDate()); + if("CP".equals(pbe.getPaymentInfo().getPaymentMethod())){ + pai.setPmReceipt(pbe.getTransactionDetails() != null?"sent":"notSent"); + } + pai.setTouchPoint(pbe.getPaymentInfo().getTouchpoint()); + pai.setPositiveBizEvtId(pbe.getId()); } - private void enrichPaymentAttemptInfo( - ConfigDataV1 config, PaymentAttemptInfo pai, NegativeBizEvent nbe) { - Long stationVersion = - Optional.ofNullable(config.getStations().get(pai.getStationId())) - .map(s -> s.getVersion()) - .orElse(null); + private void enrichPaymentAttemptInfo( PaymentAttemptInfo pai, NegativeBizEvent nbe) { pai.setIsOldPaymentModel(nbe.getDebtorPosition().getModelType().equals("1")); - if (pai.getBrokerPspId() == null) { - pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); - } + pai.setBrokerPspId(nbe.getPsp().getIdBrokerPsp()); pai.setPaymentToken(nbe.getPaymentInfo().getPaymentToken()); - pai.setStationVersion(stationVersion); pai.setAmount(nbe.getPaymentInfo().getAmount()); pai.setPaymentMethod(nbe.getPaymentInfo().getPaymentMethod()); - pai.setPmReceipt(nbe.getTransactionDetails() != null); - pai.setPaymentChannel(nbe.getPaymentInfo().getTouchpoint()); + if("CP".equals(nbe.getPaymentInfo().getPaymentMethod())){ + pai.setPmReceipt(nbe.getTransactionDetails() != null?"sent":"notSent"); + } + pai.setTouchPoint(nbe.getPaymentInfo().getTouchpoint()); + pai.setNegativeBizEvtId(nbe.getId()); } public TransactionResponse getInfoByNoticeNumber( String organizationFiscalCode, String noticeNumber, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndNN( dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, noticeNumber); @@ -145,20 +119,22 @@ public TransactionResponse getInfoByNoticeNumber( .map( paymentToken -> { List events = reGroups.get(paymentToken); + EventEntity firstEvent = events.get(0); EventEntity lastEvent = events.get(events.size() - 1); - PaymentInfo pi = eventToPaymentInfo(config, lastEvent); + PaymentInfo pi = eventToPaymentInfo(firstEvent, lastEvent); - Optional pos = + Optional pos = positiveBizClient - .countEventsByCiAndNN( + .getEventsByCiAndNN( lastEvent.getIdDominio(), lastEvent.getNoticeNumber(), dateRequest.getFrom(), dateRequest.getTo()) .stream() .findFirst(); - if (pos.isPresent() && pos.get().getCount() > 0) { + if (pos.isPresent()) { pi.setOutcome(outcomeOK); + pi.setBrokerPspId(pos.get().getPsp().getIdBrokerPsp()); } else { Optional neg = negativeBizClient @@ -171,8 +147,11 @@ public TransactionResponse getInfoByNoticeNumber( .stream() .findFirst(); if (neg.isPresent()) { + pi.setNegativeBizEvtId(neg.get().getId()); + pi.setBrokerPspId(neg.get().getPsp().getIdBrokerPsp()); if (!neg.get().getReAwakable()) { pi.setOutcome(outcomeKO); + } } } @@ -191,7 +170,6 @@ public TransactionResponse getInfoByIUV( String organizationFiscalCode, String iuv, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); List reStorageEvents = reTableService.findReByCiAndIUV( dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, iuv); @@ -206,20 +184,23 @@ public TransactionResponse getInfoByIUV( .map( ccp -> { List events = reGroups.get(ccp); + EventEntity firstEvent = events.get(events.size() - 1); EventEntity lastEvent = events.get(events.size() - 1); - PaymentInfo pi = eventToPaymentInfo(config, lastEvent); + PaymentInfo pi = eventToPaymentInfo(firstEvent, lastEvent); - Optional pos = + Optional pos = positiveBizClient - .countEventsByCiAndIUV( + .getEventsByCiAndIUV( lastEvent.getIdDominio(), lastEvent.getIuv(), dateRequest.getFrom(), dateRequest.getTo()) .stream() .findFirst(); - if (pos.isPresent() && pos.get().getCount() > 0) { + if (pos.isPresent()) { pi.setOutcome(outcomeOK); + pi.setPositiveBizEvtId(pos.get().getId()); + pi.setBrokerPspId(pos.get().getPsp().getIdBrokerPsp()); } else { Optional neg = negativeBizClient @@ -232,6 +213,8 @@ public TransactionResponse getInfoByIUV( .stream() .findFirst(); if (neg.isPresent()) { + pi.setNegativeBizEvtId(neg.get().getId()); + pi.setBrokerPspId(neg.get().getPsp().getIdBrokerPsp()); if (!neg.get().getReAwakable()) { pi.setOutcome(outcomeKO); } @@ -266,9 +249,9 @@ public TransactionResponse getAttemptByNoticeNumberAndPaymentToken( paymentToken); List pais = new ArrayList<>(); if (events.size() > 0) { + EventEntity firstEvent = events.get(0); EventEntity lastEvent = events.get(events.size() - 1); - ConfigDataV1 config = configObject.getClonedCache(); - PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config, lastEvent); + PaymentAttemptInfo pai = eventToPaymentAttemptInfo(firstEvent, lastEvent); Optional pos = positiveBizClient @@ -282,7 +265,7 @@ public TransactionResponse getAttemptByNoticeNumberAndPaymentToken( .findFirst(); if (pos.isPresent()) { pai.setOutcome(outcomeOK); - enrichPaymentAttemptInfo(config, pai, pos.get()); + enrichPaymentAttemptInfo(pai, pos.get()); } else { Optional neg = negativeBizClient @@ -298,7 +281,7 @@ public TransactionResponse getAttemptByNoticeNumberAndPaymentToken( if (!neg.get().getReAwakable()) { pai.setOutcome(outcomeKO); } - enrichPaymentAttemptInfo(config, pai, neg.get()); + enrichPaymentAttemptInfo(pai, neg.get()); } } pais.add(pai); @@ -315,14 +298,14 @@ public TransactionResponse getAttemptByIUVAndCCP( String organizationFiscalCode, String iuv, String ccp, LocalDate dateFrom, LocalDate dateTo) { DateRequest dateRequest = verifyDate(dateFrom, dateTo); - ConfigDataV1 config = configObject.getClonedCache(); List events = reTableService.findReByCiAndIUVAndCCP( dateRequest.getFrom(), dateRequest.getTo(), organizationFiscalCode, iuv, ccp); List pais = new ArrayList<>(); if (events.size() > 0) { + EventEntity firstEvent = events.get(0); EventEntity lastEvent = events.get(events.size() - 1); - PaymentAttemptInfo pai = eventToPaymentAttemptInfo(config, lastEvent); + PaymentAttemptInfo pai = eventToPaymentAttemptInfo(firstEvent, lastEvent); String outcome = null; Optional pos = @@ -333,7 +316,8 @@ public TransactionResponse getAttemptByIUVAndCCP( .findFirst(); if (pos.isPresent()) { pai.setOutcome(outcomeOK); - enrichPaymentAttemptInfo(config, pai, pos.get()); + pai.setBrokerPspId(pos.get().getPsp().getIdPsp()); + enrichPaymentAttemptInfo( pai, pos.get()); } else { Optional neg = negativeBizClient @@ -342,10 +326,11 @@ public TransactionResponse getAttemptByIUVAndCCP( .stream() .findFirst(); if (neg.isPresent()) { + pai.setBrokerPspId(neg.get().getPsp().getIdBrokerPsp()); if (!neg.get().getReAwakable()) { pai.setOutcome(outcomeKO); } - enrichPaymentAttemptInfo(config, pai, neg.get()); + enrichPaymentAttemptInfo(pai, neg.get()); } } pais.add(pai); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e863f13..3da799e 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -85,7 +85,7 @@ re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING:${mockserver.a ################### ## ADAPTER API CONFIG CACHE ################### -quarkus.rest-client.logging.scope=request-response +#quarkus.rest-client.logging.scope=request-response #quarkus.rest-client.logging.body-limit=1024 #quarkus.log.category."org.jboss.resteasy.reactive.client.logging".level=DEBUG diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java index 5e3422b..9b98f4f 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp03Test.java @@ -1,18 +1,11 @@ package it.gov.pagopa.nodetsworker.resources; -import static io.restassured.RestAssured.given; -import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; - import com.azure.cosmos.CosmosClient; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.models.CosmosItemRequestOptions; import com.azure.data.tables.TableClient; import com.azure.data.tables.TableServiceClient; import com.azure.data.tables.TableServiceClientBuilder; -import io.quarkiverse.mockserver.test.MockServerTestResource; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; @@ -27,16 +20,21 @@ import it.gov.pagopa.nodetsworker.util.AzuriteResource; import it.gov.pagopa.nodetsworker.util.CosmosResource; import it.gov.pagopa.nodetsworker.util.Util; -import java.time.Instant; -import java.time.LocalDate; -import java.util.Random; import lombok.SneakyThrows; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.time.Instant; +import java.time.LocalDate; + +import static io.restassured.RestAssured.given; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; + @QuarkusTest -@QuarkusTestResource(MockServerTestResource.class) @QuarkusTestResource(AzuriteResource.class) @QuarkusTestResource(CosmosResource.class) class Sp03Test { diff --git a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java index 334a2c2..6a92711 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/resources/Sp04Test.java @@ -1,18 +1,11 @@ package it.gov.pagopa.nodetsworker.resources; -import static io.restassured.RestAssured.given; -import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; - import com.azure.cosmos.CosmosClient; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.models.CosmosItemRequestOptions; import com.azure.data.tables.TableClient; import com.azure.data.tables.TableServiceClient; import com.azure.data.tables.TableServiceClientBuilder; -import io.quarkiverse.mockserver.test.MockServerTestResource; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.common.mapper.TypeRef; @@ -24,16 +17,22 @@ import it.gov.pagopa.nodetsworker.util.AzuriteResource; import it.gov.pagopa.nodetsworker.util.CosmosResource; import it.gov.pagopa.nodetsworker.util.Util; -import java.time.Instant; -import java.time.LocalDate; -import java.util.Random; import lombok.SneakyThrows; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.time.Instant; +import java.time.LocalDate; +import java.util.Random; + +import static io.restassured.RestAssured.given; +import static it.gov.pagopa.nodetsworker.util.AppConstantTestHelper.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; + @QuarkusTest -@QuarkusTestResource(MockServerTestResource.class) @QuarkusTestResource(AzuriteResource.class) @QuarkusTestResource(CosmosResource.class) class Sp04Test { diff --git a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java index 43f454c..8e0b1a6 100644 --- a/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java +++ b/src/test/java/it/gov/pagopa/nodetsworker/util/AppConstantTestHelper.java @@ -13,7 +13,7 @@ public class AppConstantTestHelper { public static final String SP03_NN = "/organizations/%s/noticeNumber/%s"; public static final String SP03_IUV = "/organizations/%s/iuv/%s"; - public static final String SP04_NN = "/organizations/%s/iuv/%s/paymentToken/%s"; + public static final String SP04_NN = "/organizations/%s/noticeNumber/%s/paymentToken/%s"; public static final String SP04_IUV = "/organizations/%s/iuv/%s/ccp/%s"; public static final String PA_CODE = "12345678900"; @@ -47,7 +47,7 @@ public static final PositiveBizEvent newPositiveBiz(String pa, String noticeNumb PositiveBizEvent.builder() .id(UUID.randomUUID().toString()) .timestamp(Util.toMillis(LocalDateTime.now())) - .psp(Psp.builder().psp("pspTest").idChannel("canaleTest").build()) + .psp(Psp.builder().idBrokerPsp("intTest").psp("pspTest").idChannel("canaleTest").build()) .creditor(Creditor.builder().idPA(pa).build()) .debtorPosition( DebtorPosition.builder().modelType("1").iuv(iuv).noticeNumber(noticeNumber).build()) @@ -66,7 +66,9 @@ public static final NegativeBizEvent newNegBiz( NegativeBizEvent.builder() .id(UUID.randomUUID().toString()) .timestamp(Util.toMillis(LocalDateTime.now())) - .creditor(Creditor.builder().idPA(pa).build()) + .psp(Psp.builder().idBrokerPsp("intTest").psp("pspTest").idChannel("canaleTest").build()) + + .creditor(Creditor.builder().idPA(pa).build()) .debtorPosition( DebtorPosition.builder().iuv(iuv).noticeNumber(noticeNumber).modelType("1").build()) .paymentInfo( diff --git a/src/test/resources/mockserver.properties b/src/test/resources/mockserver.properties deleted file mode 100644 index 8629897..0000000 --- a/src/test/resources/mockserver.properties +++ /dev/null @@ -1,3 +0,0 @@ -mockserver.initializationJsonPath=/mockserver/*.json -# watch changes in the file -mockserver.watchInitializationJson=true \ No newline at end of file diff --git a/src/test/resources/mockserver/cache.json b/src/test/resources/mockserver/cache.json deleted file mode 100644 index 0a27c6a..0000000 --- a/src/test/resources/mockserver/cache.json +++ /dev/null @@ -1,1701 +0,0 @@ -[{ - "id": "1", - "httpRequest": { - "path": "/stakeholders/node/cache/schemas/v1/id" - }, - "httpResponse": { - "body": { - "type": "JSON", - "json": { - "version": "15807041712995048" - }, - "contentType": "application/json" - } - } -}, - { - "id": "2", - "httpRequest": { - "path": "/stakeholders/node/cache/schemas/v1" - }, - "httpResponse": { - "body": { - "type": "JSON", - "json": { - "version": "15807041712995048", - "creditorInstitutions": { - "12345678900": { - "creditor_institution_code": "12345678900", - "enabled": true, - "business_name": "paStress80", - "description": null, - "address": { - "location": null, - "city": null, - "zip_code": null, - "country_code": null, - "tax_domicile": null - }, - "psp_payment": true, - "reporting_ftp": false, - "reporting_zip": false - }, - "00987654321": { - "creditor_institution_code": "00987654321", - "enabled": false, - "business_name": "paStress80", - "description": null, - "address": { - "location": null, - "city": null, - "zip_code": null, - "country_code": null, - "tax_domicile": null - }, - "psp_payment": true, - "reporting_ftp": false, - "reporting_zip": false - } - }, - "creditorInstitutionBrokers": { - "intPaStress14": { - "broker_code": "intPaStress14", - "enabled": true, - "description": "intPaStress14", - "extended_fault_bean": false - } - }, - "stations": { - "77777777777_01": { - "station_code": "77777777777_01", - "enabled": true, - "version": 2, - "connection": { - "protocol": "HTTPS", - "ip": "api.dev.platform.pagopa.it", - "port": 443 - } - } - }, - "creditorInstitutionStations": { - "11_15151515151_null_null_null": { - "creditor_institution_code": "15151515151", - "station_code": "11", - "application_code": null, - "aux_digit": null, - "segregation_code": null, - "mod4": false, - "broadcast": false, - "primitive_version": 1, - "spontaneous_payment": false - } - }, - "encodings": null, - "creditorInstitutionEncodings": null, - "ibans": null, - "creditorInstitutionInformations": null, - "psps": { - "pspTest": { - "psp_code": "pspTest", - "enabled": true, - "description": "pspStress1", - "business_name": "pspStress1", - "abi": "TBD", - "bic": "TBD", - "my_bank_code": null, - "digital_stamp": false, - "agid_psp": false, - "tax_code": "CFpspStress1", - "vat_number": null - }, - "pspTest2": { - "psp_code": "pspTest2", - "enabled": true, - "description": "pspStress1", - "business_name": "pspStress1", - "abi": "TBD", - "bic": "TBD", - "my_bank_code": null, - "digital_stamp": false, - "agid_psp": false, - "tax_code": "CFpspStress1", - "vat_number": null - }, - "pspNotEnabled": { - "psp_code": "pspNotEnabled", - "enabled": false, - "description": "pspStress1", - "business_name": "pspStress1", - "abi": "TBD", - "bic": "TBD", - "my_bank_code": null, - "digital_stamp": false, - "agid_psp": false, - "tax_code": "CFpspStress1", - "vat_number": null - } - }, - "pspBrokers": { - "intTest": { - "broker_psp_code": "intTest", - "description": "Intermediario per mybankSvil", - "enabled": true, - "extended_fault_bean": false - }, - "intTest2": { - "broker_psp_code": "intTest2", - "description": "Intermediario per mybankSvil", - "enabled": true, - "extended_fault_bean": false - }, - "intNotEnabled": { - "broker_psp_code": "intNotEnabled", - "description": "Intermediario per mybankSvil", - "enabled": false, - "extended_fault_bean": false - } - }, - "paymentTypes": { - "AD": { - "payment_type": "AD", - "description": "Addebito diretto" - }, - "JIF": { - "payment_type": "JIF", - "description": "Jiffy" - }, - "CP": { - "payment_type": "CP", - "description": "Carta di pagamento " - }, - "DEVPAY": { - "payment_type": "DEVPAY", - "description": "Develop PAY" - }, - "PPAL": { - "payment_type": "PPAL", - "description": "PayPal" - }, - "STP": { - "payment_type": "STP", - "description": "Satispay PROVA" - }, - "BP": { - "payment_type": "BP", - "description": "Bollettino postale " - }, - "MYBK": { - "payment_type": "MYBK", - "description": "MyBank" - }, - "TPAY": { - "payment_type": "TPAY", - "description": "Pagamento appIO di test aggiuntivo" - }, - "BBT": { - "payment_type": "BBT", - "description": "Bonifico bancario telematico" - }, - "BPAY": { - "payment_type": "BPAY", - "description": "Bancomat Pay" - }, - "OBEP": { - "payment_type": "OBEP", - "description": "Online Banking Electronic Payment " - }, - "PPAY": { - "payment_type": "PPAY", - "description": "PostePay" - }, - "PO": { - "payment_type": "PO", - "description": "Pagamento attivato presso PSP " - } - }, - "pspChannelPaymentTypes": { - "pspTest_canaleTest_PAYPAL": { - "psp_code": "pspTest", - "channel_code": "canaleTest", - "payment_type": "PAYPAL" - } - }, - "plugins": null, - "pspInformationTemplates": null, - "pspInformations": null, - "channels": { - "canaleTest": { - "channel_code": "canaleTest", - "description": null, - "enabled": true, - "password": null, - "broker_psp_code": "intTest", - "connection": { - "protocol": "HTTPS", - "ip": "api.dev.platform.pagopa.it", - "port": 443 - } - }, - "canaleNotEnabled": { - "channel_code": "canaleNotEnabled", - "description": null, - "enabled": false, - "password": null, - "broker_psp_code": "intTest", - "connection": { - "protocol": "HTTPS", - "ip": "api.dev.platform.pagopa.it", - "port": 443 - } - } - }, - "cdsServices": null, - "cdsSubjects": null, - "cdsSubjectServices": null, - "cdsCategories": null, - "configurations": { - "GLOBAL-idPspCD": { - "category": "GLOBAL", - "key": "idPspCD", - "value": "AGID_01", - "description": "id PSP Cittadinanza Digitale" - }, - "GLOBAL-scheduler.sendPaymentResultPollerMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.sendPaymentResultPollerMaxRetry", - "value": "5", - "description": "Numero massimo di tentativi di re-invio sendPaymentResult al PM" - }, - "GLOBAL-scheduler.jobName_situazioneOrdineCheck.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_situazioneOrdineCheck.enabled", - "value": "true", - "description": "Job enabled (true/false) - da P_READY a P_WAITING" - }, - "GLOBAL-scheduler.jobName_situazioneOrdineCheck.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_situazioneOrdineCheck.jobDescription", - "value": "Description", - "description": "processo di recovery che parte dal WFESP per tutte le redirect in stato P_READY" - }, - "info-quadr-commissioneCaricoPa.template.sender.name.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPa.template.sender.name.mail", - "value": "PPT", - "description": null - }, - "GLOBAL-scheduler.paAttivaRptMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.paAttivaRptMaxRetry", - "value": "5", - "description": "pa attiva Rpt max retry" - }, - "info-quadr-commissioneCaricoPa.template.sender.address.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPa.template.sender.address.mail", - "value": "prova@prova.com", - "description": null - }, - "GLOBAL-scheduler.jobName_pspRetryAckNegative.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspRetryAckNegative.cronExpression", - "value": "0/30 * * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-istitutoAttestante.civicoAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.civicoAttestante", - "value": "370", - "description": "civicoAttestante" - }, - "GLOBAL-chiediSceltaWisp.tipoVersamento": { - "category": "GLOBAL", - "key": "chiediSceltaWisp.tipoVersamento", - "value": "BBT", - "description": "tipo versamento restituito durante la chiedi scelta Wisp" - }, - "GLOBAL-scheduler.jobName_paRetryPaInviaRtNegative.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_paRetryPaInviaRtNegative.enabled", - "value": "false", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.retryPspSendPayment": { - "category": "GLOBAL", - "key": "scheduler.retryPspSendPayment", - "value": "5", - "description": "Retry psp sent payment max retries" - }, - "GLOBAL-timeout.pspInviaCarrelloRPT": { - "category": "GLOBAL", - "key": "timeout.pspInviaCarrelloRPT", - "value": "TIMEOUT_B", - "description": "Tipo timeout" - }, - "GLOBAL-istitutoAttestante.indirizzoAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.indirizzoAttestante", - "value": "Piazza Colonna", - "description": "indirizzoAttestante" - }, - "GLOBAL-scheduler.jobName_rtPullRecoveryPush.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_rtPullRecoveryPush.cronExpression", - "value": "0 0 0/1 ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-default_durata_estensione_token_IO": { - "category": "GLOBAL", - "key": "default_durata_estensione_token_IO", - "value": "1000", - "description": " default millisecondi validità token IO estesa" - }, - "GLOBAL-scheduler.jobName_rtPullRecoveryPush.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_rtPullRecoveryPush.jobDescription", - "value": "Description", - "description": "Description" - }, - "GLOBAL-scheduler.jobName_mod3CancelV1.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3CancelV1.enabled", - "value": "false", - "description": "Job enabled (true/false)" - }, - "rpt-invia-patch.ministeroDiGiustizia.idDominio": { - "category": "rpt-invia", - "key": "patch.ministeroDiGiustizia.idDominio", - "value": "01386030488", - "description": "Indicare qui idDominio della PA MdG sulle cui RPT si deve applicare la trasformazione. Eventuali identificativi devono essere separati dal carattere \",\" (virgola)" - }, - "GLOBAL-scheduler.jobName_pspRetryAckNegative.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspRetryAckNegative.jobDescription", - "value": "Description", - "description": "Description" - }, - "rpt-modello4-descrizioneServizioBolloAuto": { - "category": "rpt-modello4", - "key": "descrizioneServizioBolloAuto", - "value": "Tassa automobilistica", - "description": "-" - }, - "info-quadr-smtp.test.sia": { - "category": "info-quadr", - "key": "smtp.test.sia", - "value": "true", - "description": "set true or false se si usa smtp server test" - }, - "GLOBAL-httpmethod.wfesp.psp2wfesp": { - "category": "GLOBAL", - "key": "httpmethod.wfesp.psp2wfesp", - "value": "esito", - "description": null - }, - "GLOBAL-scheduler.jobName_situazioneOrdine.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_situazioneOrdine.jobDescription", - "value": "Description", - "description": "processo di recovery che parte dal WFESP" - }, - "GLOBAL-scheduler.jobName_positionRetrySendPaymentResult.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_positionRetrySendPaymentResult.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-payment_activation_validity_minutes": { - "category": "GLOBAL", - "key": "payment_activation_validity_minutes", - "value": "10", - "description": "Minuti di validita chiave idempotenza" - }, - "GLOBAL-scheduler.suspendAllJobs": { - "category": "GLOBAL", - "key": "scheduler.suspendAllJobs", - "value": "false", - "description": "Suspend all jobs for release" - }, - "GLOBAL-scheduler.pspChiediAvanzamentoRptPollerMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.pspChiediAvanzamentoRptPollerMaxRetry", - "value": "1", - "description": "numero massimo di tentativi di invio RPT incomplete verso il PSP" - }, - "GLOBAL-scheduler.jobName_pspSendPayment.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspSendPayment.jobDescription", - "value": "Description", - "description": "psp send payment" - }, - "GLOBAL-istitutoAttestante.codiceUnitOperAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.codiceUnitOperAttestante", - "value": "n/a", - "description": "codiceUnitOperAttestante" - }, - "GLOBAL-scheduler.jobName_generaRendicontazioneBollo.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_generaRendicontazioneBollo.jobDescription", - "value": "Description", - "description": "Description" - }, - "GLOBAL-istitutoAttestante.nazioneAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.nazioneAttestante", - "value": "IT", - "description": "nazioneAttestante" - }, - "FATTURAZIONI-tipoVersamento.PPAL": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.PPAL", - "value": "0;0;0;0;1;0;0;0", - "description": "codifica csv tipo versamento PPAL" - }, - "GLOBAL-scheduler.jobName_pspChiediListaAndChiediRt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspChiediListaAndChiediRt.jobDescription", - "value": "Description", - "description": "Description" - }, - "GLOBAL-scheduler.jobName_annullamentoRptMaiRichiesteDaPm.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_annullamentoRptMaiRichiesteDaPm.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-timeout.paaAttivaRPT": { - "category": "GLOBAL", - "key": "timeout.paaAttivaRPT", - "value": "TIMEOUT_A", - "description": "Tipo timeout" - }, - "GLOBAL-timeout.pspChiediRT": { - "category": "GLOBAL", - "key": "timeout.pspChiediRT", - "value": "TIMEOUT_C", - "description": "Tipo timeout" - }, - "GLOBAL-scheduler.jobName_pspChiediListaAndChiediRt.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspChiediListaAndChiediRt.cronExpression", - "value": "0/30 * * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-scheduler.jobName_annullamentoRptMaiRichiesteDaPm.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_annullamentoRptMaiRichiesteDaPm.jobDescription", - "value": "Description", - "description": "Description" - }, - "GLOBAL-idIntPspMod3New": { - "category": "GLOBAL", - "key": "idIntPspMod3New", - "value": "15376371009", - "description": "idIntPspMod3New" - }, - "GLOBAL-scheduler.rptExpiringDays": { - "category": "GLOBAL", - "key": "scheduler.rptExpiringDays", - "value": "8", - "description": "giorni per cui non si sono completate RPT" - }, - "GLOBAL-timeout.pspInviaCarrelloRPTCarte": { - "category": "GLOBAL", - "key": "timeout.pspInviaCarrelloRPTCarte", - "value": "TIMEOUT_B", - "description": "Tipo timeout" - }, - "GLOBAL-scheduler.jobName_mod3RiconciliazioneRpt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3RiconciliazioneRpt.jobDescription", - "value": "Description", - "description": "Riconciliazione rpt" - }, - "GLOBAL-scheduler.annullamentoRptMaiRichiesteDaPmPollerMinutesToBack": { - "category": "GLOBAL", - "key": "scheduler.annullamentoRptMaiRichiesteDaPmPollerMinutesToBack", - "value": "1", - "description": "totale minuti per cui una richiesta non è mai stata processata da WISP2" - }, - "info-quadr-smtp.password": { - "category": "info-quadr", - "key": "smtp.password", - "value": "pda", - "description": null - }, - "rpt-annulla-algoritmoFirmaRT": { - "category": "rpt-annulla", - "key": "algoritmoFirmaRT", - "value": "SHA256withRSA", - "description": null - }, - "GLOBAL-scheduler.jobName_refreshConfiguration.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_refreshConfiguration.jobDescription", - "value": "60", - "description": "Description" - }, - "GLOBAL-uri.wfesp": { - "category": "GLOBAL", - "key": "uri.wfesp", - "value": "https://api.dev.platform.pagopa.it/wfesp-ndp/service/v1/redirect", - "description": "Redirect wfesp" - }, - "GLOBAL-scheduler.jobName_refreshConfiguration.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_refreshConfiguration.cronExpression", - "value": "0 * 0 ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-scheduler.situazioneOrdineCheckMinutesToFilter": { - "category": "GLOBAL", - "key": "scheduler.situazioneOrdineCheckMinutesToFilter", - "value": "30", - "description": " indica i minuti che devono passare per un ordine prima di eseguire la Situazione Ordine - job \"check\"" - }, - "GLOBAL-scheduler.jobName_pspNotificaCancellazione.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspNotificaCancellazione.jobDescription", - "value": "Description", - "description": "Description" - }, - "GLOBAL-closePaymentV2DenyListTipoVersamento": { - "category": "GLOBAL", - "key": "closePaymentV2DenyListTipoVersamento", - "value": "AD,BBT,BP,OBEP,PO,JIF,MYBK,BPAY,PPAL", - "description": "tipi versamento non accettati per closePaymentV2 per pagamenti IO/Checkout" - }, - "info-quadr-commissioneCaricoPsp.template.sender.address.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.template.sender.address.mail", - "value": "prova@prova.com", - "description": null - }, - "info-quadr-smtp.port": { - "category": "info-quadr", - "key": "smtp.port", - "value": "1026", - "description": null - }, - "GLOBAL-scheduler.jobName_annullamentoRptMaiRichiesteDaPm.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_annullamentoRptMaiRichiesteDaPm.cronExpression", - "value": "0 0/2 * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-validate_output": { - "category": "GLOBAL", - "key": "validate_output", - "value": "true", - "description": "Validazione XSD output Bundle" - }, - "FATTURAZIONI-tipoVersamento.POS": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.POS", - "value": "0;0;0;0;0;0;0;0", - "description": "codifica csv tipo versamento POS" - }, - "GLOBAL-scheduler.jobName_situazioneOrdineCheck.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_situazioneOrdineCheck.cronExpression", - "value": "*/1 * * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "info-quadr-commissioneCaricoPa.noData.message": { - "category": "info-quadr", - "key": "commissioneCaricoPa.noData.message", - "value": "Nessun dato disponibile per il mese di riferimento", - "description": null - }, - "GLOBAL-scheduler.jobName_paInviaRtRecovery.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_paInviaRtRecovery.enabled", - "value": "true", - "description": "paInviaRtRecovery enabled" - }, - "GLOBAL-scheduler.jobName_pspChiediAvanzamentoRpt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspChiediAvanzamentoRpt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.pspRetryNotificheCancellazioneRptPollerMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.pspRetryNotificheCancellazioneRptPollerMaxRetry", - "value": "3", - "description": "numero massimo di tentativi di re-invio notifiche cancellazione al PSP" - }, - "GLOBAL-timeout.paGetPayment": { - "category": "GLOBAL", - "key": "timeout.paGetPayment", - "value": "TIMEOUT_A", - "description": "timeout" - }, - "GLOBAL-scheduler.jobName_generaRendicontazioneBollo.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_generaRendicontazioneBollo.cronExpression", - "value": "0 0 0 ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-intPspCD": { - "category": "GLOBAL", - "key": "intPspCD", - "value": "97735020584", - "description": "identificativo intermediario PSP Cittadinanza Digitale" - }, - "GLOBAL-scheduler.jobName_paSendRt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_paSendRt.jobDescription", - "value": "Description", - "description": "invio receipt verso Stazioni PA" - }, - "GLOBAL-GLOBAL-mod3_inizio": { - "category": "GLOBAL", - "key": "GLOBAL-mod3_inizio", - "value": "2021-01-01", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.jobName_ftpUpload.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_ftpUpload.jobDescription", - "value": "Description", - "description": "Description" - }, - "rpt-modello4-dataInizioValiditaBolloAuto": { - "category": "rpt-modello4", - "key": "dataInizioValiditaBolloAuto", - "value": "2017-04-30T00:00:00", - "description": "-" - }, - "GLOBAL-idCanaleAGID": { - "category": "GLOBAL", - "key": "idCanaleAGID", - "value": "97735020584_02", - "description": "identificativo canale AGID" - }, - "GLOBAL-idPspMod3New": { - "category": "GLOBAL", - "key": "idPspMod3New", - "value": "15376371009", - "description": "idPspMod3New" - }, - "GLOBAL-scheduler.jobName_pspRetryNotificheCancellazioneRpt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspRetryNotificheCancellazioneRpt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "FATTURAZIONI-tipoVersamento.BP": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.BP", - "value": "0;1;0;0;0;0;0;0", - "description": "codifica csv tipo versamento BP" - }, - "GLOBAL-scheduler.jobName_mod3UpdateNotifiedPositionPayment.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3UpdateNotifiedPositionPayment.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "info-quadr-commissioneCaricoPsp.pdf.aggregato.header": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.pdf.aggregato.header", - "value": "Tabella aggregato versamenti", - "description": null - }, - "rpt-modello4-aciDescrizione": { - "category": "rpt-modello4", - "key": "aciDescrizione", - "value": "Automobile Club d italia", - "description": "descrizione Automobile Club Italia" - }, - "GLOBAL-timeout.pspNotifyPayment": { - "category": "GLOBAL", - "key": "timeout.pspNotifyPayment", - "value": "TIMEOUT_A", - "description": "timeout" - }, - "GLOBAL-timeout.pspNotificaCancellazioneRPT": { - "category": "GLOBAL", - "key": "timeout.pspNotificaCancellazioneRPT", - "value": "TIMEOUT_C", - "description": "Tipo timeout" - }, - "GLOBAL-scheduler.jobName_ftpUpload.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_ftpUpload.cronExpression", - "value": "0 0/1 * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-scheduler.jobName_pspSendPayment.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspSendPayment.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "info-quadr-commissioneCaricoPsp.pdf.aggregato.footer": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.pdf.aggregato.footer", - "value": "n.a.", - "description": null - }, - "info-wisp-chiediListaPSP.listaPspLisPay": { - "category": "info-wisp", - "key": "chiediListaPSP.listaPspLisPay", - "value": "BIC36019", - "description": "id PSP LisPay,divisi da virgola" - }, - "FATTURAZIONI-tipoVersamento.JIF": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.JIF", - "value": "0;0;0;0;0;0;1;0", - "description": "codifica csv tipo versamento JIF" - }, - "GLOBAL-inviaCarrelloRpt.maxNumRptInCartMultibeneficiario": { - "category": "GLOBAL", - "key": "inviaCarrelloRpt.maxNumRptInCartMultibeneficiario", - "value": "2", - "description": null - }, - "GLOBAL-scheduler.jobName_pspNotificaCancellazione.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspNotificaCancellazione.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "info-quadr-commissioneCaricoPsp.template.sender.name.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.template.sender.name.mail", - "value": "PPT", - "description": null - }, - "GLOBAL-idempotency.outcome.ok.duration.days": { - "category": "GLOBAL", - "key": "idempotency.outcome.ok.duration.days", - "value": "2", - "description": "cache validity days outcome ok" - }, - "GLOBAL-mod3_inizio": { - "category": "GLOBAL", - "key": "mod3_inizio", - "value": "2021-01-01", - "description": "Job enabled (true/false)" - }, - "FATTURAZIONI-tipoVersamento.CP": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.CP", - "value": "0;0;0;0;1;0;0;0", - "description": "codifica csv tipo versamento CP" - }, - "GLOBAL-ccpRandomTraduttore": { - "category": "GLOBAL", - "key": "ccpRandomTraduttore", - "value": "true", - "description": "popolare il CCP nella paaVerificaRPT generata dal traduttore con NMP_[random 10 numeri]" - }, - "rpt-modello4-xsdRiferimentoBolloAuto": { - "category": "rpt-modello4", - "key": "xsdRiferimentoBolloAuto", - "value": "TassaAutomobilistica_1_0_0.xsd", - "description": "-" - }, - "GLOBAL-scheduler.jobName_mod3Cancel.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3Cancel.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.jobName_mod3Cancel.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3Cancel.jobDescription", - "value": "Description", - "description": "cancellazione position payment con token scaduti modello 3" - }, - "rpt-invia-inviaCarrelloRpt.maxNumRptInCart": { - "category": "rpt-invia", - "key": "inviaCarrelloRpt.maxNumRptInCart", - "value": "5", - "description": "Numero massimo di elementi nel Carrello" - }, - "rendicontazioni-bollo.intermediario.CAPDelDomicilioFiscale": { - "category": "rendicontazioni", - "key": "bollo.intermediario.CAPDelDomicilioFiscale", - "value": "20147", - "description": "Dati dell'intermediario della trasmissione/ C.A.P. domicilio fiscale" - }, - "GLOBAL-timeout.paSendRT": { - "category": "GLOBAL", - "key": "timeout.paSendRT", - "value": "TIMEOUT_B", - "description": "timeout" - }, - "GLOBAL-scheduler.jobName_pspRetryNotificheCancellazioneRpt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspRetryNotificheCancellazioneRpt.jobDescription", - "value": "Description", - "description": "Description" - }, - "GLOBAL-istitutoAttestante.capAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.capAttestante", - "value": "00187", - "description": "capAttestante" - }, - "info-quadr-commissioneCaricoPsp.template.subject.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.template.subject.mail", - "value": "Report commissioniCaricoPsp", - "description": null - }, - "rendicontazioni-bollo.intermediario.comuneDomicilioFiscale": { - "category": "rendicontazioni", - "key": "bollo.intermediario.comuneDomicilioFiscale", - "value": "Milano", - "description": "Dati dell'intermediario della trasmissione/ Comune domicilio fiscale" - }, - "GLOBAL-uri.wallet": { - "category": "GLOBAL", - "key": "uri.wallet", - "value": "https://acardste.vaservices.eu:1443/wallet/welcome", - "description": null - }, - "GLOBAL-timeout.paDemandPaymentNotice": { - "category": "GLOBAL", - "key": "timeout.paDemandPaymentNotice", - "value": "TIMEOUT_A", - "description": "Tipo timeout" - }, - "GLOBAL-scheduler.jobName_rtPullRecoveryPush.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_rtPullRecoveryPush.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "info-wisp-chiediListaPSP.outputJsonValid": { - "category": "info-wisp", - "key": "chiediListaPSP.outputJsonValid", - "value": "true", - "description": null - }, - "GLOBAL-scheduler.jobName_mod3RiconciliazioneRt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3RiconciliazioneRt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-istitutoAttestante.localitaAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.localitaAttestante", - "value": "Roma", - "description": "localitaAttestante" - }, - "GLOBAL-scheduler.paSendRtMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.paSendRtMaxRetry", - "value": "1", - "description": "pa Send Rt max retry" - }, - "GLOBAL-istitutoAttestante.denominazioneAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.denominazioneAttestante", - "value": "PagoPA S.p.A.", - "description": "denominazioneAttestante" - }, - "rendicontazioni-bollo.intermediario.indirizzoFrazioneViaENumeroCivicoDelDomicilioFiscale": { - "category": "rendicontazioni", - "key": "bollo.intermediario.indirizzoFrazioneViaENumeroCivicoDelDomicilioFiscale", - "value": "Via Gonin, 36", - "description": "Dati dell'intermediario della trasmissione/ Indirizzo, frazione, via e numero civico del domicilio fiscale" - }, - "GLOBAL-scheduler.jobName_paRetryAttivaRpt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_paRetryAttivaRpt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-timeout.paaInviaRT.push": { - "category": "GLOBAL", - "key": "timeout.paaInviaRT.push", - "value": "TIMEOUT_B", - "description": "Tipo timeout" - }, - "Z7HuDfyuFpvmg6KBF3i6FQ17SA6W0FiiC2F-conf-key": { - "category": "Z7HuDfyuFpvmg6KBF3i6FQ17SA6W0FiiC2F", - "key": "conf-key", - "value": "test value", - "description": "this is a test" - }, - "GLOBAL-scheduler.jobName_generaRendicontazioneBollo.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_generaRendicontazioneBollo.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "rendicontazioni-bollo.intermediario.denominazione": { - "category": "rendicontazioni", - "key": "bollo.intermediario.denominazione", - "value": "SIA S.p.A.", - "description": "Dati dell'intermediario della trasmissione/ Denominazione" - }, - "GLOBAL-timeout.pspInviaAckRT": { - "category": "GLOBAL", - "key": "timeout.pspInviaAckRT", - "value": "TIMEOUT_C", - "description": "Tipo timeout" - }, - "GLOBAL-scheduler.jobName_cancelIOPayment.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_cancelIOPayment.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.jobName_pspRetryNotificheCancellazioneRpt.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspRetryNotificheCancellazioneRpt.cronExpression", - "value": "0 0 * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "rendicontazioni-bollo.mittente.codiceFiscale": { - "category": "rendicontazioni", - "key": "bollo.mittente.codiceFiscale", - "value": "15376371009", - "description": null - }, - "GLOBAL-scheduler.jobName_idempotencyCacheClean.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_idempotencyCacheClean.enabled", - "value": "false", - "description": "jobName_idempotencyCacheClean enabled/disabled" - }, - "FATTURAZIONI-tipoVersamento.AD": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.AD", - "value": "0;0;1;0;0;0;0;0", - "description": "codifica csv tipo versamento AD" - }, - "GLOBAL-timeout.paaInviaRT.pull": { - "category": "GLOBAL", - "key": "timeout.paaInviaRT.pull", - "value": "TIMEOUT_C", - "description": "Tipo timeout" - }, - "GLOBAL-verificabollettino.validity.minutes": { - "category": "GLOBAL", - "key": "verificabollettino.validity.minutes", - "value": "1", - "description": "validità verifica bollettino" - }, - "GLOBAL-scheduler.pspRetryAckNegativePollerMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.pspRetryAckNegativePollerMaxRetry", - "value": "1", - "description": "numero massimo di tentativi di re-invio ACK al PSP" - }, - "GLOBAL-idPspCheckout": { - "category": "GLOBAL", - "key": "idPspCheckout", - "value": "TBD", - "description": "id PSP Checkout" - }, - "GLOBAL-intPspAGID": { - "category": "GLOBAL", - "key": "intPspAGID", - "value": "97735020584", - "description": "identificativo intermediario PSP AGID" - }, - "info-quadr-commissioneCaricoPa.pdf.dettaglio.footer": { - "category": "info-quadr", - "key": "commissioneCaricoPa.pdf.dettaglio.footer", - "value": "n.a.", - "description": null - }, - "GLOBAL-inviaCarrelloRpt.maxVersamentiInSecondRptMultibeneficiario": { - "category": "GLOBAL", - "key": "inviaCarrelloRpt.maxVersamentiInSecondRptMultibeneficiario", - "value": "1", - "description": null - }, - "GLOBAL-scheduler.jobName_paInviaRt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_paInviaRt.jobDescription", - "value": "Description", - "description": "Description" - }, - "GLOBAL-flag.chiediInfoPagamento.useNewField": { - "category": "GLOBAL", - "key": "flag.chiediInfoPagamento.useNewField", - "value": "true", - "description": "Flag che indica se il PM dovrà ricevere i nuovi campi di infoPagamento" - }, - "GLOBAL-idCanaleMod3New": { - "category": "GLOBAL", - "key": "idCanaleMod3New", - "value": "15376371009_01", - "description": "idCanaleMod3New" - }, - "GLOBAL-scheduler.jobName_situazioneOrdine.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_situazioneOrdine.enabled", - "value": "true", - "description": "Job enabled (true/false) - sitOrd per quelle in P_WAITING" - }, - "FATTURAZIONI-tipoVersamento.BPAY": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.BPAY", - "value": "0;0;0;0;1;0;0;0", - "description": "codifica csv tipo versamento BPAY" - }, - "rpt-modello4-idServizioBolloAuto": { - "category": "rpt-modello4", - "key": "idServizioBolloAuto", - "value": "00001", - "description": "-" - }, - "GLOBAL-azureSdkClientReEventEnabled": { - "category": "GLOBAL", - "key": "azureSdkClientReEventEnabled", - "value": "true", - "description": "abilitazione scrittura re su eventhub azure PagoPA" - }, - "GLOBAL-default_token_duration_validity_millis": { - "category": "GLOBAL", - "key": "default_token_duration_validity_millis", - "value": "70000", - "description": " default millisecondi validità token" - }, - "GLOBAL-scheduler.jobName_paRetryPaInviaRtNegative.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_paRetryPaInviaRtNegative.cronExpression", - "value": "0/30 * * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-scheduler.jobName_mod3RiconciliazioneRpt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3RiconciliazioneRpt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.mod3Cancel.minutesWaitPaOld": { - "category": "GLOBAL", - "key": "scheduler.mod3Cancel.minutesWaitPaOld", - "value": "0", - "description": "timeout" - }, - "info-quadr-smtp.host": { - "category": "info-quadr", - "key": "smtp.host", - "value": "10.10.39.132", - "description": null - }, - "GLOBAL-scheduler.jobName_retryPspSendPayment.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_retryPspSendPayment.jobDescription", - "value": "Description", - "description": "Retry psp send payment" - }, - "GLOBAL-validate_input": { - "category": "GLOBAL", - "key": "validate_input", - "value": "true", - "description": "Validazione XSD input Bundle" - }, - "GLOBAL-idempotency.activate.ko.duration.days": { - "category": "GLOBAL", - "key": "idempotency.activate.ko.duration.days", - "value": "1", - "description": "cache validity days activate ko" - }, - "GLOBAL-gec.fees.maxRetry": { - "category": "GLOBAL", - "key": "gec.fees.maxRetry", - "value": "0", - "description": "maxRetry to GEC service fees" - }, - "GLOBAL-istitutoAttestante.identificativoUnivocoAttestante.tipoIdentificativoUnivoco": { - "category": "GLOBAL", - "key": "istitutoAttestante.identificativoUnivocoAttestante.tipoIdentificativoUnivoco", - "value": "G", - "description": "CtIdentificativoUnivoco.tipoIdentificativoUnivoco" - }, - "GLOBAL-scheduler.jobName_mod3UpdateNotifiedPositionPayment.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3UpdateNotifiedPositionPayment.jobDescription", - "value": "Description", - "description": "Mod3 update notified Position Payment" - }, - "GLOBAL-idempotency.outcome.ko.duration.days": { - "category": "GLOBAL", - "key": "idempotency.outcome.ko.duration.days", - "value": "2", - "description": "cache validity days outcome ko" - }, - "info-wisp-chiediListaPSP.listaIdPoste": { - "category": "info-wisp", - "key": "chiediListaPSP.listaIdPoste", - "value": "POSTE1", - "description": null - }, - "rendicontazioni-ftp.internalFTPComponentEndpointPort": { - "category": "rendicontazioni", - "key": "ftp.internalFTPComponentEndpointPort", - "value": "9610", - "description": null - }, - "GLOBAL-scheduler.jobName_paRetryPaInviaRtNegative.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_paRetryPaInviaRtNegative.jobDescription", - "value": "Description", - "description": "Description" - }, - "FATTURAZIONI-tipoVersamento.PO": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.PO", - "value": "0;0;0;0;0;1;0;0", - "description": "codifica csv tipo versamento PO" - }, - "GLOBAL-usePspNotifyPayment": { - "category": "GLOBAL", - "key": "usePspNotifyPayment", - "value": "false", - "description": " flag di ON/OFF se usare primitiva pspNotifyPayment per PayPal" - }, - "GLOBAL-scheduler.jobName_paRetryAttivaRpt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_paRetryAttivaRpt.jobDescription", - "value": "Description", - "description": "retry attiva rpt " - }, - "info-quadr-smtp.username": { - "category": "info-quadr", - "key": "smtp.username", - "value": "pda@dev.test", - "description": null - }, - "GLOBAL-scheduler.jobName_ftpUpload.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_ftpUpload.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "info-quadr-commissioneCaricoPa.pdf.dettaglio.header": { - "category": "info-quadr", - "key": "commissioneCaricoPa.pdf.dettaglio.header", - "value": "Tabella dettaglio versamenti", - "description": null - }, - "GLOBAL-timeout.cdInfoWisp": { - "category": "GLOBAL", - "key": "timeout.cdInfoWisp", - "value": "TIMEOUT_A", - "description": "Tipo timeout" - }, - "GLOBAL-timeout.paSendRT.pull": { - "category": "GLOBAL", - "key": "timeout.paSendRT.pull", - "value": "TIMEOUT_C", - "description": "Tipo timeout" - }, - "GLOBAL-useCountChiediAvanzamento": { - "category": "GLOBAL", - "key": "useCountChiediAvanzamento", - "value": "true", - "description": "toggle per abilitare o disabilitare contatori NodoChiediAvanzamento" - }, - "GLOBAL-default_idempotency_key_validity_minutes": { - "category": "GLOBAL", - "key": "default_idempotency_key_validity_minutes", - "value": "10", - "description": "timeout" - }, - "rpt-info-chiediInfoPagamento.outputJsonValid": { - "category": "rpt-info", - "key": "chiediInfoPagamento.outputJsonValid", - "value": "true", - "description": "-" - }, - "GLOBAL-scheduler.jobName_paInviaRt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_paInviaRt.enabled", - "value": "false", - "description": "Job enabled (true/false)" - }, - "info-pa-psp-disableNodoChiediInformativaPSP": { - "category": "info-pa-psp", - "key": "disableNodoChiediInformativaPSP", - "value": "false", - "description": "restituisce come risposta alla nodoChiediInformativaPSP un SYSTEM_ERROR" - }, - "GLOBAL-scheduler.jobName_mod3GenerateReceipt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3GenerateReceipt.jobDescription", - "value": "Description", - "description": "generazione ricevute in formato receipt" - }, - "GLOBAL-scheduler.jobName_mod3Riconciliazione.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3Riconciliazione.jobDescription", - "value": "Description", - "description": "Riconciliazione rpt" - }, - "GLOBAL-scheduler.jobName_mod3RiconciliazioneRt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3RiconciliazioneRt.jobDescription", - "value": "Description", - "description": "Riconciliazione rpt" - }, - "GLOBAL-scheduler.jobName_mod3CancelV2.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3CancelV2.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.jobName_pspChiediAvanzamentoRpt.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspChiediAvanzamentoRpt.cronExpression", - "value": "0/30 * * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "info-wisp-chiediListaPSP.listaCanaliLisPay": { - "category": "info-wisp", - "key": "chiediListaPSP.listaCanaliLisPay", - "value": "13212880150_07", - "description": "id Canali LisPay,divisi da virgola" - }, - "GLOBAL-timeout.paVerifyPaymentNotice": { - "category": "GLOBAL", - "key": "timeout.paVerifyPaymentNotice", - "value": "TIMEOUT_A", - "description": "Tipo timeout" - }, - "GLOBAL-scheduler.jobName_refreshConfiguration.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_refreshConfiguration.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-gec.fees.maxOccurences": { - "category": "GLOBAL", - "key": "gec.fees.maxOccurences", - "value": "10", - "description": "maxOccurences to GEC service fees" - }, - "GLOBAL-idPlugin.mybank": { - "category": "GLOBAL", - "key": "idPlugin.mybank", - "value": "wpl04", - "description": "identificativo plugin MyBank" - }, - "GLOBAL-paymentmanager.baseurl": { - "category": "GLOBAL", - "key": "paymentmanager.baseurl", - "value": "http://localhost:8080", - "description": "Validazione XSD input Bundle" - }, - "FATTURAZIONI-tipoVersamento.MYBK": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.MYBK", - "value": "0;0;0;0;0;0;0;1", - "description": "codifica csv tipo versamento MYBK" - }, - "info-wisp-chiediListaPSP.ibanPosteMatch": { - "category": "info-wisp", - "key": "chiediListaPSP.ibanPosteMatch", - "value": "07601", - "description": "Check iban poste match" - }, - "GLOBAL-httpmethod.wfesp.psp2wfespMS": { - "category": "GLOBAL", - "key": "httpmethod.wfesp.psp2wfespMS", - "value": "esitoMS", - "description": null - }, - "rpt-invia-patch.ministeroDiGiustizia.active": { - "category": "rpt-invia", - "key": "patch.ministeroDiGiustizia.active", - "value": "true", - "description": "Flag di attivazione della patch" - }, - "info-quadr-commissioneCaricoPsp.noData.message": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.noData.message", - "value": "Nessun dato disponibile per il mese di riferimento", - "description": null - }, - "GLOBAL-timeout.paaVerificaRPT": { - "category": "GLOBAL", - "key": "timeout.paaVerificaRPT", - "value": "TIMEOUT_A", - "description": "Tipo timeout" - }, - "GLOBAL-timeout.pspChiediListaRT": { - "category": "GLOBAL", - "key": "timeout.pspChiediListaRT", - "value": "TIMEOUT_C", - "description": "Tipo timeout" - }, - "GLOBAL-idCanaleCheckout": { - "category": "GLOBAL", - "key": "idCanaleCheckout", - "value": "TBD", - "description": "id Canale Checkout" - }, - "GLOBAL-id_psp_poste": { - "category": "GLOBAL", - "key": "id_psp_poste", - "value": "POSTE3", - "description": "id psp poste" - }, - "GLOBAL-outcome_retry_active": { - "category": "GLOBAL", - "key": "outcome_retry_active", - "value": "true", - "description": "attivazione retry su outcome scaduto mod3" - }, - "rendicontazioni-bollo.codiceIdentificativo.1": { - "category": "rendicontazioni", - "key": "bollo.codiceIdentificativo.1", - "value": "SIA", - "description": null - }, - "GLOBAL-scheduler.jobName_paInviaRt.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_paInviaRt.cronExpression", - "value": "0/30 * * ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-scheduler.ftpUploadRetryPollerMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.ftpUploadRetryPollerMaxRetry", - "value": "5", - "description": "numero massimo di tentativi di re-invio file ftp" - }, - "GLOBAL-scheduler.sendPaymentResultPollerMinutesBack": { - "category": "GLOBAL", - "key": "scheduler.sendPaymentResultPollerMinutesBack", - "value": "1", - "description": "Minuti precedenti per cercare una retry sendPaymentResult" - }, - "rendicontazioni-bollo.codiceIdentificativo.2": { - "category": "rendicontazioni", - "key": "bollo.codiceIdentificativo.2", - "value": "YY", - "description": null - }, - "GLOBAL-timeout.pspChiediAvanzamentoRPT": { - "category": "GLOBAL", - "key": "timeout.pspChiediAvanzamentoRPT", - "value": "TIMEOUT_B", - "description": "Tipo timeout" - }, - "info-quadr-commissioneCaricoPsp.invio.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.invio.mail", - "value": "true", - "description": null - }, - "GLOBAL-maxChiediAvanzamento": { - "category": "GLOBAL", - "key": "maxChiediAvanzamento", - "value": "3", - "description": "numero massimo di tentativi per NodoChiediAvanzamento da PM" - }, - "GLOBAL-gec.enabled": { - "category": "GLOBAL", - "key": "gec.enabled", - "value": "true", - "description": "toggle to enabled/disabled gec service" - }, - "GLOBAL-scheduler.jobName_paSendRt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_paSendRt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "FATTURAZIONI-tipoVersamento.BBT": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.BBT", - "value": "1;0;0;0;0;0;0;0", - "description": "codifica csv tipo versamento BBT" - }, - "rpt-modello4-aciId": { - "category": "rpt-modello4", - "key": "aciId", - "value": "00493410583", - "description": "identificativo Automobile Club Italia" - }, - "GLOBAL-default_durata_token_IO": { - "category": "GLOBAL", - "key": "default_durata_token_IO", - "value": "2000", - "description": " default millisecondi validità token IO" - }, - "GLOBAL-idCanaleCD": { - "category": "GLOBAL", - "key": "idCanaleCD", - "value": "97735020584_03", - "description": "identificativo canale Cittadinanza Digitale" - }, - "GLOBAL-timeoutForSingleProcessSeconds": { - "category": "GLOBAL", - "key": "timeoutForSingleProcessSeconds", - "value": "130", - "description": "Secondi di timeout per singolo processo" - }, - "GLOBAL-scheduler.jobName_mod3Riconciliazione.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3Riconciliazione.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-ftp.env.path": { - "category": "GLOBAL", - "key": "ftp.env.path", - "value": "pate_", - "description": "cartella file rendicontazioni" - }, - "GLOBAL-mybank.params.passaggioCodiceMyBank": { - "category": "GLOBAL", - "key": "mybank.params.passaggioCodiceMyBank", - "value": "true", - "description": null - }, - "FATTURAZIONI-tipoVersamento.TPAY": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.TPAY", - "value": "0;0;0;0;1;0;0;0", - "description": "codifica csv tipo versamento TPAY" - }, - "GLOBAL-httpmethod.wfesp.pa2wfesp": { - "category": "GLOBAL", - "key": "httpmethod.wfesp.pa2wfesp", - "value": "get", - "description": null - }, - "FATTURAZIONI-tipoVersamento.OBEP": { - "category": "FATTURAZIONI", - "key": "tipoVersamento.OBEP", - "value": "0;0;0;1;0;0;0;0", - "description": "codifica csv tipo versamento OBEP" - }, - "GLOBAL-istitutoAttestante.identificativoUnivocoAttestante.codiceIdentificativoUnivoco": { - "category": "GLOBAL", - "key": "istitutoAttestante.identificativoUnivocoAttestante.codiceIdentificativoUnivoco", - "value": "15376371009", - "description": "CtIdentificativoUnivoco.codiceIdentificativoUnivoco" - }, - "GLOBAL-idPspECommerce": { - "category": "GLOBAL", - "key": "idPspECommerce", - "value": "TBD", - "description": "id PSP eCommerce" - }, - "GLOBAL-scheduler.jobName_pspChiediAvanzamentoRpt.jobDescription": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspChiediAvanzamentoRpt.jobDescription", - "value": "Description", - "description": "Description" - }, - "info-quadr-versioneQuadrature": { - "category": "info-quadr", - "key": "versioneQuadrature", - "value": "6.1", - "description": "Versione Quadrature" - }, - "info-quadr-commissioneCaricoPa.pdf.aggregato.footer": { - "category": "info-quadr", - "key": "commissioneCaricoPa.pdf.aggregato.footer", - "value": "n.a.", - "description": null - }, - "rendicontazioni-bollo.dateFormat": { - "category": "rendicontazioni", - "key": "bollo.dateFormat", - "value": "yyyy-MM-dd", - "description": null - }, - "info-quadr-commissioneCaricoPa.invio.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPa.invio.mail", - "value": "true", - "description": null - }, - "GLOBAL-scheduler.jobName_pspNotificaCancellazione.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspNotificaCancellazione.cronExpression", - "value": "0 0 1 ? * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "info-quadr-commissioneCaricoPa.template.subject.mail": { - "category": "info-quadr", - "key": "commissioneCaricoPa.template.subject.mail", - "value": "Report commissioniCaricoPa", - "description": null - }, - "rpt-invia-mybank.params.passaggioCodiceMyBank": { - "category": "rpt-invia", - "key": "mybank.params.passaggioCodiceMyBank", - "value": "true", - "description": null - }, - "rendicontazioni-bollo.intermediario.siglaDellaProvinciaDelDomicilioFiscale": { - "category": "rendicontazioni", - "key": "bollo.intermediario.siglaDellaProvinciaDelDomicilioFiscale", - "value": "MI", - "description": "Dati dell'intermediario della trasmissione/ Sigle della provincia del domicilio fiscale" - }, - "GLOBAL-useIdempotency": { - "category": "GLOBAL", - "key": "useIdempotency", - "value": "false", - "description": "use idempotency" - }, - "GLOBAL-scheduler.jobName_pspChiediListaAndChiediRt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspChiediListaAndChiediRt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-scheduler.cancelIOPaymentActorMinutesToBack": { - "category": "GLOBAL", - "key": "scheduler.cancelIOPaymentActorMinutesToBack", - "value": "1", - "description": "cancel IO Payment Minutes To Back" - }, - "GLOBAL-scheduler.paRetryPaInviaRtNegativePollerMaxRetry": { - "category": "GLOBAL", - "key": "scheduler.paRetryPaInviaRtNegativePollerMaxRetry", - "value": "5", - "description": "numero massimo di tentativi di re-invio delle RT alla PA" - }, - "GLOBAL-wisp.timeoutScelta": { - "category": "GLOBAL", - "key": "wisp.timeoutScelta", - "value": "75", - "description": "wisp timeout ChiediSceltaWISP" - }, - "info-quadr-commissioneCaricoPsp.pdf.dettaglio.header": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.pdf.dettaglio.header", - "value": "Tabella dettaglio versamenti", - "description": null - }, - "GLOBAL-scheduler.jobName_situazioneOrdine.cronExpression": { - "category": "GLOBAL", - "key": "scheduler.jobName_situazioneOrdine.cronExpression", - "value": "*/2 * * * *", - "description": "Cron expression (Es.[*/10 * * ? * *] will fire every ten seconds)" - }, - "GLOBAL-scheduler.jobName_mod3GenerateReceipt.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_mod3GenerateReceipt.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-idCanaleECommerce": { - "category": "GLOBAL", - "key": "idCanaleECommerce", - "value": "TBD", - "description": "id Canale eCommerce" - }, - "GLOBAL-istitutoAttestante.provinciaAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.provinciaAttestante", - "value": "RM", - "description": "provinciaAttestante" - }, - "GLOBAL-mod3_descoping": { - "category": "GLOBAL", - "key": "mod3_descoping", - "value": "true", - "description": "check mod3 descoping" - }, - "GLOBAL-timeout.paaChiediNumeroAvviso": { - "category": "GLOBAL", - "key": "timeout.paaChiediNumeroAvviso", - "value": "TIMEOUT_A", - "description": "Tipo timeout" - }, - "GLOBAL-timeout.paaAttivaRPT.pull": { - "category": "GLOBAL", - "key": "timeout.paaAttivaRPT.pull", - "value": "TIMEOUT_C", - "description": "timeout" - }, - "GLOBAL-sendBizEventsToEventHub": { - "category": "GLOBAL", - "key": "sendBizEventsToEventHub", - "value": "true", - "description": "sendBizEventsToEventHub" - }, - "info-quadr-commissioneCaricoPsp.pdf.dettaglio.footer": { - "category": "info-quadr", - "key": "commissioneCaricoPsp.pdf.dettaglio.footer", - "value": "n.a.", - "description": null - }, - "GLOBAL-scheduler.jobName_pspRetryAckNegative.enabled": { - "category": "GLOBAL", - "key": "scheduler.jobName_pspRetryAckNegative.enabled", - "value": "true", - "description": "Job enabled (true/false)" - }, - "GLOBAL-urlFittizioRedirectEC": { - "category": "GLOBAL", - "key": "urlFittizioRedirectEC", - "value": "http://url.fittizio", - "description": "urlFittizioRedirectEC" - }, - "GLOBAL-istitutoAttestante.denomUnitOperAttestante": { - "category": "GLOBAL", - "key": "istitutoAttestante.denomUnitOperAttestante", - "value": "n/a", - "description": "denomUnitOperAttestante" - }, - "info-quadr-commissioneCaricoPa.pdf.aggregato.header": { - "category": "info-quadr", - "key": "commissioneCaricoPa.pdf.aggregato.header", - "value": "Tabella aggregato versamenti", - "description": null - }, - "GLOBAL-idPspAGID": { - "category": "GLOBAL", - "key": "idPspAGID", - "value": "AGID_01", - "description": "id PSP AGID" - }, - "GLOBAL-timeout.pspInviaRPT": { - "category": "GLOBAL", - "key": "timeout.pspInviaRPT", - "value": "TIMEOUT_B", - "description": "Tipo timeout" - }, - "GLOBAL-IO_token_duration_validity_millis": { - "category": "GLOBAL", - "key": "IO_token_duration_validity_millis", - "value": "3600000", - "description": " default millisecondi validità token IO" - }, - "rendicontazioni-ftp.internalFTPComponentEndpointHost": { - "category": "rendicontazioni", - "key": "ftp.internalFTPComponentEndpointHost", - "value": "0.0.0.0", - "description": null - }, - "rt-invia-idFaultBean.nodo": { - "category": "rt-invia", - "key": "idFaultBean.nodo", - "value": "NodoDeiPagamentiSPC", - "description": "identificativo del nodo per valorizzazione dell'elemento id nel Fault Bean, in caso di errore generato dal FESP" - } - }, - "ftpServers": null, - "languages": null, - "gdeConfigurations": null, - "metadataDict": null - }, - "contentType": "application/json" - } - } - } -] \ No newline at end of file From 0533f7868b0baf715baff4f6c6826b11e6879c8c Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 19 Jul 2023 18:27:55 +0200 Subject: [PATCH 28/29] fix by design --- helm/values-dev.yaml | 2 -- helm/weu-dev/values-dev.yaml | 2 -- helm/weu-uat/values-uat.yaml | 2 -- src/main/resources/application.properties | 28 ----------------------- 4 files changed, 34 deletions(-) diff --git a/helm/values-dev.yaml b/helm/values-dev.yaml index ab19d0d..1dfbd40 100644 --- a/helm/values-dev.yaml +++ b/helm/values-dev.yaml @@ -21,7 +21,6 @@ pagopa-tech-support-api: APP_ENVIRONMENT: "dev" TZ: "Europe/Rome" OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" - ADAPTER_API_CONFIG_CACHE_URL: "https://api.dev.platform.pagopa.it/api-config-cache/p/v1" COSMOS_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-ds-cosmos-account.documents.azure.com:443/" COSMOS_NEG_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/" envFieldRef: @@ -30,7 +29,6 @@ pagopa-tech-support-api: secretProvider: create: true envSecrets: - ADAPTER_API_CONFIG_CACHE_API_KEY: "api-config-cache-subscription-key-string" EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" COSMOS_BIZ_KEY: "cosmos-biz-account-key" COSMOS_NEG_BIZ_KEY: "cosmos-neg-biz-account-key" diff --git a/helm/weu-dev/values-dev.yaml b/helm/weu-dev/values-dev.yaml index 824bddf..85c3057 100644 --- a/helm/weu-dev/values-dev.yaml +++ b/helm/weu-dev/values-dev.yaml @@ -21,7 +21,6 @@ pagopa-tech-support-api: APP_ENVIRONMENT: "dev" TZ: "Europe/Rome" OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" - ADAPTER_API_CONFIG_CACHE_URL: "https://api.dev.platform.pagopa.it/api-config-cache/p/v1" COSMOS_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-ds-cosmos-account.documents.azure.com:443/" COSMOS_NEG_BIZ_ENDPOINT: "https://pagopa-d-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/" envFieldRef: @@ -30,7 +29,6 @@ pagopa-tech-support-api: secretProvider: create: true envSecrets: - ADAPTER_API_CONFIG_CACHE_API_KEY: "api-config-cache-subscription-key-string" EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" COSMOS_BIZ_KEY: "cosmos-biz-account-key" COSMOS_NEG_BIZ_KEY: "cosmos-neg-biz-account-key" diff --git a/helm/weu-uat/values-uat.yaml b/helm/weu-uat/values-uat.yaml index f5352d7..ee0b69b 100644 --- a/helm/weu-uat/values-uat.yaml +++ b/helm/weu-uat/values-uat.yaml @@ -21,7 +21,6 @@ pagopa-tech-support-api: APP_ENVIRONMENT: "uat" TZ: "Europe/Rome" OTEL_ENDPOINT: "http://otel-collector.elastic-system.svc.cluster.local:4317" - ADAPTER_API_CONFIG_CACHE_URL: "https://api.uat.platform.pagopa.it/api-config-cache/p/v1" COSMOS_BIZ_ENDPOINT: "https://pagopa-u-weu-bizevents-ds-cosmos-account.documents.azure.com:443/" COSMOS_NEG_BIZ_ENDPOINT: "https://pagopa-u-weu-bizevents-neg-ds-cosmos-account.documents.azure.com:443/" envFieldRef: @@ -30,7 +29,6 @@ pagopa-tech-support-api: secretProvider: create: true envSecrets: - ADAPTER_API_CONFIG_CACHE_API_KEY: "api-config-cache-subscription-key-string" EVENT_HUB_RE_CONNECTION_STRING: "azure-event-hub-re-connection-string" COSMOS_BIZ_KEY: "cosmos-biz-account-key" COSMOS_NEG_BIZ_KEY: "cosmos-neg-biz-account-key" diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3da799e..2443191 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -71,7 +71,6 @@ biz.key=${COSMOS_BIZ_KEY:${mockserver.biz.key}} bizneg.endpoint=${COSMOS_NEG_BIZ_ENDPOINT:${mockserver.biz.endpoint}} bizneg.key=${COSMOS_NEG_BIZ_KEY:${mockserver.biz.key}} - re-table-storage.table-name=events re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING:${mockserver.azurite.connection-string}} %dev.re-table-storage.connection-string=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1; @@ -82,40 +81,13 @@ re-table-storage.connection-string=${RE_TABLE_STORAGE_CONN_STRING:${mockserver.a %openapi.bizneg.key=nn %openapi.re-table-storage.connection-string=nn -################### -## ADAPTER API CONFIG CACHE -################### -#quarkus.rest-client.logging.scope=request-response -#quarkus.rest-client.logging.body-limit=1024 -#quarkus.log.category."org.jboss.resteasy.reactive.client.logging".level=DEBUG - ################### ## SCHEDULER ################### %test.quarkus.scheduler.enabled=false %openapi.quarkus.scheduler.enabled=false -# By default, the syntax used for cron expressions is based on Quartz - https://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html -# You can change the syntax using the following property: -# quarkus.scheduler.cron-type=unix -api_config_cache.cron.expr=*/15 * * * * ? - -startconfig.enabled=true -%openapi.startconfig.enabled=false -adapter.api_config_cache.api-key-name=Ocp-Apim-Subscription-Key -adapter.api_config_cache.api-key-value=${ADAPTER_API_CONFIG_CACHE_API_KEY:12345} -adapter.api_config_cache.url=${ADAPTER_API_CONFIG_CACHE_URL:${quarkus.mockserver.endpoint}} - operations.filter=".*" -############## -# MOCK SERVER -############## -%dev.quarkus.mockserver.devservices.config-file=src/test/resources/mockserver.properties -%dev.quarkus.mockserver.devservices.config-dir=src/test/resources/mockserver -%dev.quarkus.mockserver.devservices.log=false -%test.quarkus.mockserver.devservices.config-file=src/test/resources/mockserver.properties -%test.quarkus.mockserver.devservices.config-dir=src/test/resources/mockserver -%test.quarkus.mockserver.devservices.log=false quarkus.test.continuous-testing=disabled quarkus.http.test-port=8083 \ No newline at end of file From 9f37a5fd34243833c56692921ca4563f13802e5b Mon Sep 17 00:00:00 2001 From: Cesare Caccuri Date: Wed, 19 Jul 2023 18:31:32 +0200 Subject: [PATCH 29/29] fix by design --- openapi/openapi.json | 726 +++++++++++++++++++++---------------------- 1 file changed, 348 insertions(+), 378 deletions(-) diff --git a/openapi/openapi.json b/openapi/openapi.json index 1b27b7b..5266027 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -1,38 +1,32 @@ { - "openapi": "3.0.3", - "info": { - "title": "Node technical support - Api (local) ${service}", - "termsOfService": "https://www.pagopa.gov.it/", - "version": "1.0.0-3-implementing" + "openapi" : "3.0.3", + "info" : { + "title" : "Node technical support - Api (local) ${service}", + "termsOfService" : "https://www.pagopa.gov.it/", + "version" : "1.0.0-3-implementing" }, - "servers": [ - { - "url": "${host}/tenchinal-support/api/v1 - APIM" - } - ], - "tags": [ - { - "name": "Info", - "description": "Info operations" - } - ], - "paths": { - "/info": { - "get": { - "tags": [ - "Info" - ], - "summary": "Get info of FDR", - "responses": { - "default": { - "$ref": "#/components/responses/InternalServerError" - }, - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InfoResponse" + "servers" : [ { + "url" : "${host}/tenchinal-support/api/v1 - APIM" + } ], + "tags" : [ { + "name" : "Info", + "description" : "Info operations" + } ], + "paths" : { + "/info" : { + "get" : { + "tags" : [ "Info" ], + "summary" : "Get info of FDR", + "responses" : { + "default" : { + "$ref" : "#/components/responses/InternalServerError" + }, + "200" : { + "description" : "Success", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/InfoResponse" } } } @@ -40,70 +34,63 @@ } } }, - "/organizations/{organizationFiscalCode}/iuv/{iuv}": { - "get": { - "tags": [ - "Worker Resource" - ], - "parameters": [ - { - "name": "iuv", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "organizationFiscalCode", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "dateFrom", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } - }, - { - "name": "dateTo", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } + "/organizations/{organizationFiscalCode}/iuv/{iuv}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "iuv", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TransactionResponse" + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" } } } }, - "400": { - "description": "Bad Request", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } }, - "500": { - "description": "Service unavailable.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } @@ -111,78 +98,70 @@ } } }, - "/organizations/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}": { - "get": { - "tags": [ - "Worker Resource" - ], - "parameters": [ - { - "name": "ccp", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "iuv", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "organizationFiscalCode", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "dateFrom", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } - }, - { - "name": "dateTo", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } + "/organizations/{organizationFiscalCode}/iuv/{iuv}/ccp/{ccp}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "ccp", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "iuv", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TransactionResponse" + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" } } } }, - "400": { - "description": "Bad Request", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } }, - "500": { - "description": "Service unavailable.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } @@ -190,78 +169,63 @@ } } }, - "/organizations/{organizationFiscalCode}/iuv/{iuv}/paymentToken/{paymentToken}": { - "get": { - "tags": [ - "Worker Resource" - ], - "parameters": [ - { - "name": "iuv", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "organizationFiscalCode", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "paymentToken", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "dateFrom", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } - }, - { - "name": "dateTo", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } + "/organizations/{organizationFiscalCode}/noticeNumber/{noticeNumber}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "noticeNumber", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TransactionResponse" + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" } } } }, - "400": { - "description": "Bad Request", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } }, - "500": { - "description": "Service unavailable.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } @@ -269,70 +233,70 @@ } } }, - "/organizations/{organizationFiscalCode}/noticeNumber/{noticeNumber}": { - "get": { - "tags": [ - "Worker Resource" - ], - "parameters": [ - { - "name": "noticeNumber", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "organizationFiscalCode", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "dateFrom", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } - }, - { - "name": "dateTo", - "in": "query", - "schema": { - "$ref": "#/components/schemas/LocalDate" - } + "/organizations/{organizationFiscalCode}/noticeNumber/{noticeNumber}/paymentToken/{paymentToken}" : { + "get" : { + "tags" : [ "Worker Resource" ], + "parameters" : [ { + "name" : "noticeNumber", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "organizationFiscalCode", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "name" : "paymentToken", + "in" : "path", + "required" : true, + "schema" : { + "type" : "string" } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TransactionResponse" + }, { + "name" : "dateFrom", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + }, { + "name" : "dateTo", + "in" : "query", + "schema" : { + "$ref" : "#/components/schemas/LocalDate" + } + } ], + "responses" : { + "200" : { + "description" : "OK", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TransactionResponse" } } } }, - "400": { - "description": "Bad Request", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "400" : { + "description" : "Bad Request", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } }, - "500": { - "description": "Service unavailable.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemJson" + "500" : { + "description" : "Service unavailable.", + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ProblemJson" } } } @@ -341,145 +305,151 @@ } } }, - "components": { - "schemas": { - "BasePaymentInfo": { - "type": "object", - "properties": { - "organizationFiscalCode": { - "type": "string" + "components" : { + "schemas" : { + "BasePaymentInfo" : { + "type" : "object", + "properties" : { + "organizationFiscalCode" : { + "type" : "string" + }, + "noticeNumber" : { + "type" : "string" }, - "noticeNumber": { - "type": "string" + "iuv" : { + "type" : "string" }, - "iuv": { - "type": "string" + "pspId" : { + "type" : "string" }, - "pspId": { - "type": "string" + "brokerPspId" : { + "type" : "string" }, - "brokerPspId": { - "type": "string" + "channelId" : { + "type" : "string" }, - "channelId": { - "type": "string" + "outcome" : { + "type" : "string" }, - "outcome": { - "type": "string" + "status" : { + "type" : "string" }, - "status": { - "type": "string" + "insertedTimestamp" : { + "type" : "string" }, - "insertedTimestamp": { - "type": "string" + "updatedTimestamp" : { + "type" : "string" }, - "updatedTimestamp": { - "type": "string" + "isOldPaymentModel" : { + "type" : "boolean" }, - "isOldPaymentModel": { - "type": "boolean" + "serviceIdentifier" : { + "type" : "string" }, - "nodeId": { - "type": "string" + "positiveBizEvtId" : { + "type" : "string" + }, + "negativeBizEvtId" : { + "type" : "string" } } }, - "ErrorCode": { - "type": "object", - "properties": { - "code": { - "type": "string", - "example": "FDR-0500" - }, - "description": { - "type": "string", - "example": "An unexpected error has occurred. Please contact support." - }, - "statusCode": { - "format": "int32", - "type": "integer", - "example": 500 + "ErrorCode" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "string", + "example" : "FDR-0500" + }, + "description" : { + "type" : "string", + "example" : "An unexpected error has occurred. Please contact support." + }, + "statusCode" : { + "format" : "int32", + "type" : "integer", + "example" : 500 } } }, - "InfoResponse": { - "type": "object", - "properties": { - "name": { - "type": "string", - "example": "pagopa-fdr" - }, - "version": { - "type": "string", - "example": "1.2.3" - }, - "environment": { - "type": "string", - "example": "dev" - }, - "description": { - "type": "string", - "example": "FDR - Flussi di rendicontazione" - }, - "errorCodes": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ErrorCode" + "InfoResponse" : { + "type" : "object", + "properties" : { + "name" : { + "type" : "string", + "example" : "pagopa-fdr" + }, + "version" : { + "type" : "string", + "example" : "1.2.3" + }, + "environment" : { + "type" : "string", + "example" : "dev" + }, + "description" : { + "type" : "string", + "example" : "FDR - Flussi di rendicontazione" + }, + "errorCodes" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/ErrorCode" } } } }, - "LocalDate": { - "format": "date", - "type": "string", - "example": "2022-03-10" + "LocalDate" : { + "format" : "date", + "type" : "string", + "example" : "2022-03-10" }, - "ProblemJson": { - "type": "object", - "properties": { - "title": { - "description": "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable", - "type": "string" - }, - "status": { - "format": "int32", - "description": "The HTTP status code generated by the origin server for this occurrence of the problem.", - "maximum": 600, - "minimum": 100, - "type": "integer", - "example": 200 - }, - "details": { - "description": "A human readable explanation specific to this occurrence of the problem.", - "type": "string", - "example": "There was an error processing the request" + "ProblemJson" : { + "type" : "object", + "properties" : { + "title" : { + "description" : "A short, summary of the problem type. Written in english and readable for engineers (usually not suited for non technical stakeholders and not localized); example: Service Unavailable", + "type" : "string" + }, + "status" : { + "format" : "int32", + "description" : "The HTTP status code generated by the origin server for this occurrence of the problem.", + "maximum" : 600, + "minimum" : 100, + "type" : "integer", + "example" : 200 + }, + "details" : { + "description" : "A human readable explanation specific to this occurrence of the problem.", + "type" : "string", + "example" : "There was an error processing the request" } } }, - "TransactionResponse": { - "type": "object", - "properties": { - "dateFrom": { - "$ref": "#/components/schemas/LocalDate" - }, - "dateTo": { - "$ref": "#/components/schemas/LocalDate" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/BasePaymentInfo" + "TransactionResponse" : { + "type" : "object", + "properties" : { + "dateFrom" : { + "$ref" : "#/components/schemas/LocalDate" + }, + "dateTo" : { + "$ref" : "#/components/schemas/LocalDate" + }, + "data" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/BasePaymentInfo" } } } } }, - "securitySchemes": { - "SecurityScheme": { - "type": "http", - "description": "Authentication", - "scheme": "basic" + "securitySchemes" : { + "SecurityScheme" : { + "type" : "http", + "description" : "Authentication", + "scheme" : "basic" } } } -} +} \ No newline at end of file