diff --git a/app/src/main/resources/swagger/api-docs.json b/app/src/main/resources/swagger/api-docs.json index d3a16ce54..e41f35048 100644 --- a/app/src/main/resources/swagger/api-docs.json +++ b/app/src/main/resources/swagger/api-docs.json @@ -33,9 +33,6 @@ }, { "name" : "Onboarding", "description" : "Onboarding Controller" - }, { - "name" : "Persons", - "description" : "User Controller" }, { "name" : "kafka", "description" : "Queue Notification Controller" @@ -705,68 +702,6 @@ } ] } }, - "/external/institutions/{externalId}/products/{productId}/manager" : { - "get" : { - "tags" : [ "External" ], - "summary" : "retrieves the manager related to the institution even if the current user is not related to the institution/product", - "description" : "retrieves the manager related to the institution even if the current user is not related to the institution/product", - "operationId" : "getManagerInstitutionByExternalIdUsingGET", - "parameters" : [ { - "name" : "externalId", - "in" : "path", - "description" : "Institution's unique external identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "productId", - "in" : "path", - "description" : "Product's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/InstitutionManagerResponse" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, "/institutions" : { "get" : { "tags" : [ "Institution", "external-v2", "support" ], @@ -2009,62 +1944,6 @@ } ] } }, - "/institutions/{institutionId}/users" : { - "get" : { - "tags" : [ "Institution", "support" ], - "summary" : "getInstitutionUsers", - "description" : "Retrieve institution's users", - "operationId" : "getInstitutionUsersUsingGET", - "parameters" : [ { - "name" : "institutionId", - "in" : "path", - "description" : "Institution's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/UserInfoResponse" - } - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, "/institutions/{productId}/brokers/{institutionType}" : { "get" : { "tags" : [ "Institution" ], @@ -2257,78 +2136,6 @@ } ] } }, - "/onboarding/info" : { - "get" : { - "tags" : [ "Onboarding" ], - "summary" : "returns onboarding info", - "description" : "returns onboarding info", - "operationId" : "onboardingInfoUsingGET", - "parameters" : [ { - "name" : "institutionId", - "in" : "query", - "description" : "The internal identifier of the institution", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionExternalId", - "in" : "query", - "description" : "Institution's unique external identifier", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "states", - "in" : "query", - "description" : "List of Relationship state for filter products", - "required" : false, - "style" : "form", - "explode" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/OnboardingInfoResponse" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, "/onboarding/institution/{externalId}/products/{productId}" : { "head" : { "tags" : [ "Onboarding" ], @@ -2384,60 +2191,6 @@ } ] } }, - "/onboarding/relationship/{relationshipId}/document" : { - "get" : { - "tags" : [ "Onboarding" ], - "summary" : "retrieve the contractDocument related to a relationship", - "description" : "retrieve the contractDocument related to a relationship", - "operationId" : "getOnboardingDocumentUsingGET", - "parameters" : [ { - "name" : "relationshipId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "type" : "string", - "format" : "byte" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, "/onboarding/verify" : { "head" : { "tags" : [ "Onboarding" ], @@ -2593,821 +2346,18 @@ "bearerAuth" : [ "global" ] } ] } - }, - "/onboarded-users" : { - "get" : { - "tags" : [ "Persons" ], - "summary" : "Retrieve onboarded users according to identifiers in input", - "description" : "Retrieve onboarded users according to identifiers in input", - "operationId" : "getOnboardedUsersUsingGET", - "parameters" : [ { - "name" : "ids", - "in" : "query", - "description" : "Users unique identifiers", - "required" : true, - "style" : "form", - "explode" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "204" : { - "description" : "No Content", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/OnboardedUsersResponse" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/relationships/{relationshipId}" : { - "get" : { - "tags" : [ "Persons" ], - "summary" : "Gets the corresponding relationship", - "description" : "Gets the corresponding relationship", - "operationId" : "getRelationshipUsingGET", - "parameters" : [ { - "name" : "relationshipId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/RelationshipResult" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - }, - "delete" : { - "tags" : [ "Persons" ], - "summary" : "Given a relationship identifier, it deletes the corresponding relationship", - "description" : "Given a relationship identifier, it deletes the corresponding relationship", - "operationId" : "deleteRelationshipUsingDELETE", - "parameters" : [ { - "name" : "relationshipId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "204" : { - "description" : "No Content" - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "409" : { - "description" : "Conflict", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/relationships/{relationshipId}/activate" : { - "post" : { - "tags" : [ "Persons" ], - "summary" : "Activate the relationship", - "description" : "Activate the relationship", - "operationId" : "activateRelationshipUsingPOST", - "parameters" : [ { - "name" : "relationshipId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "204" : { - "description" : "No Content" - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "409" : { - "description" : "Conflict", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/relationships/{relationshipId}/suspend" : { - "post" : { - "tags" : [ "Persons" ], - "summary" : "Suspend the relationship", - "description" : "Suspend the relationship", - "operationId" : "suspendRelationshipUsingPOST", - "parameters" : [ { - "name" : "relationshipId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "204" : { - "description" : "No Content" - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "409" : { - "description" : "Conflict", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/users" : { - "get" : { - "tags" : [ "Persons" ], - "summary" : "getUsers", - "description" : "Retrieve all users according to optional params in input", - "operationId" : "getUsersUsingGET", - "parameters" : [ { - "name" : "size", - "in" : "query", - "description" : "size", - "required" : false, - "style" : "form", - "schema" : { - "type" : "integer", - "format" : "int32" - } - }, { - "name" : "page", - "in" : "query", - "description" : "page", - "required" : false, - "style" : "form", - "schema" : { - "type" : "integer", - "format" : "int32" - } - }, { - "name" : "productId", - "in" : "query", - "description" : "productId", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/UsersNotificationResponse" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/users/{id}" : { - "get" : { - "tags" : [ "Persons", "external-v2", "support" ], - "summary" : "Retrieves user given userId and optional ProductId", - "description" : "Retrieves user given userId and optional ProductId", - "operationId" : "getUserInfoUsingGET", - "parameters" : [ { - "name" : "id", - "in" : "path", - "description" : "User's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "productId", - "in" : "query", - "description" : "Product's unique identifier", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionId", - "in" : "query", - "description" : "The internal identifier of the institution", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/UserResponse" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/users/{id}/status" : { - "put" : { - "tags" : [ "support" ], - "summary" : "Update user status with optional filter for institution, product, role and productRole", - "description" : "Update user status with optional filter for institution, product, role and productRole", - "operationId" : "updateUserStatusUsingPUT", - "parameters" : [ { - "name" : "id", - "in" : "path", - "description" : "User's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionId", - "in" : "query", - "description" : "The internal identifier of the institution", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "productId", - "in" : "query", - "description" : "Product's unique identifier", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "role", - "in" : "query", - "description" : "role", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string", - "enum" : [ "DELEGATE", "MANAGER", "OPERATOR", "SUB_DELEGATE" ] - } - }, { - "name" : "productRole", - "in" : "query", - "description" : "productRole", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "status", - "in" : "query", - "description" : "status", - "required" : true, - "style" : "form", - "schema" : { - "type" : "string", - "enum" : [ "ACTIVE", "DELETED", "PENDING", "REJECTED", "SUSPENDED", "TOBEVALIDATED" ] - } - } ], - "responses" : { - "204" : { - "description" : "No Content" - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "403" : { - "description" : "Forbidden", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/users/{id}/update" : { - "post" : { - "tags" : [ "Persons" ], - "summary" : "Service to send notification when user data get's updated", - "description" : "Service to send notification when user data get's updated", - "operationId" : "updateUserUsingPOST", - "parameters" : [ { - "name" : "id", - "in" : "path", - "description" : "User's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionId", - "in" : "query", - "description" : "The internal identifier of the institution", - "required" : true, - "style" : "form", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "204" : { - "description" : "No Content" - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "409" : { - "description" : "Conflict", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/users/{userId}/institution-products" : { - "get" : { - "tags" : [ "Persons" ], - "summary" : "returns onboarding info", - "description" : "returns onboarding info", - "operationId" : "getInstitutionProductsInfoUsingGET", - "parameters" : [ { - "name" : "userId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionId", - "in" : "query", - "description" : "The internal identifier of the institution", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "states", - "in" : "query", - "description" : "List of Relationship state for filter products", - "required" : false, - "style" : "form", - "explode" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/OnboardingInfoResponse" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/users/{userId}/institutions/{institutionId}/products/{productId}" : { - "delete" : { - "tags" : [ "Persons" ], - "summary" : "Delete logically the association institution and product", - "description" : "Delete logically the association institution and product", - "operationId" : "deleteProductsUsingDELETE", - "parameters" : [ { - "name" : "userId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionId", - "in" : "path", - "description" : "The internal identifier of the institution", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "productId", - "in" : "path", - "description" : "Product's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK" - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "409" : { - "description" : "Conflict", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - }, - "/users/{userId}/products" : { - "get" : { - "tags" : [ "Persons" ], - "summary" : "Retrieves products info and role which the user is enabled", - "description" : "Retrieves products info and role which the user is enabled", - "operationId" : "getUserProductsInfoUsingGET", - "parameters" : [ { - "name" : "userId", - "in" : "path", - "description" : "UserBinding's unique identifier", - "required" : true, - "style" : "simple", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionId", - "in" : "query", - "description" : "The internal identifier of the institution", - "required" : false, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "states", - "in" : "query", - "description" : "List of Relationship state for filter products", - "required" : false, - "style" : "form", - "explode" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/UserProductsResponse" - } - } - } - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } - } - }, - "components" : { - "schemas" : { - "AdditionalInformations" : { - "title" : "AdditionalInformations", - "type" : "object", - "properties" : { - "agentOfPublicService" : { - "type" : "boolean" - }, - "agentOfPublicServiceNote" : { + } + }, + "components" : { + "schemas" : { + "AdditionalInformations" : { + "title" : "AdditionalInformations", + "type" : "object", + "properties" : { + "agentOfPublicService" : { + "type" : "boolean" + }, + "agentOfPublicServiceNote" : { "type" : "string" }, "belongRegulatedMarket" : { @@ -3625,21 +2575,6 @@ } } }, - "BusinessData" : { - "title" : "BusinessData", - "type" : "object", - "properties" : { - "businessRegisterPlace" : { - "type" : "string" - }, - "rea" : { - "type" : "string" - }, - "shareCapital" : { - "type" : "string" - } - } - }, "Contract" : { "title" : "Contract", "type" : "object", @@ -3961,73 +2896,31 @@ "$ref" : "#/components/schemas/GeoTaxonomies" } }, - "institutionType" : { - "type" : "string", - "enum" : [ "AS", "CON", "GSP", "PA", "PG", "PSP", "PT", "REC", "SA", "SCP" ] - }, - "subunitCode" : { - "type" : "string" - }, - "subunitType" : { - "type" : "string", - "enum" : [ "AOO", "UO" ] - }, - "taxCode" : { - "type" : "string" - } - } - }, - "InstitutionGeographicTaxonomies" : { - "title" : "InstitutionGeographicTaxonomies", - "type" : "object", - "properties" : { - "code" : { - "type" : "string" - }, - "desc" : { - "type" : "string" - } - } - }, - "InstitutionManagerResponse" : { - "title" : "InstitutionManagerResponse", - "type" : "object", - "properties" : { - "billing" : { - "$ref" : "#/components/schemas/BillingResponse" - }, - "createdAt" : { + "institutionType" : { "type" : "string", - "format" : "date-time" - }, - "from" : { - "type" : "string" + "enum" : [ "AS", "CON", "GSP", "PA", "PG", "PSP", "PT", "REC", "SA", "SCP" ] }, - "id" : { + "subunitCode" : { "type" : "string" }, - "institutionUpdate" : { - "$ref" : "#/components/schemas/InstitutionUpdateResponse" + "subunitType" : { + "type" : "string", + "enum" : [ "AOO", "UO" ] }, - "pricingPlan" : { + "taxCode" : { "type" : "string" - }, - "product" : { - "$ref" : "#/components/schemas/ProductInfo" - }, - "role" : { + } + } + }, + "InstitutionGeographicTaxonomies" : { + "title" : "InstitutionGeographicTaxonomies", + "type" : "object", + "properties" : { + "code" : { "type" : "string" }, - "state" : { - "type" : "string", - "enum" : [ "ACTIVE", "DELETED", "PENDING", "REJECTED", "SUSPENDED", "TOBEVALIDATED" ] - }, - "to" : { + "desc" : { "type" : "string" - }, - "updatedAt" : { - "type" : "string", - "format" : "date-time" } } }, @@ -4192,27 +3085,6 @@ } } }, - "InstitutionProducts" : { - "title" : "InstitutionProducts", - "type" : "object", - "properties" : { - "institutionId" : { - "type" : "string" - }, - "institutionName" : { - "type" : "string" - }, - "institutionRootName" : { - "type" : "string" - }, - "products" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/Product" - } - } - } - }, "InstitutionPut" : { "title" : "InstitutionPut", "type" : "object", @@ -4528,222 +3400,16 @@ "type" : "string" } } - }, - "InstitutionUpdateResponse" : { - "title" : "InstitutionUpdateResponse", - "type" : "object", - "properties" : { - "address" : { - "type" : "string" - }, - "aooParentCode" : { - "type" : "string" - }, - "businessRegisterPlace" : { - "type" : "string" - }, - "city" : { - "type" : "string" - }, - "country" : { - "type" : "string" - }, - "county" : { - "type" : "string" - }, - "dataProtectionOfficer" : { - "$ref" : "#/components/schemas/DataProtectionOfficerResponse" - }, - "description" : { - "type" : "string" - }, - "digitalAddress" : { - "type" : "string" - }, - "geographicTaxonomyCodes" : { - "type" : "array", - "items" : { - "type" : "string" - } - }, - "imported" : { - "type" : "boolean" - }, - "institutionType" : { - "type" : "string", - "enum" : [ "AS", "CON", "GSP", "PA", "PG", "PSP", "PT", "REC", "SA", "SCP" ] - }, - "paymentServiceProvider" : { - "$ref" : "#/components/schemas/PaymentServiceProviderResponse" - }, - "rea" : { - "type" : "string" - }, - "shareCapital" : { - "type" : "string" - }, - "subunitCode" : { - "type" : "string" - }, - "subunitType" : { - "type" : "string" - }, - "supportEmail" : { - "type" : "string" - }, - "supportPhone" : { - "type" : "string" - }, - "taxCode" : { - "type" : "string" - }, - "zipCode" : { - "type" : "string" - } - } - }, - "InstitutionsResponse" : { - "title" : "InstitutionsResponse", - "type" : "object", - "properties" : { - "institutions" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/InstitutionResponse" - } - } - } - }, - "OnboardedInstitutionResponse" : { - "title" : "OnboardedInstitutionResponse", - "type" : "object", - "properties" : { - "address" : { - "type" : "string" - }, - "aooParentCode" : { - "type" : "string" - }, - "attributes" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/AttributesResponse" - } - }, - "billing" : { - "$ref" : "#/components/schemas/Billing" - }, - "businessData" : { - "$ref" : "#/components/schemas/BusinessData" - }, - "dataProtectionOfficer" : { - "$ref" : "#/components/schemas/DataProtectionOfficerResponse" - }, - "description" : { - "type" : "string" - }, - "digitalAddress" : { - "type" : "string" - }, - "externalId" : { - "type" : "string" - }, - "geographicTaxonomies" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/GeoTaxonomies" - } - }, - "id" : { - "type" : "string" - }, - "institutionType" : { - "type" : "string", - "enum" : [ "AS", "CON", "GSP", "PA", "PG", "PSP", "PT", "REC", "SA", "SCP" ] - }, - "origin" : { - "type" : "string" - }, - "originId" : { - "type" : "string" - }, - "parentDescription" : { - "type" : "string" - }, - "paymentServiceProvider" : { - "$ref" : "#/components/schemas/PaymentServiceProviderResponse" - }, - "pricingPlan" : { - "type" : "string" - }, - "productInfo" : { - "$ref" : "#/components/schemas/ProductInfo" - }, - "role" : { - "type" : "string", - "enum" : [ "DELEGATE", "MANAGER", "OPERATOR", "SUB_DELEGATE" ] - }, - "rootParentId" : { - "type" : "string" - }, - "state" : { - "type" : "string" - }, - "subunitCode" : { - "type" : "string" - }, - "subunitType" : { - "type" : "string" - }, - "supportContact" : { - "$ref" : "#/components/schemas/SupportContact" - }, - "taxCode" : { - "type" : "string" - }, - "zipCode" : { - "type" : "string" - } - } - }, - "OnboardedProduct" : { - "title" : "OnboardedProduct", - "type" : "object", - "properties" : { - "contract" : { - "type" : "string" - }, - "createdAt" : { - "type" : "string", - "format" : "date-time" - }, - "env" : { - "type" : "string", - "enum" : [ "COLL", "DEV", "PROD", "ROOT" ] - }, - "productId" : { - "type" : "string" - }, - "productRole" : { - "type" : "string" - }, - "relationshipId" : { - "type" : "string" - }, - "role" : { - "type" : "string", - "enum" : [ "DELEGATE", "MANAGER", "OPERATOR", "SUB_DELEGATE" ] - }, - "status" : { - "type" : "string", - "enum" : [ "ACTIVE", "DELETED", "PENDING", "REJECTED", "SUSPENDED", "TOBEVALIDATED" ] - }, - "tokenId" : { - "type" : "string" - }, - "updatedAt" : { - "type" : "string", - "format" : "date-time" + }, + "InstitutionsResponse" : { + "title" : "InstitutionsResponse", + "type" : "object", + "properties" : { + "institutions" : { + "type" : "array", + "items" : { + "$ref" : "#/components/schemas/InstitutionResponse" + } } } }, @@ -4783,33 +3449,6 @@ } } }, - "OnboardedUsersResponse" : { - "title" : "OnboardedUsersResponse", - "type" : "object", - "properties" : { - "users" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/UserProductsResponse" - } - } - } - }, - "OnboardingInfoResponse" : { - "title" : "OnboardingInfoResponse", - "type" : "object", - "properties" : { - "institutions" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/OnboardedInstitutionResponse" - } - }, - "userId" : { - "type" : "string" - } - } - }, "OnboardingRequest" : { "title" : "OnboardingRequest", "type" : "object", @@ -5049,109 +3688,6 @@ "title" : "ProblemError", "type" : "object" }, - "Product" : { - "title" : "Product", - "type" : "object", - "properties" : { - "contract" : { - "type" : "string" - }, - "createdAt" : { - "type" : "string", - "format" : "date-time" - }, - "env" : { - "type" : "string", - "enum" : [ "COLL", "DEV", "PROD", "ROOT" ] - }, - "productId" : { - "type" : "string" - }, - "productRole" : { - "type" : "string" - }, - "role" : { - "type" : "string", - "enum" : [ "DELEGATE", "MANAGER", "OPERATOR", "SUB_DELEGATE" ] - }, - "status" : { - "type" : "string", - "enum" : [ "ACTIVE", "DELETED", "PENDING", "REJECTED", "SUSPENDED", "TOBEVALIDATED" ] - }, - "tokenId" : { - "type" : "string" - }, - "updatedAt" : { - "type" : "string", - "format" : "date-time" - } - } - }, - "ProductInfo" : { - "title" : "ProductInfo", - "type" : "object", - "properties" : { - "createdAt" : { - "type" : "string", - "format" : "date-time" - }, - "id" : { - "type" : "string" - }, - "role" : { - "type" : "string" - }, - "status" : { - "type" : "string" - } - } - }, - "RelationshipResult" : { - "title" : "RelationshipResult", - "type" : "object", - "properties" : { - "billing" : { - "$ref" : "#/components/schemas/BillingResponse" - }, - "createdAt" : { - "type" : "string", - "format" : "date-time" - }, - "from" : { - "type" : "string" - }, - "id" : { - "type" : "string" - }, - "institutionUpdate" : { - "$ref" : "#/components/schemas/InstitutionUpdateResponse" - }, - "pricingPlan" : { - "type" : "string" - }, - "product" : { - "$ref" : "#/components/schemas/ProductInfo" - }, - "role" : { - "type" : "string", - "enum" : [ "DELEGATE", "MANAGER", "OPERATOR", "SUB_DELEGATE" ] - }, - "state" : { - "type" : "string", - "enum" : [ "ACTIVE", "DELETED", "PENDING", "REJECTED", "SUSPENDED", "TOBEVALIDATED" ] - }, - "to" : { - "type" : "string" - }, - "tokenId" : { - "type" : "string" - }, - "updatedAt" : { - "type" : "string", - "format" : "date-time" - } - } - }, "RootParentResponse" : { "title" : "RootParentResponse", "type" : "object", @@ -5164,155 +3700,6 @@ } } }, - "SupportContact" : { - "title" : "SupportContact", - "type" : "object", - "properties" : { - "supportEmail" : { - "type" : "string" - }, - "supportPhone" : { - "type" : "string" - } - } - }, - "UserInfoResponse" : { - "title" : "UserInfoResponse", - "type" : "object", - "properties" : { - "email" : { - "type" : "string" - }, - "id" : { - "type" : "string" - }, - "name" : { - "type" : "string" - }, - "products" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/OnboardedProduct" - } - }, - "surname" : { - "type" : "string" - }, - "taxCode" : { - "type" : "string" - } - } - }, - "UserNotificationBindingsResponse" : { - "title" : "UserNotificationBindingsResponse", - "type" : "object", - "properties" : { - "bindings" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/UserNotificationResponse" - } - } - } - }, - "UserNotificationResponse" : { - "title" : "UserNotificationResponse", - "type" : "object", - "properties" : { - "createdAt" : { - "type" : "string", - "format" : "date-time" - }, - "eventType" : { - "type" : "string", - "enum" : [ "ADD", "UPDATE" ] - }, - "id" : { - "type" : "string" - }, - "institutionId" : { - "type" : "string" - }, - "onboardingTokenId" : { - "type" : "string" - }, - "productId" : { - "type" : "string" - }, - "updatedAt" : { - "type" : "string", - "format" : "date-time" - }, - "user" : { - "$ref" : "#/components/schemas/UserToNotify" - } - } - }, - "UserProductsResponse" : { - "title" : "UserProductsResponse", - "type" : "object", - "properties" : { - "bindings" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/InstitutionProducts" - } - }, - "id" : { - "type" : "string" - } - } - }, - "UserResponse" : { - "title" : "UserResponse", - "type" : "object", - "properties" : { - "email" : { - "type" : "string" - }, - "id" : { - "type" : "string" - }, - "name" : { - "type" : "string" - }, - "surname" : { - "type" : "string" - }, - "taxCode" : { - "type" : "string" - } - } - }, - "UserToNotify" : { - "title" : "UserToNotify", - "type" : "object", - "properties" : { - "email" : { - "type" : "string" - }, - "familyName" : { - "type" : "string" - }, - "name" : { - "type" : "string" - }, - "productRole" : { - "type" : "string" - }, - "relationshipStatus" : { - "type" : "string", - "enum" : [ "ACTIVE", "DELETED", "PENDING", "REJECTED", "SUSPENDED", "TOBEVALIDATED" ] - }, - "role" : { - "type" : "string", - "enum" : [ "DELEGATE", "MANAGER", "OPERATOR", "SUB_DELEGATE" ] - }, - "userId" : { - "type" : "string" - } - } - }, "UserToOnboard" : { "title" : "UserToOnboard", "type" : "object", @@ -5347,18 +3734,6 @@ "type" : "string" } } - }, - "UsersNotificationResponse" : { - "title" : "UsersNotificationResponse", - "type" : "object", - "properties" : { - "users" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/UserNotificationBindingsResponse" - } - } - } } }, "securitySchemes" : { diff --git a/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java b/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java index 4bdaf3501..e0dd11aba 100644 --- a/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java +++ b/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java @@ -47,18 +47,12 @@ class SwaggerConfigTest { @MockBean OnboardingService onboardingService; - @MockBean - UserService userService; - @MockBean QueueNotificationService queueNotificationService; @Autowired WebApplicationContext context; - @MockBean - UserRelationshipService userRelationshipService; - @MockBean DelegationService delegationService; diff --git a/connector-api/src/main/java/it/pagopa/selfcare/mscore/api/UserConnector.java b/connector-api/src/main/java/it/pagopa/selfcare/mscore/api/UserConnector.java deleted file mode 100644 index 222d78d44..000000000 --- a/connector-api/src/main/java/it/pagopa/selfcare/mscore/api/UserConnector.java +++ /dev/null @@ -1,63 +0,0 @@ -package it.pagopa.selfcare.mscore.api; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionFilter; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.mscore.model.user.UserInfo; -import org.springframework.lang.Nullable; - -import java.time.OffsetDateTime; -import java.util.List; - -public interface UserConnector { - - List findAllValidUsers(Integer page, Integer size, String productId); - - OnboardedUser findById(String userId); - - /** - * Necessario specificare almeno uno tra relationshipId e tokenId. - * - * @param userId id utente - * @param relationshipId id relationship - * @param token token - * @param state nuovo stato - */ - void findAndUpdateState(String userId, @Nullable String relationshipId, @Nullable Token token, RelationshipState state); - - void findAndUpdateStateWithOptionalFilter(String userId, String institutionId, String productId, PartyRole role, String productRole, RelationshipState state); - - void findAndUpdate(OnboardedUser onboardedUser, String id, String institutionId, OnboardedProduct product, UserBinding bindings); - - OnboardedUser findOnboardedManager(String institutionId, String productId, List state); - - OnboardedUser findAndCreate(String id, UserBinding binding); - - List findActiveInstitutionUser(String userId, String institutionId); - - List findUsersByInstitutionIdAndProductId(String institutionId, String productId); - - List findWithFilter(String institutionId, String personId, List roles, List states, List products, List productRoles); - - OnboardedUser findByRelationshipId(String relationshipId); - - void findAndRemoveProduct(String userId, String institutionId, OnboardedProduct product); - - List findAllByIds(List users); - - List findAllByExistingIds(List users); - - List updateUserBindingCreatedAt(String institutionId, String productId, List users, OffsetDateTime createdAt); - - List findUserInstitutionAggregation(UserInstitutionFilter filter); - - List findByInstitutionId(String institutionId); - - List getUserInfo(String userId, String institutionId, String[] states); - -} diff --git a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/UserConnectorImpl.java b/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/UserConnectorImpl.java deleted file mode 100644 index 9ebca961b..000000000 --- a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/UserConnectorImpl.java +++ /dev/null @@ -1,428 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.connector.dao.model.UserEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.aggregation.UserInstitutionAggregationEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.inner.OnboardedProductEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.inner.UserBindingEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.mapper.UserEntityMapper; -import it.pagopa.selfcare.mscore.connector.dao.model.mapper.UserInstitutionAggregationMapper; -import it.pagopa.selfcare.mscore.constant.Env; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.exception.InvalidRequestException; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionFilter; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.mscore.model.user.UserInfo; -import it.pagopa.selfcare.product.entity.Product; -import it.pagopa.selfcare.product.entity.ProductRoleInfo; -import it.pagopa.selfcare.product.service.ProductService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.mongodb.core.FindAndModifyOptions; -import org.springframework.data.mongodb.core.MongoOperations; -import org.springframework.data.mongodb.core.aggregation.Aggregation; -import org.springframework.data.mongodb.core.aggregation.GraphLookupOperation; -import org.springframework.data.mongodb.core.aggregation.MatchOperation; -import org.springframework.data.mongodb.core.aggregation.UnwindOperation; -import org.springframework.data.mongodb.core.query.Criteria; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Component; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -import java.time.OffsetDateTime; -import java.util.*; -import java.util.stream.Collectors; - -import static it.pagopa.selfcare.mscore.constant.CustomError.*; - -@Slf4j -@Component -@RequiredArgsConstructor -public class UserConnectorImpl implements UserConnector { - - private static final String CURRENT_PRODUCT = "current."; - private static final String CURRENT_ANY = "$[]"; - private static final String CURRENT_PRODUCT_REF = "$[current]"; - private static final String CURRENT_USER_BINDING = "currentUserBinding."; - private static final String CURRENT_USER_BINDING_REF = "$[currentUserBinding]"; - - private static final List VALID_USER_RELATIONSHIPS = List.of(RelationshipState.ACTIVE.name(), RelationshipState.DELETED.name(), RelationshipState.SUSPENDED.name()); - private final UserRepository repository; - - private final UserEntityMapper userMapper; - - private final UserInstitutionAggregationMapper userInstitutionAggregationMapper; - - private final MongoOperations mongoOperations; - - private final ProductService productService; - - - /** - * This query retrieves all the users having status in VALID_USER_RELATIONSHIPS for the given productId - * - * @param page - * @param size - * @param productId - * @return List of onboarded users - */ - @Override - public List findAllValidUsers(Integer page, Integer size, String productId) { - Pageable pageable = PageRequest.of(page, size); - Query queryMatch = Query.query(Criteria.where(UserEntity.Fields.bindings.name()) - .elemMatch(Criteria.where(UserBinding.Fields.products.name()) - .elemMatch(CriteriaBuilder.builder() - .isIfNotNull(OnboardedProductEntity.Fields.productId.name(), productId) - .build() - .and(OnboardedProductEntity.Fields.status.name()).in(VALID_USER_RELATIONSHIPS)))); - return repository.find(queryMatch, pageable, UserEntity.class) - .stream() - .map(userMapper::toOnboardedUser) - .collect(Collectors.toList()); - } - - @Override - public OnboardedUser findById(String userId) { - Optional entityOpt = repository.findById(userId); - return entityOpt.map(userMapper::toOnboardedUser) - .orElseThrow(() -> { - log.error(String.format(USER_NOT_FOUND_ERROR.getMessage(), userId)); - return new ResourceNotFoundException(String.format(USER_NOT_FOUND_ERROR.getMessage(), userId), USER_NOT_FOUND_ERROR.getCode()); - }); - } - - @Override - public List findAllByIds(List users) { - return findAll(users, false); - } - - @Override - public List findAllByExistingIds(List users) { - return findAll(users, true); - } - - private List findAll(List userIds, boolean existingOnly) { - List userList = new ArrayList<>(); - Set remainingUserIds = new HashSet<>(userIds); - - repository.findAllById(userIds).forEach(userEntity -> { - userList.add(userMapper.toOnboardedUser(userEntity)); - remainingUserIds.remove(userEntity.getId()); - }); - - if (!existingOnly && !remainingUserIds.isEmpty()) { - String missingUserIds = String.join(",", remainingUserIds); - throw new ResourceNotFoundException(String.format(USERS_NOT_FOUND_ERROR.getMessage(), missingUserIds), USERS_NOT_FOUND_ERROR.getCode()); - } - return userList; - } - - - @Override - public void findAndUpdateState(String userId, @Nullable String relationshipId, @Nullable Token token, RelationshipState state) { - Query query = Query.query(Criteria.where(UserEntity.Fields.id.name()).is(userId)); - Update update = new Update() - .set(constructQuery(CURRENT_ANY, UserBinding.Fields.products.name(), CURRENT_PRODUCT_REF, OnboardedProduct.Fields.status.name()), state) - .set(constructQuery(CURRENT_ANY, UserBinding.Fields.products.name(), CURRENT_PRODUCT_REF, OnboardedProduct.Fields.updatedAt.name()), OffsetDateTime.now()); - if (relationshipId != null) { - update.filterArray(Criteria.where(CURRENT_PRODUCT + OnboardedProduct.Fields.relationshipId.name()).is(relationshipId)); - } - if (token != null) { - update.filterArray(Criteria.where(CURRENT_PRODUCT + OnboardedProduct.Fields.tokenId.name()).is(token.getId())); - if (token.getContractSigned() != null) { - update.set(constructQuery(CURRENT_ANY, UserBinding.Fields.products.name(), CURRENT_PRODUCT_REF, OnboardedProduct.Fields.contract.name()), token.getContractSigned()); - } - } - FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().upsert(false).returnNew(false); - repository.findAndModify(query, update, findAndModifyOptions, UserEntity.class); - } - - @Override - public void findAndUpdateStateWithOptionalFilter(String userId, String institutionId, String productId, PartyRole role, String productRole, RelationshipState state) { - - checkRoles(productId, role, productRole); - - Query query = Query.query(Criteria.where(UserEntity.Fields.id.name()).is(userId)); - Update update = new Update(); - - boolean productFilterIsPresent = role != null || StringUtils.hasText(productId) || StringUtils.hasText(productRole); - - if (StringUtils.hasText(institutionId) && productFilterIsPresent) { - filterForInstution(update, institutionId); - filterForProduct(update, role, productRole, productId); - setUpdate(update, state, CURRENT_USER_BINDING_REF, CURRENT_PRODUCT_REF); - } else if (StringUtils.hasText(institutionId)) { - filterForInstution(update, institutionId); - setUpdate(update, state, CURRENT_USER_BINDING_REF, CURRENT_ANY); - } else if (productFilterIsPresent) { - filterForProduct(update, role, productRole, productId); - setUpdate(update, state, CURRENT_ANY, CURRENT_PRODUCT_REF); - } else { - setUpdate(update, state, CURRENT_ANY, CURRENT_ANY); - } - - FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().upsert(false).returnNew(false); - repository.findAndModify(query, update, findAndModifyOptions, UserEntity.class); - } - - private void filterForProduct(Update update, PartyRole role, String productRole, String productId) { - update.filterArray(constructCriteria(role, productRole, productId)); - } - - private void filterForInstution(Update update, String institutionId) { - update.filterArray(Criteria.where(CURRENT_USER_BINDING + UserBinding.Fields.institutionId.name()).is(institutionId)); - } - - private void setUpdate(Update update, RelationshipState state, String firstCurrent, String secondCurrent) { - update.set(constructQuery(firstCurrent, UserBinding.Fields.products.name(), secondCurrent, OnboardedProduct.Fields.status.name()), state) - .set(constructQuery(firstCurrent, UserBinding.Fields.products.name(), secondCurrent, OnboardedProduct.Fields.updatedAt.name()), OffsetDateTime.now()); - } - - @Override - public void findAndUpdate(OnboardedUser onboardedUser, String userId, String institutionId, OnboardedProduct product, UserBinding bindings) { - Query query = Query.query(Criteria.where(UserEntity.Fields.id.name()).is(userId)); - Update update = new Update(); - Optional opt = onboardedUser.getBindings().stream() - .filter(userBinding -> institutionId.equalsIgnoreCase(userBinding.getInstitutionId())) - .findFirst(); - if (opt.isPresent()) { - update.addToSet(constructQuery(CURRENT_USER_BINDING_REF, UserBinding.Fields.products.name()), product); - update.filterArray(Criteria.where(CURRENT_USER_BINDING + UserBinding.Fields.institutionId.name()).is(institutionId)); - } else { - update.addToSet(UserEntity.Fields.bindings.name(), bindings); - } - FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().upsert(true).returnNew(true); - repository.findAndModify(query, update, findAndModifyOptions, UserEntity.class); - } - - @Override - public OnboardedUser findAndCreate(String id, UserBinding binding) { - Query query = Query.query(Criteria.where(UserEntity.Fields.id.name()).is(id)); - Update update = new Update(); - if (binding != null) { - update.addToSet(UserEntity.Fields.bindings.name(), binding); - } - update.set(UserEntity.Fields.updatedAt.name(), OffsetDateTime.now()); - update.set(UserEntity.Fields.createdAt.name(), OffsetDateTime.now()); - FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().upsert(true).returnNew(true); - return userMapper.toOnboardedUser(repository.findAndModify(query, update, findAndModifyOptions, UserEntity.class)); - } - - @Override - public OnboardedUser findOnboardedManager(String institutionId, String productId, List state) { - - Query query = Query.query(Criteria.where(UserEntity.Fields.bindings.name()) - .elemMatch(Criteria.where(UserBinding.Fields.institutionId.name()).is(institutionId) - .and(UserBinding.Fields.products.name()) - .elemMatch(Criteria.where(OnboardedProduct.Fields.productId.name()).is(productId) - .and(OnboardedProduct.Fields.role.name()).is(PartyRole.MANAGER) - .and(OnboardedProduct.Fields.env.name()).is(Env.ROOT) - .and(OnboardedProduct.Fields.status.name()).in(state)))); - - return repository.find(query, UserEntity.class).stream() - .findFirst() - .map(userMapper::toOnboardedUser) - .orElseThrow(() -> new ResourceNotFoundException(String.format(GET_INSTITUTION_MANAGER_NOT_FOUND.getMessage(), institutionId, productId), - GET_INSTITUTION_MANAGER_NOT_FOUND.getCode())); - } - - @Override - public List findActiveInstitutionUser(String userId, String institutionId) { - Query query = Query.query(Criteria.where(UserEntity.Fields.id.name()).is(userId)) - .addCriteria(Criteria.where(UserEntity.Fields.bindings.name()) - .elemMatch(Criteria.where(UserBinding.Fields.institutionId.name()).is(institutionId))); - - return repository.find(query, UserEntity.class).stream() - .map(userMapper::toOnboardedUser) - .collect(Collectors.toList()); - } - - @Override - public List findUsersByInstitutionIdAndProductId(String institutionId, String productId) { - Query query = Query.query(Criteria.where(UserEntity.Fields.bindings.name()) - .elemMatch(Criteria.where(UserBinding.Fields.institutionId.name()).is(institutionId) - .and(UserBinding.Fields.products.name()).elemMatch( - Criteria.where(OnboardedProductEntity.Fields.productId.name()).is(productId) - .and(OnboardedProductEntity.Fields.status.name()).is(RelationshipState.ACTIVE.name()) - ))); - - return repository.find(query, UserEntity.class).stream() - .map(UserEntity::getId) - .toList(); - } - - @Override - public List findWithFilter(String institutionId, String personId, List roles, List states, List products, List productRoles) { - Criteria criteria = Criteria.where(UserEntity.Fields.bindings.name()) - .elemMatch(constructElemMatch(institutionId, roles, states, productRoles, products)); - if (personId != null) { - criteria = criteria.and(UserEntity.Fields.id.name()).is(personId); - } - - return repository.find(new Query(criteria), UserEntity.class).stream() - .map(userMapper::toOnboardedUser) - .collect(Collectors.toList()); - } - - @Override - public OnboardedUser findByRelationshipId(String relationshipId) { - Query query = Query.query(Criteria.where(UserEntity.Fields.bindings.name()) - .elemMatch(Criteria.where(UserBinding.Fields.products.name()) - .elemMatch(Criteria.where(OnboardedProduct.Fields.relationshipId.name()).in(relationshipId)))); - - return repository.find(query, UserEntity.class).stream() - .findFirst() - .map(userMapper::toOnboardedUser) - .orElseThrow(() -> new ResourceNotFoundException(String.format(RELATIONSHIP_ID_NOT_FOUND.getMessage(), relationshipId), - RELATIONSHIP_ID_NOT_FOUND.getCode())); - } - - @Override - public void findAndRemoveProduct(String userId, String institutionId, OnboardedProduct product) { - Query query = Query.query(Criteria.where(UserEntity.Fields.id.name()).is(userId)); - Update update = new Update(); - - update.pull(constructQuery(CURRENT_USER_BINDING_REF, UserBinding.Fields.products.name()), product); - update.filterArray(Criteria.where(CURRENT_USER_BINDING + UserBinding.Fields.institutionId.name()).is(institutionId)); - - FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().upsert(true).returnNew(true); - repository.findAndModify(query, update, findAndModifyOptions, UserEntity.class); - } - - @Override - public List updateUserBindingCreatedAt(String institutionId, String productId, List usersId, OffsetDateTime createdAt) { - List updatedUsersBindings = new ArrayList<>(); - - usersId.forEach(userId -> { - Query query = Query.query(Criteria.where(UserEntity.Fields.id.name()).is(userId)); - - Update update = new Update(); - update.set(constructQuery(CURRENT_USER_BINDING_REF, UserBindingEntity.Fields.products.name(), CURRENT_PRODUCT_REF, OnboardedProductEntity.Fields.createdAt.name()), createdAt) - .set(constructQuery(CURRENT_USER_BINDING_REF, UserBindingEntity.Fields.products.name(), CURRENT_PRODUCT_REF, OnboardedProductEntity.Fields.updatedAt.name()), OffsetDateTime.now()) - .filterArray(Criteria.where(CURRENT_USER_BINDING + UserBindingEntity.Fields.institutionId.name()).is(institutionId)) - .filterArray(Criteria.where(CURRENT_PRODUCT + OnboardedProductEntity.Fields.productId.name()).is(productId)); - - Update updateUserEntityUpdatedAt = new Update(); - updateUserEntityUpdatedAt.set(UserEntity.Fields.updatedAt.name(), OffsetDateTime.now()); - - FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().upsert(false).returnNew(true); - repository.findAndModify(query, update, findAndModifyOptions, UserEntity.class); - updatedUsersBindings.add(userMapper.toOnboardedUser(repository.findAndModify(query, updateUserEntityUpdatedAt, findAndModifyOptions, UserEntity.class))); - }); - - return updatedUsersBindings; - } - - @Override - public List findByInstitutionId(String institutionId) { - Criteria criteria = Criteria.where(UserEntity.Fields.bindings.name()) - .elemMatch(Criteria.where(UserBinding.Fields.institutionId.name()) - .is(institutionId)); - return repository.find(new Query(criteria), UserEntity.class).stream() - .map(userEntity -> userMapper.toUserInfoByFirstInstitution(userEntity, institutionId)) - .collect(Collectors.toList()); - } - - @Override - public List getUserInfo(String userId, String institutionId, String[] states) { - - List criterias = new ArrayList<>(); - MatchOperation matchUserId = Aggregation.match(Criteria.where("_id").is(userId)); - - GraphLookupOperation lookup = Aggregation.graphLookup("Institution") - .startWith("$bindings.institutionId") - .connectFrom("institutionId") - .connectTo("_id").as("institutions"); - - UnwindOperation unwindBindings = Aggregation.unwind("$bindings"); - UnwindOperation unwindProducts = Aggregation.unwind("$bindings.products"); - - if (Objects.nonNull(states) && states.length > 0) { - criterias.add(Criteria.where("bindings.products.status").in(states)); - } - - if (Objects.nonNull(institutionId)) { - criterias.add(Criteria.where("bindings.institutionId").is(institutionId)); - } - - MatchOperation matchInstitutionExist = Aggregation.match(Criteria.where("institutions").size(1)); - MatchOperation matchOperation; - if(!criterias.isEmpty()) { - matchOperation = new MatchOperation(new Criteria().andOperator(criterias.toArray(new Criteria[criterias.size()]))); - } else { - matchOperation = new MatchOperation(new Criteria()); - } - Aggregation aggregation = Aggregation.newAggregation(matchUserId, unwindBindings, lookup, matchInstitutionExist, unwindProducts, matchOperation); - - return mongoOperations.aggregate(aggregation, "User", UserInstitutionAggregation.class).getMappedResults(); - } - - private void checkRoles(String productId, PartyRole role, String productRole) { - if (StringUtils.hasText(productRole)) { - Assert.notNull(role, ROLE_IS_NULL.getMessage()); - Product product = productService.getProduct(productId); - ProductRoleInfo productRoleInfo = product.getRoleMappings().get(it.pagopa.selfcare.onboarding.common.PartyRole.valueOf(role.name())); - if (productRoleInfo == null) { - throw new InvalidRequestException(ROLE_NOT_FOUND.getMessage(), ROLE_NOT_FOUND.getCode()); - } - boolean roleExists = productRoleInfo.getRoles().stream() - .anyMatch(prodRole -> prodRole.getCode().equals(productRole)); - if (!roleExists) { - throw new InvalidRequestException(PRODUCT_ROLE_NOT_FOUND.getMessage(), PRODUCT_ROLE_NOT_FOUND.getCode()); - } - } - } - - @Override - public List findUserInstitutionAggregation(UserInstitutionFilter filter) { - List userInstitutionAggregationEntities = - repository.findUserInstitutionAggregation(filter, UserInstitutionAggregationEntity.class); - return userInstitutionAggregationEntities.stream() - .map(userInstitutionAggregationMapper::constructUserInstitutionAggregation) - .collect(Collectors.toList()); - } - - private Criteria constructElemMatch(String institutionId, List roles, List states, List productRoles, List products) { - return CriteriaBuilder.builder() - .isIfNotNull(UserBinding.Fields.institutionId.name(), institutionId) - .build() - .and(UserBinding.Fields.products.name()) - .elemMatch(constructCriteria(roles, states, productRoles, products)); - } - - private Criteria constructCriteria(PartyRole role, String productRole, String product) { - return CriteriaBuilder.builder() - .isIfNotNull(CURRENT_PRODUCT + OnboardedProductEntity.Fields.role.name(), role != null ? role.name() : null) - .isIfNotNull(CURRENT_PRODUCT + OnboardedProductEntity.Fields.productId.name(), product) - .isIfNotNull(CURRENT_PRODUCT + OnboardedProductEntity.Fields.productRole.name(), productRole) - .build(); - } - - private Criteria constructCriteria(List roles, List states, List productRoles, List products) { - return CriteriaBuilder.builder() - .inIfNotEmpty(OnboardedProductEntity.Fields.role.name(), roles) - .inIfNotEmpty(OnboardedProductEntity.Fields.status.name(), states) - .inIfNotEmpty(OnboardedProductEntity.Fields.productId.name(), products) - .inIfNotEmpty(OnboardedProductEntity.Fields.productRole.name(), productRoles) - .build(); - - } - - private String constructQuery(String... variables) { - StringBuilder builder = new StringBuilder(); - builder.append(UserEntity.Fields.bindings.name()); - Arrays.stream(variables).forEach(s -> builder.append(".").append(s)); - return builder.toString(); - } -} diff --git a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/UserConnectorImplTest.java b/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/UserConnectorImplTest.java deleted file mode 100644 index f00dc9833..000000000 --- a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/UserConnectorImplTest.java +++ /dev/null @@ -1,681 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.connector.dao.model.InstitutionEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.UserEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.aggregation.UserInstitutionAggregationEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.aggregation.UserInstitutionBindingEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.inner.OnboardedProductEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.inner.OnboardingEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.inner.UserBindingEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.mapper.*; -import it.pagopa.selfcare.mscore.constant.Env; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionBinding; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionFilter; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.product.entity.Product; -import it.pagopa.selfcare.product.entity.ProductRole; -import it.pagopa.selfcare.product.entity.ProductRoleInfo; -import it.pagopa.selfcare.product.service.ProductService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.*; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.data.mongodb.core.FindAndModifyOptions; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.aggregation.Aggregation; -import org.springframework.data.mongodb.core.aggregation.AggregationResults; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Optional; - -import static it.pagopa.selfcare.commons.utils.TestUtils.mockInstance; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class UserConnectorImplTest { - @InjectMocks - private UserConnectorImpl userConnectorImpl; - - @Mock - private UserRepository userRepository; - - @Spy - private UserEntityMapper userMapper = new UserEntityMapperImpl(); - - @Mock - private ProductService productService; - - @Spy - private OnboardedProductMapper productMapper = new OnboardedProductMapperImpl(); - - @Spy - private UserInstitutionAggregationMapper userInstitutionAggregationMapper = new UserInstitutionAggregationMapperImpl(); - - @Captor - ArgumentCaptor queryArgumentCaptor; - - @Captor - ArgumentCaptor updateArgumentCaptor; - @Captor - ArgumentCaptor pageableArgumentCaptor; - - @Captor - ArgumentCaptor findAndModifyOptionsArgumentCaptor; - - @Mock - private MongoTemplate mongoTemplate; - - static UserInstitutionAggregation dummyUserInstitution; - - static UserEntity dummyUserEntity; - - static { - dummyUserInstitution = new UserInstitutionAggregation(); - dummyUserInstitution.setId("userId"); - Institution institution = new Institution(); - institution.setId("id"); - dummyUserInstitution.setInstitutions(List.of(institution)); - UserInstitutionBinding bindings = new UserInstitutionBinding(); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setProductId("prod-io"); - bindings.setProducts(onboardedProduct); - dummyUserInstitution.setBindings(bindings); - - dummyUserEntity = new UserEntity(); - UserBindingEntity binding = new UserBindingEntity(); - OnboardedProductEntity onboardedProductEntity = new OnboardedProductEntity(); - onboardedProductEntity.setStatus(RelationshipState.ACTIVE); - onboardedProductEntity.setProductId("product"); - binding.setProducts(List.of(onboardedProductEntity)); - ArrayList userBindingEntityList = new ArrayList<>(); - dummyUserEntity.setBindings(userBindingEntityList); - } - - @Test - void findAllPaged(){ - //given - final String productId = "product"; - final Integer page = 0; - final Integer size = 1; - Page userEntities = new PageImpl<>(List.of(dummyUserEntity)); - - doReturn(userEntities).when(userRepository).find(any(), any(), any()); - //when - List users = userConnectorImpl.findAllValidUsers(page, size, productId); - //then - assertFalse(users.isEmpty()); - assertEquals(1, users.size()); - verify(userRepository, times(1)).find(queryArgumentCaptor.capture(), pageableArgumentCaptor.capture(), eq(UserEntity.class)); - Query capturedQuery = queryArgumentCaptor.getValue(); - assertTrue(capturedQuery.getQueryObject().toString().contains(productId)); - } - - @Test - void findAllPagedWithEmptyProductId(){ - //given - final Integer page = 0; - final Integer size = 1; - dummyUserEntity.getBindings().forEach(obj -> obj.getProducts().get(0).setProductId(null)); - Page userEntities = new PageImpl<>(List.of(dummyUserEntity)); - doReturn(userEntities).when(userRepository).find(any(), any(), any()); - //when - List users = userConnectorImpl.findAllValidUsers(page, size, null); - //then - assertFalse(users.isEmpty()); - assertEquals(1, users.size()); - verify(userRepository, times(1)).find(queryArgumentCaptor.capture(), pageableArgumentCaptor.capture(), eq(UserEntity.class)); - } - - private UserBindingEntity dummyUserBindingEntity() { - UserBindingEntity dummyUserBindingEntity = new UserBindingEntity(); - dummyUserBindingEntity.setInstitutionId("42"); - dummyUserBindingEntity.setProducts(new ArrayList<>()); - return dummyUserBindingEntity; - } - - @Test - void findById() { - UserEntity userEntity = new UserEntity(); - when(userRepository.findById(any())).thenReturn(Optional.of(userEntity)); - assertNotNull(userConnectorImpl.findById("id")); - } - - @Test - void findById2() { - when(userRepository.findById(any())).thenReturn(Optional.empty()); - assertThrows(ResourceNotFoundException.class, () -> userConnectorImpl.findById("id")); - } - - @Test - void findAllByIds() { - List userEntities = new ArrayList<>(); - UserEntity userEntity = new UserEntity(); - userEntity.setId("id"); - userEntities.add(userEntity); - when(userRepository.findAllById(any())).thenReturn(userEntities); - List ids = new ArrayList<>(); - ids.add("id1"); - assertThrows(ResourceNotFoundException.class, () -> userConnectorImpl.findAllByIds(ids)); - } - - @Test - void findAllByIds2() { - List userEntities = new ArrayList<>(); - UserEntity userEntity = new UserEntity(); - userEntity.setId("id1"); - userEntities.add(userEntity); - when(userRepository.findAllById(any())).thenReturn(userEntities); - List users = new ArrayList<>(); - users.add("id1"); - assertNotNull(userConnectorImpl.findAllByIds(users)); - } - - @Test - void findAllExistingByIds2() { - List userEntities = new ArrayList<>(); - UserEntity userEntity = new UserEntity(); - userEntity.setId("id1"); - userEntities.add(userEntity); - when(userRepository.findAllById(any())).thenReturn(userEntities); - List users = new ArrayList<>(); - users.add("id1"); - assertNotNull(userConnectorImpl.findAllByExistingIds(users)); - } - - @Test - void testFindAndUpdateState() { - UserEntity userEntity = new UserEntity(); - userEntity.setBindings(new ArrayList<>()); - userEntity.setCreatedAt(null); - userEntity.setId("42"); - userEntity.setUpdatedAt(null); - Token token = new Token(); - token.setContractSigned("contract signed"); - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(userEntity); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findAndUpdateState("42", "42", token, RelationshipState.PENDING)); - } - - @Test - void findAndUpdateStateByInstitutionAndProduct() { - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(new UserEntity()); - Product product = mock(Product.class); - EnumMap map = mock(EnumMap.class); - ProductRoleInfo productRoleInfo = mock(ProductRoleInfo.class); - ProductRole productRole = mock(ProductRole.class); - when(productRole.getCode()).thenReturn("productRole"); - when(productRoleInfo.getRoles()).thenReturn(List.of(productRole)); - when(map.get(it.pagopa.selfcare.onboarding.common.PartyRole.DELEGATE)).thenReturn(productRoleInfo); - when(product.getRoleMappings()).thenReturn(map); - - when(productService.getProduct(anyString())).thenReturn(product); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findAndUpdateStateWithOptionalFilter("42", "42", "productId", PartyRole.DELEGATE, "productRole", RelationshipState.PENDING)); - } - - @Test - void findAndUpdateStateByInstitutionId() { - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(new UserEntity()); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findAndUpdateStateWithOptionalFilter("42", "42", null, null, null, RelationshipState.PENDING)); - } - - @Test - void findAndUpdateStateByProductId() { - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(new UserEntity()); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findAndUpdateStateWithOptionalFilter("42", null, "productId", null, null, RelationshipState.PENDING)); - } - - @Test - void findAndUpdateStateWithoutFilter() { - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(new UserEntity()); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findAndUpdateStateWithOptionalFilter("42", null, null, null, null, RelationshipState.PENDING)); - } - - @Test - void findAndUpdateStateByInstitutionAndProductWithoutProductRole() { - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(new UserEntity()); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findAndUpdateStateWithOptionalFilter("42", "42", "productId", PartyRole.DELEGATE, null, RelationshipState.PENDING)); - } - - - @Test - void testFindAndUpdate() { - UserEntity userEntity = new UserEntity(); - userEntity.setBindings(new ArrayList<>()); - userEntity.setCreatedAt(null); - userEntity.setId("42"); - userEntity.setUpdatedAt(null); - when(userRepository.findAndModify(any(), any(), any(), any())).thenReturn(userEntity); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("role"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("42"); - userBinding.setProducts(new ArrayList<>()); - - OnboardedUser user = new OnboardedUser(); - List bindings = new ArrayList<>(); - UserBinding binding = new UserBinding(); - binding.setInstitutionId("42"); - bindings.add(binding); - user.setBindings(bindings); - userConnectorImpl.findAndUpdate(user, "42", "42", onboardedProduct, userBinding); - verify(userRepository).findAndModify(any(), any(), any(), any()); - } - - @Test - void testFindAndUpdate2() { - UserEntity userEntity = new UserEntity(); - userEntity.setBindings(new ArrayList<>()); - userEntity.setCreatedAt(null); - userEntity.setId("42"); - userEntity.setUpdatedAt(null); - when(userRepository.findAndModify(any(), any(), any(), any())).thenReturn(userEntity); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("role"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("42"); - userBinding.setProducts(new ArrayList<>()); - - OnboardedUser user = new OnboardedUser(); - user.setBindings(new ArrayList<>()); - userConnectorImpl.findAndUpdate(user, "42", "42", onboardedProduct, userBinding); - verify(userRepository).findAndModify(any(), any(), any(), any()); - } - - @Test - void testFindAndCreate() { - UserEntity userEntity = new UserEntity(); - userEntity.setBindings(new ArrayList<>()); - userEntity.setCreatedAt(null); - userEntity.setId("42"); - userEntity.setUpdatedAt(null); - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(userEntity); - userConnectorImpl.findAndCreate("42", new UserBinding()); - verify(userRepository).findAndModify(any(), any(), any(), any()); - } - - @Test - void testFindAndCreate2() { - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenThrow(new ResourceNotFoundException("An error occurred", "Code")); - UserBinding userBinding = new UserBinding(); - assertThrows(ResourceNotFoundException.class, - () -> userConnectorImpl.findAndCreate("42", userBinding)); - verify(userRepository).findAndModify(any(), any(), any(), any()); - } - - @Test - void testFindAndCreate3() { - UserEntity userEntity = new UserEntity(); - userEntity.setBindings(new ArrayList<>()); - userEntity.setCreatedAt(null); - userEntity.setId("42"); - userEntity.setUpdatedAt(null); - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(userEntity); - userConnectorImpl.findAndCreate("42", null); - verify(userRepository).findAndModify(any(), any(), any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findOnboardedManager(String, String, List)} - */ - @Test - void testFindOnboardedManager() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - List states = new ArrayList<>(); - Assertions.assertThrows(ResourceNotFoundException.class, () -> userConnectorImpl.findOnboardedManager("42", "42", states)); - } - - /** - * Method under test: {@link UserConnector#findActiveInstitutionUser(String, String)} - */ - @Test - void testFindAdminWithFilter() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - assertTrue(userConnectorImpl.findActiveInstitutionUser("42", "42").isEmpty()); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnector#findActiveInstitutionUser(String, String)} - */ - @Test - void testFindAdminWithFilter4() { - when(userRepository.find(any(), any())) - .thenThrow(new ResourceNotFoundException("An error occurred", ".")); - assertThrows(ResourceNotFoundException.class, - () -> userConnectorImpl.findActiveInstitutionUser("42", "42")); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findWithFilter(String, String, List, List, List, List)} - */ - @Test - void testFindWithFilter() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - ArrayList roles = new ArrayList<>(); - ArrayList states = new ArrayList<>(); - ArrayList products = new ArrayList<>(); - assertTrue(userConnectorImpl.findWithFilter("42", "42", roles, states, products, new ArrayList<>()).isEmpty()); - verify(userRepository).find(any(), any()); - } - - - /** - * Method under test: {@link UserConnectorImpl#findWithFilter(String, String, List, List, List, List)} - */ - @Test - void testFindWithFilter4() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - - ArrayList partyRoleList = new ArrayList<>(); - partyRoleList.add(PartyRole.MANAGER); - ArrayList states = new ArrayList<>(); - ArrayList products = new ArrayList<>(); - assertTrue( - userConnectorImpl.findWithFilter("42", "42", partyRoleList, states, products, new ArrayList<>()).isEmpty()); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findWithFilter(String, String, List, List, List, List)} - */ - @Test - void testFindWithFilter5() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - ArrayList roles = new ArrayList<>(); - - ArrayList relationshipStateList = new ArrayList<>(); - relationshipStateList.add(RelationshipState.PENDING); - ArrayList products = new ArrayList<>(); - assertTrue(userConnectorImpl.findWithFilter("42", "42", roles, relationshipStateList, products, new ArrayList<>()) - .isEmpty()); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findWithFilter(String, String, List, List, List, List)} - */ - @Test - void testFindWithFilter6() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - ArrayList roles = new ArrayList<>(); - ArrayList states = new ArrayList<>(); - - ArrayList stringList = new ArrayList<>(); - stringList.add("."); - assertTrue(userConnectorImpl.findWithFilter("42", "42", roles, states, stringList, new ArrayList<>()).isEmpty()); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findWithFilter(String, String, List, List, List, List)} - */ - @Test - void testFindWithFilter7() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - ArrayList roles = new ArrayList<>(); - ArrayList states = new ArrayList<>(); - ArrayList products = new ArrayList<>(); - - ArrayList stringList = new ArrayList<>(); - stringList.add("."); - assertTrue(userConnectorImpl.findWithFilter("42", "42", roles, states, products, stringList).isEmpty()); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findWithFilter(String, String, List, List, List, List)} - */ - @Test - void testFindWithFilter8() { - when(userRepository.find(any(), any())) - .thenThrow(new ResourceNotFoundException("An error occurred", ".")); - ArrayList roles = new ArrayList<>(); - ArrayList states = new ArrayList<>(); - ArrayList products = new ArrayList<>(); - List productRoles = new ArrayList<>(); - assertThrows(ResourceNotFoundException.class, - () -> userConnectorImpl.findWithFilter("42", "42", roles, states, products, productRoles)); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findByRelationshipId(String)} - */ - @Test - void testFindByRelationshipId() { - when(userRepository.find(any(), any())).thenReturn(new ArrayList<>()); - assertThrows(ResourceNotFoundException.class, () -> userConnectorImpl.findByRelationshipId("42")); - verify(userRepository).find(any(), any()); - } - - - /** - * Method under test: {@link UserConnectorImpl#findByRelationshipId(String)} - */ - @Test - void testFindByRelationshipId3() { - when(userRepository.find(any(), any())) - .thenThrow(new ResourceNotFoundException("An error occurred", "Code")); - assertThrows(ResourceNotFoundException.class, () -> userConnectorImpl.findByRelationshipId("42")); - verify(userRepository).find(any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findAndRemoveProduct(String, String, OnboardedProduct)} - */ - @Test - void testFindAndRemoveProduct() { - UserEntity userEntity = new UserEntity(); - userEntity.setBindings(new ArrayList<>()); - userEntity.setCreatedAt(null); - userEntity.setId("42"); - userEntity.setUpdatedAt(null); - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(userEntity); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - userConnectorImpl.findAndRemoveProduct("42", "42", onboardedProduct); - verify(userRepository).findAndModify(any(), any(), any(), any()); - } - - /** - * Method under test: {@link UserConnectorImpl#findAndRemoveProduct(String, String, OnboardedProduct)} - */ - @Test - void testFindAndRemoveProduct2() { - when(userRepository.findAndModify(any(), any(), any(), - any())) - .thenThrow(new ResourceNotFoundException("An error occurred", "$[currentUserBinding]")); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - assertThrows(ResourceNotFoundException.class, - () -> userConnectorImpl.findAndRemoveProduct("42", "42", onboardedProduct)); - verify(userRepository).findAndModify(any(), any(), any(), any()); - } - - @Test - void updateOnboardedProductCreatedAt() { - // Given - String institutionIdMock = "InstitutionIdMock"; - String productIdMock = "ProductIdMock"; - List usersIdMock = List.of("UserId2"); - OffsetDateTime createdAt = OffsetDateTime.parse("2020-11-01T02:15:30+01:00"); - - UserBindingEntity userBindingEntityMock1 = mockInstance(new UserBindingEntity()); - userBindingEntityMock1.setProducts(List.of(mockInstance(new OnboardedProductEntity()))); - OnboardedProductEntity onboardedProductEntity1 = mockInstance(new OnboardedProductEntity()); - OnboardedProductEntity onboardedProductEntity2 = mockInstance(new OnboardedProductEntity()); - onboardedProductEntity2.setProductId(productIdMock); - OnboardedProductEntity onboardedProductEntity3 = mockInstance(new OnboardedProductEntity(), 3); - UserBindingEntity userBindingEntityMock2 = mockInstance(new UserBindingEntity()); - userBindingEntityMock2.setInstitutionId(institutionIdMock); - userBindingEntityMock2.setProducts(List.of(onboardedProductEntity1, onboardedProductEntity2, onboardedProductEntity3)); - UserEntity updatedUserEntityMock = mockInstance(new UserEntity()); - OnboardingEntity onboardingEntityMock = mockInstance(new OnboardingEntity()); - onboardingEntityMock.setProductId(productIdMock); - - when(userRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(updatedUserEntityMock); - // When - List result = userConnectorImpl.updateUserBindingCreatedAt(institutionIdMock, productIdMock, usersIdMock, createdAt); - // Then - assertFalse(result.isEmpty()); - assertEquals(usersIdMock.size(), result.size()); - verify(userRepository, times(2)) - .findAndModify(queryArgumentCaptor.capture(), updateArgumentCaptor.capture(), findAndModifyOptionsArgumentCaptor.capture(), Mockito.eq(UserEntity.class)); - List capturedQuery = queryArgumentCaptor.getAllValues(); - assertEquals(2, capturedQuery.size()); - assertSame(capturedQuery.get(0).getQueryObject().get(UserEntity.Fields.id.name()), usersIdMock.get(0)); - assertSame(capturedQuery.get(1).getQueryObject().get(UserEntity.Fields.id.name()), usersIdMock.get(0)); - assertEquals(2, updateArgumentCaptor.getAllValues().size()); - Update updateUserBindingCreatedAt = updateArgumentCaptor.getAllValues().get(0); - Update updateUserEntityUpdatedAt = updateArgumentCaptor.getAllValues().get(1); - assertEquals(2, updateUserBindingCreatedAt.getArrayFilters().size()); - assertTrue(updateUserEntityUpdatedAt.getArrayFilters().isEmpty()); - assertTrue(updateUserEntityUpdatedAt.getUpdateObject().get("$set").toString().contains(InstitutionEntity.Fields.updatedAt.name())); - assertTrue(updateUserBindingCreatedAt.getUpdateObject().get("$set").toString().contains("bindings.$[currentUserBinding].products.$[current].createdAt") && - updateUserBindingCreatedAt.getUpdateObject().get("$set").toString().contains("bindings.$[currentUserBinding].products.$[current].updatedAt") && - updateUserBindingCreatedAt.getUpdateObject().get("$set").toString().contains(createdAt.toString())); - verifyNoMoreInteractions(userRepository); - } - - @Test - void findUserInstitutionAggregation() { - UserInstitutionAggregationEntity entity = new UserInstitutionAggregationEntity(); - entity.setInstitutions(List.of(mock(InstitutionEntity.class))); - entity.setBindings(mock(UserInstitutionBindingEntity.class)); - entity.setId("UserId"); - UserInstitutionFilter filter = new UserInstitutionFilter(); - filter.setUserId("UserId"); - when(userRepository.findUserInstitutionAggregation(any(), any())) - .thenReturn(List.of(mockInstance(new UserInstitutionAggregationEntity()))); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findUserInstitutionAggregation(filter)); - } - - @Test - void findByInstitutionId() { - UserEntity userEntity = new UserEntity(); - userEntity.setId("id"); - when(userRepository.find(any(), any())) - .thenReturn(List.of(userEntity)); - Assertions.assertDoesNotThrow(() -> userConnectorImpl.findByInstitutionId("institutionId")); - } - - @Test - void getUserInfo() { - //Given - AggregationResults results = mock(AggregationResults.class); - when(results.getMappedResults()).thenReturn(List.of(dummyUserInstitution)); - - //When - when(mongoTemplate.aggregate(any(Aggregation.class), anyString(), any())). - thenReturn(results); - - List response = userConnectorImpl.getUserInfo("userId", null, null); - - //Then - assertNotNull(response); - assertFalse(response.isEmpty()); - UserInstitutionAggregation actual = response.get(0); - - assertEquals(actual.getId(), dummyUserInstitution.getId()); - assertEquals(actual.getInstitutions().get(0).getId(), dummyUserInstitution.getInstitutions().get(0).getId()); - assertEquals(actual.getBindings().getProducts().getProductId(), dummyUserInstitution.getBindings().getProducts().getProductId()); - } - - @Test - void getUserInfoWithFilters() { - //Given - AggregationResults results = mock(AggregationResults.class); - when(results.getMappedResults()).thenReturn(List.of(dummyUserInstitution)); - - //When - when(mongoTemplate.aggregate(any(Aggregation.class), anyString(), any())). - thenReturn(results); - - List response = userConnectorImpl.getUserInfo("userId", "id", new String[]{"PENDING"}); - - //Then - assertNotNull(response); - assertFalse(response.isEmpty()); - UserInstitutionAggregation actual = response.get(0); - - assertEquals(actual.getId(), dummyUserInstitution.getId()); - assertEquals(actual.getInstitutions().get(0).getId(), dummyUserInstitution.getInstitutions().get(0).getId()); - assertEquals(actual.getBindings().getProducts().getProductId(), dummyUserInstitution.getBindings().getProducts().getProductId()); - } - - @Test - void findUsersByInstitutionIdAndProductId(){ - UserEntity userEntity = new UserEntity(); - userEntity.setId("id"); - when(userRepository.find(any(), any())).thenReturn(List.of(userEntity)); - List userIds = userConnectorImpl.findUsersByInstitutionIdAndProductId("institutionId", "productId"); - assertEquals(1, userIds.size()); - } - -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalService.java index f1467b25f..9fe312e2c 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalService.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalService.java @@ -4,7 +4,6 @@ import it.pagopa.selfcare.mscore.model.institution.GeographicTaxonomies; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.user.ProductManagerInfo; import java.util.List; @@ -12,8 +11,6 @@ public interface ExternalService { Institution getInstitutionByExternalId(String externalId); - ProductManagerInfo retrieveInstitutionManager(String externalId, String productId); - Institution retrieveInstitutionProduct(String externalId, String productId); List retrieveInstitutionGeoTaxonomiesByExternalId(String externalId); diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalServiceImpl.java index 38eb15c91..f9a475b69 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/ExternalServiceImpl.java @@ -1,30 +1,22 @@ package it.pagopa.selfcare.mscore.core; import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.exception.InvalidRequestException; import it.pagopa.selfcare.mscore.model.institution.GeographicTaxonomies; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.ProductManagerInfo; -import it.pagopa.selfcare.mscore.model.user.UserBinding; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; -import static it.pagopa.selfcare.mscore.constant.GenericError.INSTITUTION_MANAGER_ERROR; - @Service @Slf4j public class ExternalServiceImpl implements ExternalService { private final InstitutionService institutionService; - private final UserService userService; - public ExternalServiceImpl(InstitutionService institutionService, UserService userService) { + public ExternalServiceImpl(InstitutionService institutionService) { this.institutionService = institutionService; - this.userService = userService; } @Override @@ -32,20 +24,6 @@ public Institution getInstitutionByExternalId(String externalId) { return institutionService.retrieveInstitutionByExternalId(externalId); } - @Override - public ProductManagerInfo retrieveInstitutionManager(String externalId, String productId) { - Institution institution = institutionService.retrieveInstitutionByExternalId(externalId); - if(institution.getOnboarding()!=null) { - OnboardedUser onboardedUser = userService.findOnboardedManager(institution.getId(), productId, List.of(RelationshipState.ACTIVE)); - for (UserBinding userBinding : onboardedUser.getBindings()) { - if (institution.getId().equalsIgnoreCase(userBinding.getInstitutionId())) { - return new ProductManagerInfo(onboardedUser.getId(), institution, userBinding.getProducts()); - } - } - } - throw new InvalidRequestException(INSTITUTION_MANAGER_ERROR.getMessage(),INSTITUTION_MANAGER_ERROR.getCode()); - } - @Override public Institution retrieveInstitutionProduct(String externalId, String productId) { return institutionService.retrieveInstitutionProduct(externalId, productId); diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionService.java index 5b6204713..97d973ea5 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionService.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionService.java @@ -6,7 +6,6 @@ import it.pagopa.selfcare.mscore.constant.SearchMode; import it.pagopa.selfcare.mscore.core.util.InstitutionPaSubunitType; import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.user.UserInfo; import java.time.OffsetDateTime; import java.util.List; @@ -70,6 +69,4 @@ public interface InstitutionService { List getInstitutionBrokers(String productId, InstitutionType type); - List getInstitutionUsers(String institutionId); - } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java index 3b983e695..0d3a9b08b 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java @@ -1,12 +1,9 @@ package it.pagopa.selfcare.mscore.core; -import it.pagopa.selfcare.commons.base.logging.LogUtils; import it.pagopa.selfcare.commons.base.security.SelfCareUser; import it.pagopa.selfcare.commons.base.utils.InstitutionType; import it.pagopa.selfcare.mscore.api.InstitutionConnector; import it.pagopa.selfcare.mscore.api.PartyRegistryProxyConnector; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.api.UserRegistryConnector; import it.pagopa.selfcare.mscore.config.CoreConfig; import it.pagopa.selfcare.mscore.constant.*; import it.pagopa.selfcare.mscore.core.mapper.InstitutionMapper; @@ -22,7 +19,6 @@ import it.pagopa.selfcare.mscore.model.QueueEvent; import it.pagopa.selfcare.mscore.model.institution.*; import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.UserInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.Assert; @@ -44,32 +40,26 @@ public class InstitutionServiceImpl implements InstitutionService { private static final String REQUIRED_INSTITUTION_MESSAGE = "An institution id is required"; private final InstitutionConnector institutionConnector; - private final UserConnector userConnector; - private final UserRegistryConnector userRegistryConnector; private final PartyRegistryProxyConnector partyRegistryProxyConnector; private final CoreConfig coreConfig; private final ContractEventNotificationService contractService; private final InstitutionMapper institutionMapper; - private final TokenMapper tokenMapper; private final CreateInstitutionStrategyFactory createInstitutionStrategyFactory; + private final TokenMapper tokenMapper; public InstitutionServiceImpl(PartyRegistryProxyConnector partyRegistryProxyConnector, InstitutionConnector institutionConnector, CoreConfig coreConfig, - UserConnector userConnector, ContractEventNotificationService contractService, InstitutionMapper institutionMapper, CreateInstitutionStrategyFactory createInstitutionStrategyFactory, - UserRegistryConnector userRegistryConnector, TokenMapper tokenMapper) { this.partyRegistryProxyConnector = partyRegistryProxyConnector; this.institutionConnector = institutionConnector; this.coreConfig = coreConfig; - this.userConnector = userConnector; this.contractService = contractService; this.institutionMapper = institutionMapper; this.createInstitutionStrategyFactory = createInstitutionStrategyFactory; - this.userRegistryConnector = userRegistryConnector; this.tokenMapper = tokenMapper; } @@ -405,16 +395,4 @@ public void checkIfAlreadyExists(String externalId) { public List getInstitutionBrokers(String productId, InstitutionType type) { return institutionConnector.findBrokers(productId, type); } - - @Override - public List getInstitutionUsers(String institutionId) { - log.trace("getInstitutionUsers start"); - log.debug("getInstitutionUsers institutionId = {}", institutionId); - Assert.hasText(institutionId, REQUIRED_INSTITUTION_MESSAGE); - List userInfos = userConnector.findByInstitutionId(institutionId); - userInfos.forEach(userInfo -> userInfo.setUser(userRegistryConnector.getUserByInternalIdWithFiscalCode(userInfo.getId()))); - log.debug(LogUtils.CONFIDENTIAL_MARKER, "getInstitutionUsers result = {}", userInfos); - log.trace("getInstitutionUsers end"); - return userInfos; - } } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java index 982f58205..da9177a59 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java @@ -1,64 +1,27 @@ package it.pagopa.selfcare.mscore.core; import it.pagopa.selfcare.mscore.api.InstitutionConnector; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.exception.InvalidRequestException; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.UserBinding; import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; -import static it.pagopa.selfcare.mscore.constant.CustomError.INVALID_STATUS_CHANGE; - @Service @Slf4j public class OnboardingDao { private final InstitutionConnector institutionConnector; - private final UserConnector userConnector; - public OnboardingDao(InstitutionConnector institutionConnector, - UserConnector userConnector) { + public OnboardingDao(InstitutionConnector institutionConnector) { this.institutionConnector = institutionConnector; - this.userConnector = userConnector; } - public void updateUserProductState(OnboardedUser user, String relationshipId, RelationshipState toState) { - for (UserBinding binding : user.getBindings()) { - binding.getProducts().stream() - .filter(onboardedProduct -> relationshipId.equalsIgnoreCase(onboardedProduct.getRelationshipId())) - .forEach(product -> checkStatus(product.getStatus(), user.getId(), product.getRelationshipId(), toState)); - } - } - private void checkStatus(RelationshipState fromState, String userId, String relationshipId, RelationshipState toState) { - if (isValidStateChangeForRelationship(fromState, toState)) { - userConnector.findAndUpdateState(userId, relationshipId, null, toState); - } else { - throw new InvalidRequestException((String.format(INVALID_STATUS_CHANGE.getMessage(), fromState, toState)), INVALID_STATUS_CHANGE.getCode()); - } - } public void rollbackPersistOnboarding(String institutionId, Onboarding onboarding, List users) { institutionConnector.findAndRemoveOnboarding(institutionId, onboarding); log.debug("rollback persistOnboarding"); } - - private boolean isValidStateChangeForRelationship(RelationshipState fromState, RelationshipState toState) { - switch (toState) { - case ACTIVE: - return fromState == RelationshipState.SUSPENDED; - case SUSPENDED: - return fromState == RelationshipState.ACTIVE; - case DELETED: - return fromState != RelationshipState.DELETED; - default: - return false; - } - } } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java index 5b6f4e133..71efe1f3c 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java @@ -2,8 +2,6 @@ import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardingInfo; -import it.pagopa.selfcare.mscore.model.onboarding.ResourceResponse; import it.pagopa.selfcare.mscore.model.onboarding.VerifyOnboardingFilters; import it.pagopa.selfcare.mscore.model.user.UserToOnboard; @@ -17,11 +15,6 @@ public interface OnboardingService { void verifyOnboardingInfoByFilters(VerifyOnboardingFilters filters); - List getOnboardingInfo(String institutionId, String institutionExternalId, String[] states, String userId); - Institution persistOnboarding(String institutionId, String productId, List users, Onboarding onboarding); - ResourceResponse retrieveDocument(String relationshipId); - - } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java index 32995db5d..fadc21f36 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java @@ -4,28 +4,24 @@ import it.pagopa.selfcare.mscore.constant.CustomError; import it.pagopa.selfcare.mscore.constant.RelationshipState; import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; -import it.pagopa.selfcare.mscore.core.util.OnboardingInfoUtils; import it.pagopa.selfcare.mscore.core.util.UtilEnumList; import it.pagopa.selfcare.mscore.exception.InvalidRequestException; import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionFilter; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.*; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; +import it.pagopa.selfcare.mscore.model.onboarding.Token; +import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; +import it.pagopa.selfcare.mscore.model.onboarding.VerifyOnboardingFilters; import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; import java.time.OffsetDateTime; -import java.util.*; -import java.util.stream.Collectors; +import java.util.List; +import java.util.Objects; +import java.util.Optional; -import static it.pagopa.selfcare.mscore.constant.CustomError.DOCUMENT_NOT_FOUND; -import static it.pagopa.selfcare.mscore.constant.CustomError.ONBOARDING_INFO_INSTITUTION_NOT_FOUND; import static it.pagopa.selfcare.mscore.constant.GenericError.ONBOARDING_OPERATION_ERROR; @Slf4j @@ -33,26 +29,17 @@ public class OnboardingServiceImpl implements OnboardingService { private final OnboardingDao onboardingDao; private final InstitutionService institutionService; - private final UserService userService; - private final UserRelationshipService userRelationshipService; - private final ContractService contractService; private final ContractEventNotificationService contractEventNotification; private final InstitutionConnector institutionConnector; private final TokenMapper tokenMapper; public OnboardingServiceImpl(OnboardingDao onboardingDao, InstitutionService institutionService, - UserService userService, - UserRelationshipService userRelationshipService, - ContractService contractService, ContractEventNotificationService contractEventNotification, InstitutionConnector institutionConnector, TokenMapper tokenMapper) { this.onboardingDao = onboardingDao; this.institutionService = institutionService; - this.userService = userService; - this.userRelationshipService = userRelationshipService; - this.contractService = contractService; this.contractEventNotification = contractEventNotification; this.institutionConnector = institutionConnector; this.tokenMapper = tokenMapper; @@ -84,25 +71,6 @@ public void verifyOnboardingInfoByFilters(VerifyOnboardingFilters filters) { } } - @Override - public List getOnboardingInfo(String institutionId, String institutionExternalId, String[] - states, String userId) { - - List relationshipStateList = OnboardingInfoUtils.getRelationShipStateList(states); - List onboardingInfoList = new ArrayList<>(); - try { - List userInstitutionAggregation = getUserInstitutionAggregation(userId, institutionId, institutionExternalId, relationshipStateList); - userInstitutionAggregation.forEach(userBinding -> onboardingInfoList.add(new OnboardingInfo(userId, userBinding.getInstitutions().get(0), userBinding.getBindings()))); - - if (onboardingInfoList.isEmpty()) { - throw new InvalidRequestException(CustomError.ONBOARDING_INFO_ERROR.getMessage(), CustomError.ONBOARDING_INFO_ERROR.getCode()); - } - return onboardingInfoList; - } catch (ResourceNotFoundException e) { - return Collections.emptyList(); - } - } - @Override public Institution persistOnboarding(String institutionId, String productId, List users, Onboarding onboarding) { @@ -156,26 +124,4 @@ private TokenUser toTokenUser(UserToOnboard user) { return tokenUser; } - @Override - public ResourceResponse retrieveDocument(String relationshipId) { - RelationshipInfo relationship = userRelationshipService.retrieveRelationship(relationshipId); - if (relationship.getOnboardedProduct() != null && - StringUtils.hasText(relationship.getOnboardedProduct().getContract())) { - return contractService.getFile(relationship.getOnboardedProduct().getContract()); - } else { - throw new ResourceNotFoundException(String.format(DOCUMENT_NOT_FOUND.getMessage(), relationshipId), DOCUMENT_NOT_FOUND.getCode()); - } - } - - private List getUserInstitutionAggregation(String userId, String - institutionId, String externalId, List relationshipStates) { - List states = relationshipStates.stream().map(Enum::name).collect(Collectors.toList()); - UserInstitutionFilter filter = new UserInstitutionFilter(userId, institutionId, externalId, states); - List userInstitutionAggregation = userService.findUserInstitutionAggregation(filter); - if (userInstitutionAggregation == null || userInstitutionAggregation.isEmpty()) { - throw new ResourceNotFoundException(String.format(ONBOARDING_INFO_INSTITUTION_NOT_FOUND.getMessage(), userId), ONBOARDING_INFO_INSTITUTION_NOT_FOUND.getCode()); - } - return userInstitutionAggregation; - } - } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceImpl.java index e0c34fbcf..5f5ee599d 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceImpl.java @@ -2,12 +2,12 @@ import it.pagopa.selfcare.mscore.api.InstitutionConnector; import it.pagopa.selfcare.mscore.constant.RelationshipState; +import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; import it.pagopa.selfcare.mscore.model.QueueEvent; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; import it.pagopa.selfcare.mscore.model.onboarding.Token; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @@ -26,13 +26,13 @@ public class QueueNotificationServiceImpl implements QueueNotificationService { private Optional page = Optional.empty(); private final InstitutionConnector institutionConnector; private Optional> productsFilter = Optional.empty(); - + private final TokenMapper tokenMapper; private final List statesToSend = List.of(RelationshipState.ACTIVE, RelationshipState.DELETED); - @Autowired public QueueNotificationServiceImpl(ContractEventNotificationService contractService, - InstitutionConnector institutionConnector) { + InstitutionConnector institutionConnector, TokenMapper tokenMapper) { + this.tokenMapper = tokenMapper; log.info("Initializing {}...", QueueNotificationServiceImpl.class.getSimpleName()); this.contractService = contractService; this.institutionConnector = institutionConnector; @@ -58,15 +58,8 @@ public void sendContractsNotificationsByInstitutionIdAndTokenId(String tokenId, for(Onboarding onboarding : onboardings) { - Token token = new Token(); - token.setId(onboarding.getTokenId()); - token.setInstitutionId(institutionId); - token.setProductId(onboarding.getProductId()); + Token token = tokenMapper.toToken(onboarding, institutionId, onboarding.getProductId()); //token.setUsers(users.stream().map(this::toTokenUser).toList()); - token.setCreatedAt(onboarding.getCreatedAt()); - token.setUpdatedAt(onboarding.getUpdatedAt()); - token.setStatus(onboarding.getStatus()); - token.setContractSigned(onboarding.getContract()); institution.setOnboarding(List.of(onboarding)); contractService.sendDataLakeNotification(institution, token, QueueEvent.UPDATE); } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventService.java index 1270a41f3..9afd3dc1b 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventService.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventService.java @@ -1,15 +1,9 @@ package it.pagopa.selfcare.mscore.core; -import it.pagopa.selfcare.mscore.model.QueueEvent; import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; public interface UserEventService { - void sendLegalTokenUserNotification(Token token); - void sendOperatorUserNotification(RelationshipInfo relationshipInfo, QueueEvent eventType); - void sendUserNotificationToQueue(String userId, String institutionId, QueueEvent eventType); void sendOnboardedUserNotification(OnboardedUser onboardedUser, String productId); } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceIgnore.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceIgnore.java index d8e736783..c93b29f66 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceIgnore.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceIgnore.java @@ -1,9 +1,6 @@ package it.pagopa.selfcare.mscore.core; -import it.pagopa.selfcare.mscore.model.QueueEvent; import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; @@ -15,20 +12,6 @@ havingValue = "ignore", matchIfMissing = true) public class UserEventServiceIgnore implements UserEventService{ - @Override - public void sendLegalTokenUserNotification(Token token) { - - } - - @Override - public void sendOperatorUserNotification(RelationshipInfo relationshipInfo, QueueEvent eventType) { - - } - - @Override - public void sendUserNotificationToQueue(String userId, String institutionId, QueueEvent eventType) { - - } @Override public void sendOnboardedUserNotification(OnboardedUser onboardedUser, String productId) { diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceImpl.java index f4a58bd63..59b2042fb 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceImpl.java @@ -6,8 +6,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; -import it.pagopa.selfcare.commons.base.logging.LogUtils; -import it.pagopa.selfcare.mscore.api.UserConnector; import it.pagopa.selfcare.mscore.api.UserRegistryConnector; import it.pagopa.selfcare.mscore.config.CoreConfig; import it.pagopa.selfcare.mscore.constant.RelationshipState; @@ -20,8 +18,6 @@ import it.pagopa.selfcare.mscore.model.UserToNotify; import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; import it.pagopa.selfcare.mscore.model.user.User; import it.pagopa.selfcare.mscore.model.user.UserBinding; import lombok.extern.slf4j.Slf4j; @@ -36,9 +32,6 @@ import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.EnumSet; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; @Slf4j @Service @@ -53,7 +46,6 @@ public class UserEventServiceImpl implements UserEventService { private final EnumSet ALLOWED_RELATIONSHIP_STATUSES = EnumSet.of(RelationshipState.ACTIVE, RelationshipState.SUSPENDED, RelationshipState.DELETED); private final KafkaPropertiesConfig kafkaPropertiesConfig; private final ObjectMapper mapper; - private final UserConnector userConnector; private final UserRegistryConnector userRegistryConnector; private final NotificationMapper notificationMapper; @@ -64,7 +56,6 @@ public UserEventServiceImpl(CoreConfig coreConfig, KafkaTemplate kafkaTemplateUsers, KafkaPropertiesConfig kafkaPropertiesConfig, ObjectMapper mapper, - UserConnector userConnector, UserRegistryConnector userRegistryConnector, NotificationMapper notificationMapper, UserNotificationMapper userNotificationMapper) { @@ -72,7 +63,6 @@ public UserEventServiceImpl(CoreConfig coreConfig, this.kafkaTemplateUsers = kafkaTemplateUsers; this.kafkaPropertiesConfig = kafkaPropertiesConfig; this.mapper = mapper; - this.userConnector = userConnector; this.userRegistryConnector = userRegistryConnector; this.notificationMapper = notificationMapper; this.userNotificationMapper = userNotificationMapper; @@ -87,10 +77,6 @@ public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator mapper.registerModule(simpleModule); } - public void sendLegalTokenUserNotification(Token token) { - token.getUsers().forEach(tokenUser -> sendUserNotificationToQueue(tokenUser.getUserId(), token.getInstitutionId(), QueueEvent.ADD)); - } - @Override public void sendOnboardedUserNotification(OnboardedUser onboardedUser, String productId) { try { @@ -107,40 +93,6 @@ public void sendOnboardedUserNotification(OnboardedUser onboardedUser, String pr } - protected List toUserToNotify(String userId, String institutionId, String productId, Optional relationshipId, Optional tokenId) { - User user = userRegistryConnector.getUserByInternalId(userId); - OnboardedUser onboardedUser = userConnector.findById(userId); - return onboardedUser.getBindings().stream() - .filter(userBinding -> institutionId.equals(userBinding.getInstitutionId())) - .flatMap(userBinding -> userBinding.getProducts().stream()) - .filter(onboardedProduct -> productId.equals(onboardedProduct.getProductId())) - .filter(onboardedProduct -> relationshipId.map(s -> s.equals(onboardedProduct.getRelationshipId())).orElse(true)) - .filter(onboardedProduct -> tokenId.map(s -> s.equals(onboardedProduct.getTokenId())).orElse(true)) - .map(onboardedProduct -> toUserToNotify(userId, institutionId, user, onboardedProduct)) - .collect(Collectors.toList()); - } - - protected Optional toUserBinding(String userId, String institutionId) { - OnboardedUser onboardedUser = userConnector.findById(userId); - return onboardedUser.getBindings().stream() - .filter(userBinding -> institutionId.equals(userBinding.getInstitutionId())) - .findFirst(); - } - - @Override - public void sendUserNotificationToQueue(String userId, String institutionId, QueueEvent eventType) { - log.trace("sendUpdateUserNotification start"); - log.debug("sendUpdateUserNotification userId = {}, institutionId = {}", userId, institutionId); - OnboardedUser onboardedUser = userConnector.findById(userId); - onboardedUser.getBindings().stream() - .filter(userBinding -> userBinding.getInstitutionId().equals(institutionId)) - .forEach(userBinding -> userBinding.getProducts().stream() - .filter(onboardedProduct -> ALLOWED_RELATIONSHIP_STATUSES.contains(onboardedProduct.getStatus())) - .forEach(onboardedProduct -> { - sendUserNotificationFromBindings(userId, eventType, userBinding, onboardedProduct); - })); - } - private void sendUserNotificationFromBindings(String userId, QueueEvent eventType, UserBinding userBinding, OnboardedProduct onboardedProduct) { User user = userRegistryConnector.getUserByInternalId(userId); UserToNotify userToNotify = userNotificationMapper.toUserNotify(user, onboardedProduct, userBinding.getInstitutionId()); @@ -156,34 +108,6 @@ private void sendUserNotificationFromBindings(String userId, QueueEvent eventTyp } } - public void sendOperatorUserNotification(RelationshipInfo relationshipInfo, QueueEvent eventType) { - if (relationshipInfo != null) { - Optional userBinding = toUserBinding(relationshipInfo.getUserId(), - relationshipInfo.getInstitution().getId()); - userBinding.ifPresent(currentUserBinding -> { - currentUserBinding.getProducts().stream() - .filter(onboardedProduct -> relationshipInfo.getOnboardedProduct().getProductId().equals(onboardedProduct.getProductId())) - .filter(onboardedProduct -> ALLOWED_RELATIONSHIP_STATUSES.contains(onboardedProduct.getStatus())) - .filter(onboardedProduct -> Optional.of(relationshipInfo.getOnboardedProduct().getRelationshipId()).map(s -> s.equals(onboardedProduct.getRelationshipId())).orElse(true)) - .forEach(currentOnboardedProduct -> sendUserNotificationFromBindings(relationshipInfo.getUserId(), eventType, currentUserBinding, currentOnboardedProduct)); - }); - } - } - - - - private UserToNotify toUserToNotify(String userId, String institutionId, User user, OnboardedProduct onboardedProduct) { - UserToNotify userToNotify = new UserToNotify(); - userToNotify.setUserId(userId); - userToNotify.setName(user.getName()); - userToNotify.setFamilyName(user.getFamilyName()); - userToNotify.setEmail(user.getWorkContacts().containsKey(institutionId) ? user.getWorkContacts().get(institutionId).getEmail() : user.getEmail()); - userToNotify.setRole(onboardedProduct.getRole()); - userToNotify.setRelationshipStatus(onboardedProduct.getStatus()); - userToNotify.setProductRole(onboardedProduct.getProductRole()); - return userToNotify; - } - private String idBuilder(String userId, String institutionId, String productId, String productRole){ return String.format("%s_%s_%s_%s", userId, institutionId, productId, productRole); } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationService.java index 00e423b3e..a556224ca 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationService.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationService.java @@ -1,8 +1,5 @@ package it.pagopa.selfcare.mscore.core; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.user.UserBinding; - import java.util.List; import java.util.Map; @@ -10,13 +7,4 @@ public interface UserNotificationService { void sendDelegationUserNotification(List to, String templateName, String productName, Map mailParameters); - void sendCreateUserNotification(String description, String productTitle, String email, List roleLabels, String loggedUserName, String loggedUserSurname); - - void sendActivatedUserNotification(String relationshipId, String userId, UserBinding binding, String loggedUserName, String loggedUserSurname); - - void sendDeletedUserNotification(String relationshipId, String userId, UserBinding binding, String loggedUserName, String loggedUserSurname); - - void sendSuspendedUserNotification(String relationshipId, String userId, UserBinding binding, String loggedUserName, String loggedUserSurname); - - void sendAddedProductRoleNotification(String userId, Institution institution, String productTitle, List roleLabels, String loggedUserName, String loggedUserSurname); } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImpl.java index 11ffa07ec..9c5116bbc 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImpl.java @@ -1,35 +1,18 @@ package it.pagopa.selfcare.mscore.core; import com.fasterxml.jackson.databind.ObjectMapper; -import freemarker.template.Configuration; -import freemarker.template.Template; import it.pagopa.selfcare.mscore.api.FileStorageConnector; import it.pagopa.selfcare.mscore.api.NotificationServiceConnector; -import it.pagopa.selfcare.mscore.api.ProductConnector; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.notification.MessageRequest; import it.pagopa.selfcare.mscore.model.notification.MultipleReceiverMessageRequest; import it.pagopa.selfcare.mscore.model.onboarding.MailTemplate; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.product.entity.Product; -import it.pagopa.selfcare.product.entity.ProductRole; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.text.StringSubstitutor; import org.springframework.mail.MailPreparationException; -import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; -import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; @Slf4j @Service @@ -54,40 +37,10 @@ public class UserNotificationServiceImpl implements UserNotificationService { private static final String SURNAME_IS_REQUIRED = "RequesterSurname is required"; - private final Configuration freemarkerConfig; private final NotificationServiceConnector notificationConnector; - private final ProductConnector productsConnector; - private final UserService userService; - private final InstitutionService institutionService; - private final FileStorageConnector fileStorageConnector; private final ObjectMapper mapper; - - @Override - @Async - public void sendAddedProductRoleNotification(String userId, Institution institution, String productTitle, List roleLabels, String loggedUserName, String loggedUserSurname) { - log.trace("sendAddedProductRoleNotification start"); - log.debug("sendAddedProductRoleNotification institutionId = {}, productTitle = {}, userId = {}, productRoles = {}", institution.getId(), productTitle, userId, roleLabels); - Assert.notNull(institution.getId(), INSTITUTION_ID_IS_REQUIRED); - Assert.notNull(productTitle, A_PRODUCT_TITLE_IS_REQUIRED); - Assert.notEmpty(roleLabels, PRODUCT_ROLES_ARE_REQUIRED); - Assert.notNull(loggedUserName, NAME_IS_REQUIRED); - Assert.notNull(loggedUserSurname, SURNAME_IS_REQUIRED); - - User user = userService.retrieveUserFromUserRegistry(userId); - Assert.notNull(user.getName(), NAME_IS_REQUIRED); - Assert.notNull(user.getFamilyName(), SURNAME_IS_REQUIRED); - Assert.notNull(user.getWorkContacts(), "WorkContacts is required to get email"); - Assert.notNull(user.getWorkContacts().get(institution.getId()), String.format("WorkContacts for institution %s is required to get email", institution.getId())); - - String email = user.getWorkContacts().get(institution.getId()).getEmail(); - Assert.isTrue(StringUtils.hasText(email), "Email is required"); - - sendCreateUserNotification(institution.getDescription(), productTitle, email, roleLabels, loggedUserName, loggedUserSurname); - log.trace("sendAddedProductRoleNotification start"); - } - @Override public void sendDelegationUserNotification(List to, String templateName, String productName, Map mailParameters) { try { @@ -105,114 +58,4 @@ public void sendDelegationUserNotification(List to, String templateName, } } - @Override - public void sendCreateUserNotification(String description, String productTitle, String email, List roleLabels, String loggedUserName, String loggedUserSurname) { - log.debug("sendCreateNotification start"); - log.debug("sendCreateNotification institution = {}, productTitle = {}, email = {}", description, productTitle, email); - - Map dataModel = new HashMap<>(); - dataModel.put("requesterName", loggedUserName); - dataModel.put("requesterSurname", loggedUserSurname); - - dataModel.put("productName", productTitle); - dataModel.put("institutionName", description); - if (roleLabels.size() > 1) { - String roleLabel = roleLabels.stream() - .limit(roleLabels.size() - 1L) - .collect(Collectors.joining(", ")); - - dataModel.put("productRoles", roleLabel); - dataModel.put("lastProductRole", roleLabels.get(roleLabels.size() - 1)); - sendNotification(email, CREATE_TEMPLATE_MULTIPLE_ROLE, CREATE_SUBJECT, dataModel); - } else { - String roleLabel = roleLabels.get(0); - dataModel.put("productRole", roleLabel); - sendNotification(email, CREATE_TEMPLATE_SINGLE_ROLE, CREATE_SUBJECT, dataModel); - } - log.debug("sendCreateNotification end"); - } - - @Override - @Async - public void sendActivatedUserNotification(String relationshipId, String userId, UserBinding binding, String loggedUserName, String loggedUserSurname) { - log.trace("sendActivatedUserNotification start"); - log.debug("sendActivatedUserNotification relationshipId = {}", relationshipId); - sendRelationshipBasedNotification(relationshipId, userId, binding, ACTIVATE_TEMPLATE, ACTIVATE_SUBJECT, loggedUserName, loggedUserSurname); - log.debug("sendActivatedUserNotification end"); - } - - - @Override - @Async - public void sendDeletedUserNotification(String relationshipId, String userId, UserBinding binding, String loggedUserName, String loggedUserSurname) { - log.trace("sendDeletedUserNotification start"); - log.debug("sendDeletedUserNotification relationshipId = {}", relationshipId); - sendRelationshipBasedNotification(relationshipId, userId, binding, DELETE_TEMPLATE, DELETE_SUBJECT, loggedUserName, loggedUserSurname); - log.debug("sendDeletedUserNotification end"); - } - - - @Override - @Async - public void sendSuspendedUserNotification(String relationshipId, String userId, UserBinding binding, String loggedUserName, String loggedUserSurname) { - log.trace("sendSuspendedUserNotification start"); - log.debug("sendSuspendedUserNotification relationshipId = {}", relationshipId); - sendRelationshipBasedNotification(relationshipId, userId, binding, SUSPEND_TEMPLATE, SUSPEND_SUBJECT, loggedUserName, loggedUserSurname); - log.debug("sendSuspendedUserNotification end"); - } - - - private void sendRelationshipBasedNotification(String relationshipId, String userId, UserBinding binding, String templateName, String subject, String loggedUserName, String loggedUserSurname){ - Assert.notNull(relationshipId, "A relationship Id is required"); - Assert.notNull(loggedUserName, NAME_IS_REQUIRED); - Assert.notNull(loggedUserSurname, SURNAME_IS_REQUIRED); - - User user = userService.retrieveUserFromUserRegistry(userId); - Assert.notNull(user.getWorkContacts(), "WorkContacts is required to get email"); - Assert.notNull(user.getWorkContacts().get(binding.getInstitutionId()), String.format("WorkContacts for institution %s is required to get email", binding.getInstitutionId())); - - String email = user.getWorkContacts().get(binding.getInstitutionId()).getEmail(); - Assert.isTrue(StringUtils.hasText(email), "Email is required"); - - Assert.notNull(user.getName(), NAME_IS_REQUIRED); - Assert.notNull(user.getFamilyName(), SURNAME_IS_REQUIRED); - - Institution institution = institutionService.retrieveInstitutionById(binding.getInstitutionId()); - Assert.notNull(institution.getDescription(), "An institution description is required"); - - OnboardedProduct onboardedProduct = binding.getProducts().stream().filter(product -> relationshipId.equalsIgnoreCase(product.getRelationshipId())) - .findFirst().orElseThrow(); - Assert.notNull(onboardedProduct.getProductId(), "A product Id is required"); - Assert.notNull(institution.getDescription(), "An institution description is required"); - Product product = productsConnector.getProductById(onboardedProduct.getProductId()); - Assert.notNull(product.getTitle(), A_PRODUCT_TITLE_IS_REQUIRED); - Optional roleLabel = product.getRoleMappings().values().stream() - .flatMap(productRoleInfo -> productRoleInfo.getRoles().stream()) - .filter(productRole -> productRole.getCode().equals(onboardedProduct.getProductRole())) - .map(ProductRole::getLabel) - .findAny(); - - Map dataModel = new HashMap<>(); - dataModel.put("productName", product.getTitle()); - dataModel.put("productRole", roleLabel.orElse("no_role_found")); - dataModel.put("institutionName", institution.getDescription()); - dataModel.put("requesterName", loggedUserName); - dataModel.put("requesterSurname", loggedUserSurname); - - sendNotification(email, templateName, subject, dataModel); - } - - private void sendNotification(String email, String templateName, String subject, Map dataModel) { - try { - Template template = freemarkerConfig.getTemplate(templateName); - String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, dataModel); - MessageRequest messageRequest = new MessageRequest(); - messageRequest.setContent(html); - messageRequest.setReceiverEmail(email); - messageRequest.setSubject(subject); - notificationConnector.sendNotificationToUser(messageRequest); - } catch (Exception e) { - throw new MailPreparationException(e); - } - } } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserRelationshipService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserRelationshipService.java deleted file mode 100644 index ecce86c18..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserRelationshipService.java +++ /dev/null @@ -1,18 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; - -public interface UserRelationshipService { - - OnboardedUser findByRelationshipId(String relationshipId); - - void activateRelationship(String relationshipId, String loggedUserName, String loggedUserSurname); - - void suspendRelationship(String relationshipId, String loggedUserName, String loggedUserSurname); - - void deleteRelationship(String relationshipId, String loggedUserName, String loggedUserSurname); - - RelationshipInfo retrieveRelationship(String relationshipId); - -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserRelationshipServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserRelationshipServiceImpl.java deleted file mode 100644 index 3b6b369ed..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserRelationshipServiceImpl.java +++ /dev/null @@ -1,109 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.exception.InvalidRequestException; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -import static it.pagopa.selfcare.mscore.constant.CustomError.*; - -@Slf4j -@Service -public class UserRelationshipServiceImpl implements UserRelationshipService { - - private final OnboardingDao onboardingDao; - private final UserConnector userConnector; - private final InstitutionService institutionService; - private final UserNotificationService userNotificationService; - - private final UserEventService userEventService; - - public UserRelationshipServiceImpl(OnboardingDao onboardingDao, UserConnector userConnector, InstitutionService institutionService, UserEventService userEventService, UserNotificationService userNotificationService) { - this.onboardingDao = onboardingDao; - this.userConnector = userConnector; - this.institutionService = institutionService; - this.userNotificationService = userNotificationService; - this.userEventService = userEventService; - } - - @Override - public OnboardedUser findByRelationshipId(String relationshipId) { - return userConnector.findByRelationshipId(relationshipId); - } - - @Override - public void activateRelationship(String relationshipId,String loggedUserName, String loggedUserSurname) { - OnboardedUser user = findByRelationshipId(relationshipId); - UserBinding userBinding = retrieveUserBinding(user, relationshipId); - try { - onboardingDao.updateUserProductState(user, relationshipId, RelationshipState.ACTIVE); - sendRelationshipEventNotification(user, relationshipId, QueueEvent.UPDATE); - userNotificationService.sendActivatedUserNotification(relationshipId, user.getId(), userBinding, loggedUserName, loggedUserSurname); - } catch (InvalidRequestException e) { - throw new InvalidRequestException(String.format(RELATIONSHIP_NOT_ACTIVABLE.getMessage(), relationshipId), RELATIONSHIP_NOT_ACTIVABLE.getCode()); - } - } - - @Override - public void suspendRelationship(String relationshipId, String loggedUserName, String loggedUserSurname) { - OnboardedUser user = findByRelationshipId(relationshipId); - UserBinding userBinding = retrieveUserBinding(user, relationshipId); - try { - onboardingDao.updateUserProductState(user, relationshipId, RelationshipState.SUSPENDED); - userNotificationService.sendSuspendedUserNotification(relationshipId, user.getId(), userBinding, loggedUserName, loggedUserSurname); - sendRelationshipEventNotification(user, relationshipId, QueueEvent.UPDATE); - } catch (InvalidRequestException e) { - throw new InvalidRequestException(String.format(RELATIONSHIP_NOT_SUSPENDABLE.getMessage(), relationshipId), RELATIONSHIP_NOT_SUSPENDABLE.getCode()); - } - } - - private void sendRelationshipEventNotification(OnboardedUser user, String relationshipId, QueueEvent eventType){ - RelationshipInfo relationshipInfo = getRelationshipInfoFromUser(user, relationshipId); - userEventService.sendOperatorUserNotification(relationshipInfo, eventType); - } - @Override - public void deleteRelationship(String relationshipId, String loggedUserName, String loggedUserSurname) { - OnboardedUser user = findByRelationshipId(relationshipId); - UserBinding userBinding = retrieveUserBinding(user, relationshipId); - onboardingDao.updateUserProductState(user, relationshipId, RelationshipState.DELETED); - sendRelationshipEventNotification(user, relationshipId, QueueEvent.UPDATE); - userNotificationService.sendDeletedUserNotification(relationshipId, user.getId(), userBinding, loggedUserName, loggedUserSurname); - } - - @Override - public RelationshipInfo retrieveRelationship(String relationshipId) { - OnboardedUser user = findByRelationshipId(relationshipId); - return getRelationshipInfoFromUser(user, relationshipId); - } - - private RelationshipInfo getRelationshipInfoFromUser(OnboardedUser user, String relationshipId){ - for (UserBinding userBinding : user.getBindings()) { - for (OnboardedProduct product : userBinding.getProducts()) { - if (relationshipId.equalsIgnoreCase(product.getRelationshipId())) { - Institution institution = institutionService.retrieveInstitutionById(userBinding.getInstitutionId()); - return new RelationshipInfo(institution, user.getId(), product); - } - } - } - throw new InvalidRequestException(String.format(RELATIONSHIP_ID_NOT_FOUND.getMessage(), relationshipId), RELATIONSHIP_ID_NOT_FOUND.getCode()); - } - - private UserBinding retrieveUserBinding(OnboardedUser user, String relationshipId) { - if (user.getBindings() != null) { - return user.getBindings().stream() - .filter(binding -> binding.getProducts().stream().anyMatch(product -> relationshipId.equalsIgnoreCase(product.getRelationshipId()))) - .findAny() - .orElseThrow(() -> new InvalidRequestException(String.format(RELATIONSHIP_ID_NOT_FOUND.getMessage(), relationshipId), RELATIONSHIP_ID_NOT_FOUND.getCode())); - }else{ - throw new InvalidRequestException(String.format(RELATIONSHIP_ID_NOT_FOUND.getMessage(), relationshipId), RELATIONSHIP_ID_NOT_FOUND.getCode()); - - } - } -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserService.java deleted file mode 100644 index cf122021d..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserService.java +++ /dev/null @@ -1,45 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionFilter; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardingInfo; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; - -import java.util.List; -import java.util.Optional; - -public interface UserService { - - OnboardedUser findOnboardedManager(String id, String productId, List active); - - List findAllByIds(List users); - - List findAll(Optional size, Optional page, String productId); - - List findAllExistingByIds(List users); - - List retrieveBindings(String institutionId, String userId, String[] states, List products); - - boolean checkIfInstitutionUser(String userId, String institutionId); - - User retrieveUserFromUserRegistry(String userId); - - User retrieveUserFromUserRegistryByFiscalCode(String fiscalCode); - - User persistUserRegistry(String name, String familyName, String fiscalCode, String email, String institutionId); - - User persistWorksContractToUserRegistry(String fiscalCode, String email, String institutionId); - - List findUserInstitutionAggregation(UserInstitutionFilter filter); - - User retrievePerson(String userId, String productId, String institutionId); - - List getUserInfo(String userId, String institutionId, String[] states); - - void updateUserStatus(String userId, String institutionId, String productId, PartyRole role, String productRole, RelationshipState status); -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserServiceImpl.java deleted file mode 100644 index c4fb574e6..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserServiceImpl.java +++ /dev/null @@ -1,176 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.api.UserRegistryConnector; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.util.NotificationMapper; -import it.pagopa.selfcare.mscore.core.util.OnboardingInfoUtils; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapper; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.UserToNotify; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionFilter; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardingInfo; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; - -import java.util.*; -import java.util.stream.Collectors; - -import static it.pagopa.selfcare.mscore.constant.CustomError.USER_NOT_FOUND_ERROR; - -@Service -@Slf4j -public class UserServiceImpl implements UserService { - private static final List VALID_USER_RELATIONSHIPS = List.of(RelationshipState.ACTIVE.name(), RelationshipState.DELETED.name(), RelationshipState.SUSPENDED.name()); - private final UserConnector userConnector; - private final UserRegistryConnector userRegistryConnector; - private final NotificationMapper notificationMapper; - private final UserNotificationMapper userNotificationMapper; - private static final int USER_PAGE_SIZE = 100; - - public UserServiceImpl(UserConnector userConnector, - UserRegistryConnector userRegistryConnector, - NotificationMapper notificationMapper, - UserNotificationMapper userNotificationMapper) { - this.userConnector = userConnector; - this.userRegistryConnector = userRegistryConnector; - this.notificationMapper = notificationMapper; - this.userNotificationMapper = userNotificationMapper; - } - - @Override - public OnboardedUser findOnboardedManager(String institutionId, String productId, List active) { - return userConnector.findOnboardedManager(institutionId, productId, List.of(RelationshipState.ACTIVE)); - } - - @Override - public List findAllByIds(List users) { - if (users == null || users.isEmpty()) { - return Collections.emptyList(); - } - return userConnector.findAllByIds(users); - } - - @Override - public List findAll(Optional size, Optional page, String productId) { - List users = new ArrayList<>(); - final int limit = size.orElse(USER_PAGE_SIZE); - final int offset = page.orElse(0); - List onboardedUsers = userConnector.findAllValidUsers(offset, limit, productId); - onboardedUsers.forEach(onboardedUser -> { - User user = userRegistryConnector.getUserByInternalId(onboardedUser.getId()); - onboardedUser.getBindings().forEach(userBinding -> { - for (OnboardedProduct onboardedProduct : userBinding.getProducts()) { - if(!StringUtils.hasText(productId) - || (StringUtils.hasText(productId) && productId.equals(onboardedProduct.getProductId()) - && VALID_USER_RELATIONSHIPS.contains(onboardedProduct.getStatus().name()))) { - UserToNotify userToNotify = userNotificationMapper.toUserNotify(user, onboardedProduct, userBinding.getInstitutionId()); - UserNotificationToSend userNotification = notificationMapper.setNotificationDetailsFromOnboardedProduct(userToNotify, onboardedProduct, userBinding.getInstitutionId()); - users.add(userNotification); - } - } - }); - }); - return users; - } - - @Override - public List findAllExistingByIds(List users) { - if (users == null || users.isEmpty()) { - return Collections.emptyList(); - } - return userConnector.findAllByExistingIds(users); - } - - @Override - public List retrieveBindings(String institutionId, String userId, String[] states, List products) { - - - List relationshipStates = Optional.ofNullable(states) - .map(OnboardingInfoUtils::convertStatesToRelationshipsState) - .orElse(null); - - List onboardingInfoList = userConnector.findWithFilter(institutionId, userId, null, relationshipStates, null, null); - if (Objects.isNull(onboardingInfoList) || onboardingInfoList.isEmpty()) return List.of(); - - OnboardedUser onboardedUser = onboardingInfoList.get(0); - return onboardedUser.getBindings().stream() - .peek(userBinding -> userBinding.setProducts(userBinding.getProducts().stream() - .filter(product -> Objects.isNull(relationshipStates) || relationshipStates.isEmpty() - || relationshipStates.contains(product.getStatus())) - .collect(Collectors.toList()))) - .filter(userBinding -> !userBinding.getProducts().isEmpty()) - .collect(Collectors.toList()); - } - - @Override - public boolean checkIfInstitutionUser(String userId, String institutionId) { - return !userConnector.findActiveInstitutionUser(userId, institutionId).isEmpty(); - } - - @Override - public User retrieveUserFromUserRegistry(String userId) { - return userRegistryConnector.getUserByInternalIdWithFiscalCode(userId); - } - - @Override - public User retrieveUserFromUserRegistryByFiscalCode(String fiscalCode) { - return userRegistryConnector.getUserByFiscalCode(fiscalCode); - } - - @Override - public User persistUserRegistry(String name, String familyName, String fiscalCode, String email, String institutionId) { - return userRegistryConnector.persistUserUsingPatch(name ,familyName ,fiscalCode ,email , institutionId); - } - - @Override - public User persistWorksContractToUserRegistry(String fiscalCode, String email, String institutionId) { - return userRegistryConnector.persistUserWorksContractUsingPatch(fiscalCode ,email , institutionId); - } - - @Override - public List findUserInstitutionAggregation(UserInstitutionFilter filter) { - return userConnector.findUserInstitutionAggregation(filter); - } - - @Override - public void updateUserStatus(String userId, String institutionId, String productId, PartyRole role, String productRole, RelationshipState status) { - userConnector.findAndUpdateStateWithOptionalFilter(userId, institutionId, productId, role, productRole, status); - } - - @Override - public User retrievePerson(String userId, String productId, String institutionId) { - OnboardedUser onboardedUser = userConnector.findById(userId); - if (StringUtils.hasText(productId) && !verifyBindings(onboardedUser, productId)) { - log.error(String.format(USER_NOT_FOUND_ERROR.getMessage(), userId)); - throw new ResourceNotFoundException(String.format(USER_NOT_FOUND_ERROR.getMessage(), userId), USER_NOT_FOUND_ERROR.getCode()); - } - return userRegistryConnector.getUserByInternalIdWithFiscalCode(userId); - } - - @Override - public List getUserInfo(String userId, String institutionId, String[] states) { - List onboardingInfos = new ArrayList<>(); - List userInfos = userConnector.getUserInfo(userId, institutionId, states); - userInfos.forEach(userBinding -> onboardingInfos.add(new OnboardingInfo(userId, userBinding.getInstitutions().get(0), userBinding.getBindings()))); - return onboardingInfos; - } - - private boolean verifyBindings(OnboardedUser onboardedUser, String productId) { - return onboardedUser.getBindings().stream() - .anyMatch(binding -> existsProduct(binding, productId)); - } - - private boolean existsProduct(UserBinding binding, String productId) { - return binding.getProducts().stream() - .anyMatch(product -> productId.equalsIgnoreCase(product.getProductId())); - } -} diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/ExternalServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/ExternalServiceImplTest.java index 8d87eceb3..f278c558b 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/ExternalServiceImplTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/ExternalServiceImplTest.java @@ -5,9 +5,6 @@ import it.pagopa.selfcare.mscore.model.institution.GeographicTaxonomies; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -17,7 +14,6 @@ import java.util.ArrayList; import java.util.List; -import static it.pagopa.selfcare.mscore.core.util.TestUtils.dummyInstitutionPa; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -30,8 +26,6 @@ class ExternalServiceImplTest { @Mock private InstitutionService institutionService; - @Mock - private UserService userService; /** * Method under test: {@link ExternalServiceImpl#getInstitutionByExternalId(String)} @@ -66,80 +60,6 @@ void testGetInstitutionByExternalId3() { verify(institutionService).retrieveInstitutionByExternalId(any()); } - /** - * Method under test: {@link ExternalServiceImpl#retrieveInstitutionManager(String, String)} - */ - @Test - void testRetrieveInstitutionManager() { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - when(userService.findOnboardedManager(any(), any(), any())) - .thenReturn(onboardedUser); - Institution institution = new Institution(); - institution.setOnboarding(new ArrayList<>()); - when(institutionService.retrieveInstitutionByExternalId(any())).thenReturn(institution); - Assertions.assertThrows(InvalidRequestException.class, () -> externalServiceImpl.retrieveInstitutionManager("42", "42")); - } - - @Test - void testRetrieveInstitutionManager2() { - OnboardedUser onboardedUser = new OnboardedUser(); - List userBindings = new ArrayList<>(); - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("id"); - userBinding.setProducts(new ArrayList<>()); - userBindings.add(userBinding); - onboardedUser.setBindings(userBindings); - onboardedUser.setId("id"); - when(userService.findOnboardedManager(any(), any(), any())) - .thenReturn(onboardedUser); - Institution institution = new Institution(); - institution.setId("id"); - institution.setOnboarding(new ArrayList<>()); - when(institutionService.retrieveInstitutionByExternalId(any())).thenReturn(institution); - assertNotNull(externalServiceImpl.retrieveInstitutionManager("42", "42")); - } - - /** - * Method under test: {@link ExternalServiceImpl#retrieveInstitutionManager(String, String)} - */ - @Test - void testRetrieveInstitutionManager3() { - when(institutionService.retrieveInstitutionByExternalId(any())).thenReturn(new Institution()); - assertThrows(InvalidRequestException.class, () -> externalServiceImpl.retrieveInstitutionManager("42", "42")); - verify(institutionService).retrieveInstitutionByExternalId(any()); - } - - /** - * Method under test: {@link ExternalServiceImpl#retrieveInstitutionManager(String, String)} - */ - @Test - void testRetrieveInstitutionManager6() { - - when(institutionService.retrieveInstitutionByExternalId(any())).thenReturn(dummyInstitutionPa()); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - when(userService.findOnboardedManager(any(), any(), any())) - .thenReturn(onboardedUser); - assertThrows(InvalidRequestException.class, () -> externalServiceImpl.retrieveInstitutionManager("42", "42")); - verify(institutionService).retrieveInstitutionByExternalId(any()); - verify(userService).findOnboardedManager(any(), any(), any()); - } - - /** - * Method under test: {@link ExternalServiceImpl#retrieveInstitutionManager(String, String)} - */ - @Test - void testRetrieveInstitutionManager8() { - - when(institutionService.retrieveInstitutionByExternalId(any())).thenReturn(dummyInstitutionPa()); - when(userService.findOnboardedManager(any(), any(), any())) - .thenThrow(new InvalidRequestException("An error occurred", "Code")); - assertThrows(InvalidRequestException.class, () -> externalServiceImpl.retrieveInstitutionManager("42", "42")); - verify(institutionService).retrieveInstitutionByExternalId(any()); - verify(userService).findOnboardedManager(any(), any(), any()); - } /** * Method under test: {@link ExternalServiceImpl#retrieveInstitutionProduct(String, String)} diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java index 50039369d..07817f3f9 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java @@ -5,8 +5,6 @@ import it.pagopa.selfcare.commons.base.utils.InstitutionType; import it.pagopa.selfcare.mscore.api.InstitutionConnector; import it.pagopa.selfcare.mscore.api.PartyRegistryProxyConnector; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.api.UserRegistryConnector; import it.pagopa.selfcare.mscore.config.CoreConfig; import it.pagopa.selfcare.mscore.constant.RelationshipState; import it.pagopa.selfcare.mscore.constant.SearchMode; @@ -25,8 +23,6 @@ import it.pagopa.selfcare.mscore.model.institution.*; import it.pagopa.selfcare.mscore.model.onboarding.Token; import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserInfo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -64,12 +60,6 @@ class InstitutionServiceImplTest { @Mock private ContractEventNotificationService contractService; - @Mock - private UserConnector userConnector; - - @Mock - private UserRegistryConnector userRegistryConnector; - @Mock private CreateInstitutionStrategyFactory createInstitutionStrategyFactory; @@ -492,7 +482,6 @@ void testCreatePgInstitution14() { @Test void testRetrieveInstitutionProducts() { PartyRegistryProxyConnector partyRegistryProxyConnector = mock(PartyRegistryProxyConnector.class); - UserServiceImpl userService = new UserServiceImpl(null, null, null, null); Institution institution = new Institution(); Onboarding onboarding = new Onboarding(); onboarding.setStatus(RelationshipState.PENDING); @@ -913,7 +902,7 @@ void updateCreatedAt() { .updateOnboardedProductCreatedAt(institutionIdMock, productIdMock, createdAtMock); verify(contractService, times(1)) .sendDataLakeNotification(updatedInstitutionMock, updatedTokenMock, QueueEvent.UPDATE); - verifyNoMoreInteractions(institutionConnector, userConnector, contractService); + verifyNoMoreInteractions(institutionConnector, contractService); } @Test @@ -926,7 +915,7 @@ void updateCreatedAt_nullInstitutionId() { // Then IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class, executable); assertEquals("An institution ID is required.", illegalArgumentException.getMessage()); - verifyNoInteractions(institutionConnector, userConnector); + verifyNoInteractions(institutionConnector); } @Test @@ -939,7 +928,7 @@ void updateCreatedAt_nullProductId() { // Then IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class, executable); assertEquals("A product ID is required.", illegalArgumentException.getMessage()); - verifyNoInteractions(institutionConnector, userConnector); + verifyNoInteractions(institutionConnector); } @Test @@ -952,7 +941,7 @@ void updateCreatedAt_nullCreatedAt() { // Then IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class, executable); assertEquals("A createdAt date is required.", illegalArgumentException.getMessage()); - verifyNoInteractions(institutionConnector, userConnector); + verifyNoInteractions(institutionConnector); } @@ -972,8 +961,6 @@ void updateCreatedAt_onboardingNotFound() { Executable executable = () -> institutionServiceImpl.updateCreatedAt(institutionIdMock, productIdMock, createdAtMock, activatedAtMock); // Then assertThrows(ResourceNotFoundException.class, executable); - verifyNoInteractions(userConnector); - } /** @@ -1012,24 +999,5 @@ void getInstitutionsByTaxCode() { } - /** - * Method under test: {@link InstitutionServiceImpl#getInstitutionUsers(String)} - */ - @Test - void getInstitutionUsers() { - UserInfo userInfo = new UserInfo(); - userInfo.setId("id"); - User user = new User(); - user.setId("id"); - when(userConnector.findByInstitutionId(any())).thenReturn(List.of(userInfo)); - when(userRegistryConnector.getUserByInternalIdWithFiscalCode(any())).thenReturn(user); - List userInfos = institutionServiceImpl.getInstitutionUsers("test"); - assertNotNull(userInfos); - assertFalse(userInfos.isEmpty()); - assertNotNull(userInfos.get(0)); - assertEquals(userInfos.get(0).getId(), userInfo.getId()); - verify(userConnector).findByInstitutionId("test"); - } - } diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java index 61382a619..b067836b4 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java @@ -1,15 +1,7 @@ package it.pagopa.selfcare.mscore.core; -import it.pagopa.selfcare.commons.base.security.PartyRole; import it.pagopa.selfcare.mscore.api.InstitutionConnector; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.constant.Env; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.exception.InvalidRequestException; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.UserBinding; import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,16 +12,15 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; @ExtendWith(SpringExtension.class) class OnboardingDaoTest { @Mock private InstitutionConnector institutionConnector; - @Mock - private UserConnector userConnector; + @InjectMocks private OnboardingDao onboardingDao; @@ -55,520 +46,4 @@ void rollbackPersistOnboarding() { .findAndRemoveOnboarding(institutionId, onboarding); } - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState2() { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.PENDING); - assertNotNull(onboardedUser); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState4() { - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.DELETED); - assertTrue(onboardedUser.getBindings().isEmpty()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState5() { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.ACTIVE); - assertNotNull(onboardedUser); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState6() { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.SUSPENDED); - assertNotNull(onboardedUser); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState8() { - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(new ArrayList<>()); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.PENDING); - assertEquals(1, onboardedUser.getBindings().size()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState9() { - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.ACTIVE); - assertTrue(onboardedUser.getBindings().isEmpty()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState10() { - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.SUSPENDED); - assertTrue(onboardedUser.getBindings().isEmpty()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState11() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole(""); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - assertThrows(InvalidRequestException.class, () -> onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.PENDING)); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState12() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.DELETED); - assertTrue(onboardedUser.getBindings().isEmpty()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState13() { - doNothing().when(userConnector) - .findAndUpdateState(any(), any(), any(), any()); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole(""); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.ACTIVE); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.SUSPENDED); - verify(userConnector).findAndUpdateState(any(), any(), any(), any()); - assertEquals(1, onboardedUser.getBindings().size()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState14() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - onboardingDao.updateUserProductState(onboardedUser, "42", RelationshipState.TOBEVALIDATED); - assertTrue(onboardedUser.getBindings().isEmpty()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState15() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(new ArrayList<>()); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - onboardingDao.updateUserProductState(onboardedUser, "foo", RelationshipState.PENDING); - assertEquals(1, onboardedUser.getBindings().size()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState17() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - onboardingDao.updateUserProductState(onboardedUser, "foo", RelationshipState.PENDING); - assertEquals(1, onboardedUser.getBindings().size()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState18() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - OnboardedProduct onboardedProduct1 = new OnboardedProduct(); - onboardedProduct1.setContract("it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct"); - onboardedProduct1.setCreatedAt(null); - onboardedProduct1.setEnv(Env.DEV); - onboardedProduct1.setProductId("Product Id"); - onboardedProduct1.setProductRole("it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct"); - onboardedProduct1.setRelationshipId("Relationship Id"); - onboardedProduct1.setRole(PartyRole.DELEGATE); - onboardedProduct1.setStatus(RelationshipState.ACTIVE); - onboardedProduct1.setTokenId("ABC123"); - onboardedProduct1.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct1); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - onboardingDao.updateUserProductState(onboardedUser, "foo", RelationshipState.PENDING); - assertEquals(1, onboardedUser.getBindings().size()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState19() { - - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - OnboardedProduct onboardedProduct = mock(OnboardedProduct.class); - when(onboardedProduct.getRelationshipId()).thenReturn("42"); - doNothing().when(onboardedProduct).setContract(any()); - doNothing().when(onboardedProduct).setCreatedAt( any()); - doNothing().when(onboardedProduct).setEnv(any()); - doNothing().when(onboardedProduct).setProductId(any()); - doNothing().when(onboardedProduct).setProductRole(any()); - doNothing().when(onboardedProduct).setRelationshipId(any()); - doNothing().when(onboardedProduct).setRole( any()); - doNothing().when(onboardedProduct).setStatus( any()); - doNothing().when(onboardedProduct).setTokenId(any()); - doNothing().when(onboardedProduct).setUpdatedAt( any()); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - onboardingDao.updateUserProductState(onboardedUser, "foo", RelationshipState.PENDING); - verify(onboardedProduct).getRelationshipId(); - verify(onboardedProduct).setContract(any()); - verify(onboardedProduct).setCreatedAt( any()); - verify(onboardedProduct).setEnv(any()); - verify(onboardedProduct).setProductId(any()); - verify(onboardedProduct).setProductRole(any()); - verify(onboardedProduct).setRelationshipId(any()); - verify(onboardedProduct).setRole( any()); - verify(onboardedProduct).setStatus( any()); - verify(onboardedProduct).setTokenId(any()); - verify(onboardedProduct).setUpdatedAt( any()); - assertEquals(1, onboardedUser.getBindings().size()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState20() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - OnboardedProduct onboardedProduct = mock(OnboardedProduct.class); - when(onboardedProduct.getStatus()).thenReturn(RelationshipState.PENDING); - when(onboardedProduct.getRelationshipId()).thenReturn("foo"); - doNothing().when(onboardedProduct).setContract(any()); - doNothing().when(onboardedProduct).setCreatedAt( any()); - doNothing().when(onboardedProduct).setEnv(any()); - doNothing().when(onboardedProduct).setProductId(any()); - doNothing().when(onboardedProduct).setProductRole(any()); - doNothing().when(onboardedProduct).setRelationshipId(any()); - doNothing().when(onboardedProduct).setRole( any()); - doNothing().when(onboardedProduct).setStatus( any()); - doNothing().when(onboardedProduct).setTokenId(any()); - doNothing().when(onboardedProduct).setUpdatedAt( any()); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - assertThrows(InvalidRequestException.class, - () -> onboardingDao.updateUserProductState(onboardedUser, "foo", RelationshipState.PENDING)); - verify(onboardedProduct).getStatus(); - verify(onboardedProduct, atLeast(1)).getRelationshipId(); - verify(onboardedProduct).setContract(any()); - verify(onboardedProduct).setCreatedAt( any()); - verify(onboardedProduct).setEnv(any()); - verify(onboardedProduct).setProductId(any()); - verify(onboardedProduct).setProductRole(any()); - verify(onboardedProduct).setRelationshipId(any()); - verify(onboardedProduct).setRole( any()); - verify(onboardedProduct).setStatus( any()); - verify(onboardedProduct).setTokenId(any()); - verify(onboardedProduct).setUpdatedAt( any()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState21() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - OnboardedProduct onboardedProduct = mock(OnboardedProduct.class); - when(onboardedProduct.getStatus()).thenReturn(RelationshipState.PENDING); - when(onboardedProduct.getRelationshipId()).thenReturn("foo"); - doNothing().when(onboardedProduct).setContract(any()); - doNothing().when(onboardedProduct).setCreatedAt( any()); - doNothing().when(onboardedProduct).setEnv(any()); - doNothing().when(onboardedProduct).setProductId(any()); - doNothing().when(onboardedProduct).setProductRole(any()); - doNothing().when(onboardedProduct).setRelationshipId(any()); - doNothing().when(onboardedProduct).setRole( any()); - doNothing().when(onboardedProduct).setStatus( any()); - doNothing().when(onboardedProduct).setTokenId(any()); - doNothing().when(onboardedProduct).setUpdatedAt( any()); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - assertThrows(InvalidRequestException.class, - () -> onboardingDao.updateUserProductState(onboardedUser, "foo", RelationshipState.ACTIVE)); - verify(onboardedProduct).getStatus(); - verify(onboardedProduct, atLeast(1)).getRelationshipId(); - verify(onboardedProduct).setContract(any()); - verify(onboardedProduct).setCreatedAt( any()); - verify(onboardedProduct).setEnv(any()); - verify(onboardedProduct).setProductId(any()); - verify(onboardedProduct).setProductRole(any()); - verify(onboardedProduct).setRelationshipId(any()); - verify(onboardedProduct).setRole( any()); - verify(onboardedProduct).setStatus( any()); - verify(onboardedProduct).setTokenId(any()); - verify(onboardedProduct).setUpdatedAt( any()); - } - - /** - * Method under test: {@link OnboardingDao#updateUserProductState(OnboardedUser, String, RelationshipState)} - */ - @Test - void testUpdateUserProductState22() { - - OnboardingDao onboardingDao = new OnboardingDao(null, null); - OnboardedProduct onboardedProduct = mock(OnboardedProduct.class); - when(onboardedProduct.getStatus()).thenReturn(RelationshipState.PENDING); - when(onboardedProduct.getRelationshipId()).thenReturn("foo"); - doNothing().when(onboardedProduct).setContract(any()); - doNothing().when(onboardedProduct).setCreatedAt( any()); - doNothing().when(onboardedProduct).setEnv(any()); - doNothing().when(onboardedProduct).setProductId(any()); - doNothing().when(onboardedProduct).setProductRole(any()); - doNothing().when(onboardedProduct).setRelationshipId(any()); - doNothing().when(onboardedProduct).setRole( any()); - doNothing().when(onboardedProduct).setStatus( any()); - doNothing().when(onboardedProduct).setTokenId(any()); - doNothing().when(onboardedProduct).setUpdatedAt( any()); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - assertThrows(InvalidRequestException.class, - () -> onboardingDao.updateUserProductState(onboardedUser, "foo", RelationshipState.SUSPENDED)); - verify(onboardedProduct).getStatus(); - verify(onboardedProduct, atLeast(1)).getRelationshipId(); - verify(onboardedProduct).setContract(any()); - verify(onboardedProduct).setCreatedAt( any()); - verify(onboardedProduct).setEnv(any()); - verify(onboardedProduct).setProductId(any()); - verify(onboardedProduct).setProductRole(any()); - verify(onboardedProduct).setRelationshipId(any()); - verify(onboardedProduct).setRole( any()); - verify(onboardedProduct).setStatus( any()); - verify(onboardedProduct).setTokenId(any()); - verify(onboardedProduct).setUpdatedAt( any()); - } } diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java index 355e0994a..12902c97b 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java @@ -13,14 +13,11 @@ import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; import it.pagopa.selfcare.mscore.model.Certification; import it.pagopa.selfcare.mscore.model.CertifiedField; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionBinding; import it.pagopa.selfcare.mscore.model.institution.Billing; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.InstitutionUpdate; import it.pagopa.selfcare.mscore.model.institution.Onboarding; import it.pagopa.selfcare.mscore.model.onboarding.*; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; import it.pagopa.selfcare.mscore.model.user.User; import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import org.junit.jupiter.api.Assertions; @@ -30,34 +27,22 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.context.ContextConfiguration; -import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import static it.pagopa.selfcare.mscore.core.util.TestUtils.dummyInstitutionPa; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; @ContextConfiguration(classes = {OnboardingServiceImpl.class}) @ExtendWith(MockitoExtension.class) class OnboardingServiceImplTest { - @Mock - private ContractService contractService; - @Mock private ContractEventNotificationService contractEventNotificationService; - @Mock - private UserService userService; - @Mock - private MailNotificationService emailService; - - @Mock - private UserRelationshipService userRelationshipService; - @Mock private OnboardingDao onboardingDao; @@ -187,63 +172,6 @@ void testVerifyOnboardingInfo7() { any()); } - /** - * Method under test: {@link OnboardingServiceImpl#getOnboardingInfo(String, String, String[], String)} - */ - @Test - void testGetOnboardingInfo10() { - - Institution institution = dummyInstitutionPa(); - - OnboardedProduct onboardedProduct = getOnboardedProduct(); - - UserInstitutionBinding userBinding = new UserInstitutionBinding(); - userBinding.setInstitutionId("42"); - userBinding.setProducts(onboardedProduct); - - UserInstitutionAggregation userInstitutionAggregation = new UserInstitutionAggregation(); - userInstitutionAggregation.setId("42"); - userInstitutionAggregation.setBindings(userBinding); - userInstitutionAggregation.setInstitutions(List.of(institution)); - when(userService.findUserInstitutionAggregation(any())).thenReturn(List.of(userInstitutionAggregation)); - List actualOnboardingInfo = onboardingServiceImpl.getOnboardingInfo("42", "42", new String[]{}, - "42"); - assertEquals(1, actualOnboardingInfo.size()); - OnboardingInfo getResult = actualOnboardingInfo.get(0); - Institution institution1 = getResult.getInstitution(); - assertSame(institution, institution1); - List onboarding1 = institution1.getOnboarding(); - assertTrue(onboarding1.isEmpty()); - } - - /** - * Method under test: {@link OnboardingServiceImpl#getOnboardingInfo(String, String, String[], String)} - */ - @Test - void testGetOnboardingInfoWithTwoParameters() { - - Institution institution = dummyInstitutionPa(); - - OnboardedProduct onboardedProduct = getOnboardedProduct(); - - UserInstitutionBinding userBinding = new UserInstitutionBinding(); - userBinding.setInstitutionId("42"); - userBinding.setProducts(onboardedProduct); - - UserInstitutionAggregation userInstitutionAggregation = new UserInstitutionAggregation(); - userInstitutionAggregation.setId("42"); - userInstitutionAggregation.setBindings(userBinding); - userInstitutionAggregation.setInstitutions(List.of(institution)); - when(userService.findUserInstitutionAggregation(any())).thenReturn(List.of(userInstitutionAggregation)); - var actualOnboardingInfo = onboardingServiceImpl.getOnboardingInfo("42", null, null, "42"); - assertEquals(1, actualOnboardingInfo.size()); - OnboardingInfo getResult = actualOnboardingInfo.get(0); - Institution institution1 = getResult.getInstitution(); - assertSame(institution, institution1); - List onboarding1 = institution1.getOnboarding(); - assertTrue(onboarding1.isEmpty()); - } - private Institution dummyInstitution() { Institution institution = new Institution(); institution.setId("42"); @@ -268,48 +196,6 @@ private UserToOnboard createSimpleUserToOnboard() { return userToOnboard; } - /** - * Method under test: {@link OnboardingServiceImpl#retrieveDocument(String)} - */ - @Test - void testRetrieveDocument() { - when(userRelationshipService.retrieveRelationship(any())).thenReturn(new RelationshipInfo()); - assertThrows(ResourceNotFoundException.class, () -> onboardingServiceImpl.retrieveDocument("42")); - verify(userRelationshipService).retrieveRelationship(any()); - } - - /** - * Method under test: {@link OnboardingServiceImpl#retrieveDocument(String)} - */ - @Test - void testRetrieveDocument3() { - Institution institution = new Institution(); - when(userRelationshipService.retrieveRelationship(any())) - .thenReturn(new RelationshipInfo(institution, "42", new OnboardedProduct())); - assertThrows(ResourceNotFoundException.class, () -> onboardingServiceImpl.retrieveDocument("42")); - verify(userRelationshipService).retrieveRelationship(any()); - } - - /** - * Method under test: {@link OnboardingServiceImpl#retrieveDocument(String)} - */ - @Test - void testRetrieveDocument4(){ - OnboardedProduct onboardedProduct = getOnboardedProduct(); - RelationshipInfo relationshipInfo = mock(RelationshipInfo.class); - when(relationshipInfo.getOnboardedProduct()).thenReturn(onboardedProduct); - when(userRelationshipService.retrieveRelationship(any())).thenReturn(relationshipInfo); - - ResourceResponse resourceResponse = new ResourceResponse(); - resourceResponse.setData("AXAXAXAX".getBytes(StandardCharsets.UTF_8)); - resourceResponse.setFileName("foo.txt"); - resourceResponse.setMimetype("Mimetype"); - when(contractService.getFile(any())).thenReturn(resourceResponse); - assertSame(resourceResponse, onboardingServiceImpl.retrieveDocument("42")); - verify(userRelationshipService).retrieveRelationship(any()); - verify(relationshipInfo, atLeast(1)).getOnboardedProduct(); - verify(contractService).getFile(any()); - } @Test void persistOnboarding_shouldThrowIfOnboardingExists() { @@ -411,8 +297,6 @@ void persistOnboarding_whenUserNotExistsOnRegistry() { .findAndUpdate(any(), captor.capture(), any(), any()); Onboarding actual = captor.getValue(); assertEquals(actual.getCreatedAt().getDayOfYear(), LocalDate.now().getDayOfYear()); - - verifyNoMoreInteractions(userService); } private OnboardedProduct getOnboardedProduct() { diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceTest.java index 7b638d88a..0de605a67 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceTest.java @@ -1,8 +1,9 @@ package it.pagopa.selfcare.mscore.core; import it.pagopa.selfcare.mscore.api.InstitutionConnector; -import it.pagopa.selfcare.mscore.api.UserConnector; import it.pagopa.selfcare.mscore.constant.RelationshipState; +import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; +import it.pagopa.selfcare.mscore.core.mapper.TokenMapperImpl; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; import org.junit.jupiter.api.Test; @@ -10,6 +11,7 @@ import org.junit.jupiter.api.function.Executable; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; @@ -26,11 +28,10 @@ class QueueNotificationServiceTest { private QueueNotificationServiceImpl schedulerService; @Mock private ContractEventNotificationService contractService; - - @Mock - private UserConnector userConnector; @Mock private InstitutionConnector institutionConnector; + @Spy + private TokenMapper tokenMapper = new TokenMapperImpl(); @Test @@ -50,7 +51,7 @@ void sendContractsNotificationsByInstitutionIdAndTokenId() { onboardingDeleted.setStatus(RelationshipState.DELETED); institution.setOnboarding(List.of(onboardingActive, onboardingDeleted, onboarding)); - schedulerService = new QueueNotificationServiceImpl(contractService, institutionConnector); + schedulerService = new QueueNotificationServiceImpl(contractService, institutionConnector, tokenMapper); when(institutionConnector.findById(institutionId)).thenReturn(institution); //when diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserEventServiceTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/UserEventServiceTest.java index 97751d610..2db960a5e 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserEventServiceTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/UserEventServiceTest.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import it.pagopa.selfcare.mscore.api.UserConnector; import it.pagopa.selfcare.mscore.api.UserRegistryConnector; import it.pagopa.selfcare.mscore.config.CoreConfig; import it.pagopa.selfcare.mscore.constant.RelationshipState; @@ -13,15 +12,8 @@ import it.pagopa.selfcare.mscore.core.util.UserNotificationMapperImpl; import it.pagopa.selfcare.mscore.core.util.model.DummyUser; import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.UserToNotify; -import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; import it.pagopa.selfcare.mscore.model.user.User; import it.pagopa.selfcare.mscore.model.user.UserBinding; import org.junit.jupiter.api.Test; @@ -29,7 +21,6 @@ import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; @@ -40,13 +31,10 @@ import org.springframework.util.concurrent.ListenableFutureCallback; import java.util.List; -import java.util.Optional; import java.util.UUID; -import static it.pagopa.selfcare.commons.utils.TestUtils.checkNotNullFields; import static it.pagopa.selfcare.commons.utils.TestUtils.mockInstance; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -61,8 +49,6 @@ class UserEventServiceTest { @Spy private ObjectMapper mapper; @Mock - private UserConnector userConnector; - @Mock private UserRegistryConnector userRegistryConnector; @Mock private CoreConfig coreConfig; @@ -76,326 +62,6 @@ class UserEventServiceTest { @Spy UserNotificationMapper userNotificationMapper = new UserNotificationMapperImpl(); - @Test - void sendLegalTokenUserNotification_ok() { - //given - final String institutionId = UUID.randomUUID().toString(); - final String productId = "productId"; - final String tokenId = UUID.randomUUID().toString(); - final String userId = UUID.randomUUID().toString(); - Token token = mockInstance(new Token()); - token.setId(tokenId); - token.setProductId(productId); - token.setInstitutionId(institutionId); - TokenUser tokenUser = mockInstance(new TokenUser()); - tokenUser.setUserId(userId); - token.setUsers(List.of(tokenUser)); - - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setTokenId(tokenId); - onboardedProduct.setProductId(productId); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - UserBinding userBinding = new UserBinding(institutionId, List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser(institutionId); - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - - when(kafkaTemplateUsers.send(any(), any())) - .thenReturn(mockFuture); - doAnswer(invocationOnMock -> { - ListenableFutureCallback callback = invocationOnMock.getArgument(0); - callback.onSuccess(mockSendResult); - return null; - }).when(mockFuture).addCallback(any(ListenableFutureCallback.class)); - - //when - Executable executable = () -> userEventService.sendLegalTokenUserNotification(token); - //then - assertDoesNotThrow(executable); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verify(kafkaTemplateUsers, times(1)).send(any(), any()); - verifyNoMoreInteractions(userConnector, userRegistryConnector, kafkaTemplateUsers); - - } - - @Test - void sendLegalTokenUsersNotification_onFailure(){ - //given - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - final String tokenId = UUID.randomUUID().toString(); - final String userId = UUID.randomUUID().toString(); - - Token token = mockInstance(new Token()); - token.setId(tokenId); - token.setProductId(productId); - token.setInstitutionId(institutionId); - TokenUser tokenUser = mockInstance(new TokenUser()); - tokenUser.setUserId(userId); - token.setUsers(List.of(tokenUser)); - - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setTokenId(tokenId); - onboardedProduct.setProductId(productId); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - UserBinding userBinding = new UserBinding(institutionId, List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser("institutionId"); - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - - RuntimeException ex = new RuntimeException("error"); - when(kafkaTemplateUsers.send(any(), any())) - .thenReturn(mockFuture); - doAnswer(invocationOnMock -> { - ListenableFutureCallback callback = invocationOnMock.getArgument(0); - callback.onFailure(ex); - return null; - }).when(mockFuture).addCallback(any(ListenableFutureCallback.class)); - - //when - Executable executable = () -> userEventService.sendLegalTokenUserNotification(token); - //then - assertDoesNotThrow(executable); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verify(kafkaTemplateUsers, times(1)).send(any(), any()); - verifyNoMoreInteractions(userConnector, userRegistryConnector, kafkaTemplateUsers); - } - - @Test - void sendOperatorUserNotification(){ - //given - final String relationshipId = UUID.randomUUID().toString(); - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - - RelationshipInfo relationshipInfo = mockInstance(new RelationshipInfo()); - relationshipInfo.setUserId(userId); - Institution institution = mockInstance(new Institution()); - institution.setId(institutionId); - relationshipInfo.setInstitution(institution); - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setRelationshipId(relationshipId); - onboardedProduct.setProductId(productId); - relationshipInfo.setOnboardedProduct(onboardedProduct); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - UserBinding userBinding = new UserBinding(institutionId, List.of(onboardedProduct)); - userBinding.setInstitutionId(institutionId); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser(institutionId); - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - when(kafkaTemplateUsers.send(any(), any())) - .thenReturn(mockFuture); - doAnswer(invocationOnMock -> { - ListenableFutureCallback callback = invocationOnMock.getArgument(0); - callback.onSuccess(mockSendResult); - return null; - }).when(mockFuture).addCallback(any(ListenableFutureCallback.class)); - //when - Executable executable = () -> userEventService.sendOperatorUserNotification(relationshipInfo, QueueEvent.ADD); - //then - assertDoesNotThrow(executable); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verify(kafkaTemplateUsers, times(1)).send(any(), any()); - verifyNoMoreInteractions(userConnector, userRegistryConnector, kafkaTemplateUsers); - - } - - @Test - void sendOperatorJsonError() throws JsonProcessingException { - //given - final String relationshipId = UUID.randomUUID().toString(); - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - - RelationshipInfo relationshipInfo = mockInstance(new RelationshipInfo()); - relationshipInfo.setUserId(userId); - Institution institution = mockInstance(new Institution()); - institution.setId(institutionId); - relationshipInfo.setInstitution(institution); - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setRelationshipId(relationshipId); - onboardedProduct.setProductId(productId); - relationshipInfo.setOnboardedProduct(onboardedProduct); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - UserBinding userBinding = new UserBinding(institutionId, List.of(onboardedProduct)); - userBinding.setInstitutionId(institutionId); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser(institutionId); - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - - when(mapper.writeValueAsString(any())).thenThrow(JsonProcessingException.class); - //when - Executable executable = () -> userEventService.sendOperatorUserNotification(relationshipInfo, QueueEvent.ADD); - //then - assertDoesNotThrow(executable); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verifyNoMoreInteractions(userConnector, userRegistryConnector); - } - @Test - void toUserToNotifyFromToken() { - //given - final Optional tokenId = Optional.of(UUID.randomUUID().toString()); - final Optional relationshipId = Optional.empty(); - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setTokenId(tokenId.get()); - onboardedProduct.setProductId(productId); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - UserBinding userBinding = new UserBinding(institutionId, List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser(institutionId); - - - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - - - //when - List usersToNotify = userEventService.toUserToNotify(userId, institutionId, productId, relationshipId, tokenId); - //then - assertEquals(1, usersToNotify.size()); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verifyNoMoreInteractions(userConnector, userRegistryConnector); - } - - @Test - void userToNotifyFromRelationship() { - //given - final Optional tokenId = Optional.empty(); - final Optional relationshipId = Optional.of(UUID.randomUUID().toString()); - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setRelationshipId(relationshipId.get()); - onboardedProduct.setProductId(productId); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - UserBinding userBinding = new UserBinding(institutionId, List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser(institutionId); - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - //when - List usersToNotify = userEventService.toUserToNotify(userId, institutionId, productId, relationshipId, tokenId); - //then - assertEquals(1, usersToNotify.size()); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verifyNoMoreInteractions(userConnector, userRegistryConnector); - } - - @Test - void toUserToNotifyNoProduct() { - //given - final Optional tokenId = Optional.empty(); - final Optional relationshipId = Optional.of(UUID.randomUUID().toString()); - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setRelationshipId(relationshipId.get()); - onboardedProduct.setProductId("prod-diff"); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - UserBinding userBinding = new UserBinding(institutionId, List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser(institutionId); - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - //when - List usersToNotify = userEventService.toUserToNotify(userId, institutionId, productId, relationshipId, tokenId); - //then - assertEquals(0, usersToNotify.size()); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verifyNoMoreInteractions(userConnector, userRegistryConnector); - } - - @Test - void toUserToNotifyDifferentInstitution() { - //given - final Optional tokenId = Optional.empty(); - final Optional relationshipId = Optional.of(UUID.randomUUID().toString()); - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setRelationshipId(relationshipId.get()); - onboardedProduct.setProductId(productId); - OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - UserBinding userBinding = new UserBinding(UUID.randomUUID().toString(), List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - final User userMock = new DummyUser(institutionId); - when(userRegistryConnector.getUserByInternalId(any())) - .thenReturn(userMock); - when(userConnector.findById(any())).thenReturn(onboardedUser); - //when - List usersToNotify = userEventService.toUserToNotify(userId, institutionId, productId, relationshipId, tokenId); - //then - assertEquals(0, usersToNotify.size()); - verify(userConnector, times(1)).findById(userId); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - verifyNoMoreInteractions(userConnector, userRegistryConnector); - } - - @Test - void updateUserEventNotification() throws JsonProcessingException { - //given - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "prod-test"; - when(kafkaTemplateUsers.send(any(), any())) - .thenReturn(mockFuture); - doAnswer(invocationOnMock -> { - ListenableFutureCallback callback = invocationOnMock.getArgument(0); - callback.onSuccess(mockSendResult); - return null; - }).when(mockFuture).addCallback(any(ListenableFutureCallback.class)); - final OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - final OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setProductId(productId); - onboardedProduct.setStatus(RelationshipState.ACTIVE); - final UserBinding userBinding = mockInstance(new UserBinding()); - final User user = new DummyUser(institutionId); - user.setId(userId); - userBinding.setInstitutionId(institutionId); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userRegistryConnector.getUserByInternalId(any())).thenReturn(user); - when(userConnector.findById(userId)).thenReturn(onboardedUser); - //when - Executable executable = () -> userEventService.sendUserNotificationToQueue(userId, institutionId, QueueEvent.UPDATE); - //then - assertDoesNotThrow(executable); - ArgumentCaptor messageArgumentCaptor = ArgumentCaptor.forClass(UserNotificationToSend.class); - verify(mapper, times(1)).writeValueAsString(messageArgumentCaptor.capture()); - UserNotificationToSend message = messageArgumentCaptor.getValue(); - checkNotNullFields(message, "user.fiscalCode"); - } @ParameterizedTest @EnumSource(value = RelationshipState.class, names = {"ACTIVE", "DELETED", "SUSPENDED"}) diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImplTest.java index 472db633a..c637611ad 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImplTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/UserNotificationServiceImplTest.java @@ -2,38 +2,23 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import freemarker.template.Configuration; -import freemarker.template.Template; import it.pagopa.selfcare.mscore.api.FileStorageConnector; import it.pagopa.selfcare.mscore.api.NotificationServiceConnector; -import it.pagopa.selfcare.mscore.api.ProductConnector; -import it.pagopa.selfcare.mscore.model.CertifiedField; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.WorkContact; import it.pagopa.selfcare.mscore.model.onboarding.MailTemplate; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.onboarding.common.PartyRole; -import it.pagopa.selfcare.product.entity.Product; -import it.pagopa.selfcare.product.entity.ProductRole; -import it.pagopa.selfcare.product.entity.ProductRoleInfo; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.mail.MailPreparationException; -import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @@ -42,21 +27,9 @@ class UserNotificationServiceImplTest { @InjectMocks private UserNotificationServiceImpl userNotificationService; - @Mock - private Configuration freemarkerConfig; - @Mock private NotificationServiceConnector notificationConnector; - @Mock - private ProductConnector productsConnector; - - @Mock - private UserService userService; - - @Mock - private InstitutionService institutionService; - @Mock private FileStorageConnector fileStorageConnector; @@ -64,29 +37,6 @@ class UserNotificationServiceImplTest { private ObjectMapper objectMapper; - @Test - void sendAddedProductRoleNotification() throws IOException { - Institution institution = new Institution(); - institution.setId("id"); - List labels = new ArrayList<>(); - labels.add("label"); - - User user1 = TestUtils.createSimpleUser(); - - Map workContacts1 = new HashMap<>(); - WorkContact workContact = new WorkContact(); - CertifiedField email = new CertifiedField<>(); - email.setValue("email"); - workContact.setEmail(email); - workContacts1.put("id",workContact); - - user1.setWorkContacts(workContacts1); - when(userService.retrieveUserFromUserRegistry(any())).thenReturn(user1); - Template template = mock(Template.class); - when(freemarkerConfig.getTemplate(any())).thenReturn(template); - assertDoesNotThrow(() -> userNotificationService.sendAddedProductRoleNotification("id",institution,"product", labels, "name","surname")); - } - @Test void sendDelegationUserNotification() throws JsonProcessingException { when(fileStorageConnector.getTemplateFile(any())).thenReturn("template"); @@ -96,187 +46,4 @@ void sendDelegationUserNotification() throws JsonProcessingException { when(objectMapper.readValue(anyString(),(Class) any())).thenReturn(mailTemplate); assertDoesNotThrow(() -> userNotificationService.sendDelegationUserNotification(List.of("id"),"institution","product", new HashMap<>())); } - - - @Test - void sendAddedProductRoleNotification2() throws IOException { - Institution institution = new Institution(); - institution.setId("id"); - List labels = new ArrayList<>(); - labels.add("label"); - labels.add("la"); - labels.add("Lab"); - - User user1 = TestUtils.createSimpleUser(); - - Map workContacts1 = new HashMap<>(); - WorkContact workContact = new WorkContact(); - CertifiedField email = new CertifiedField<>(); - email.setValue("email"); - workContact.setEmail(email); - workContacts1.put("id",workContact); - - user1.setWorkContacts(workContacts1); - when(userService.retrieveUserFromUserRegistry(any())).thenReturn(user1); - Template template = mock(Template.class); - when(freemarkerConfig.getTemplate(any())).thenReturn(template); - assertDoesNotThrow(() -> userNotificationService.sendAddedProductRoleNotification("id",institution,"product", labels, "name","surname")); - } - - @Test - void sendDeletedUserNotification(){ - User user1 = TestUtils.createSimpleUser(); - - Map workContacts1 = new HashMap<>(); - WorkContact workContact = new WorkContact(); - CertifiedField email = new CertifiedField<>(); - email.setValue("email"); - workContact.setEmail(email); - workContacts1.put("id",workContact); - - user1.setWorkContacts(workContacts1); - when(userService.retrieveUserFromUserRegistry(any())).thenReturn(user1); - - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("id"); - - Institution institution = new Institution(); - institution.setId("id"); - institution.setDescription("desc"); - - when(institutionService.retrieveInstitutionById(any())).thenReturn(institution); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setProductId("id"); - onboardedProduct.setRelationshipId("id"); - onboardedProduct.setProductRole("MANAGER"); - List onboardedProducts = new ArrayList<>(); - onboardedProducts.add(onboardedProduct); - - userBinding.setProducts(onboardedProducts); - - Product product = new Product(); - product.setId("id"); - product.setTitle("id"); - EnumMap map = new EnumMap<>(PartyRole.class); - ProductRoleInfo productRoleInfo = new ProductRoleInfo(); - List productRoles = new ArrayList<>(); - ProductRole productRole = new ProductRole(); - productRole.setLabel("MANAGER"); - productRole.setCode("MANAGER"); - productRoles.add(productRole); - productRoleInfo.setRoles(productRoles); - map.put(PartyRole.MANAGER, productRoleInfo); - - product.setRoleMappings(map); - - when(productsConnector.getProductById(any())).thenReturn(product); - - assertThrows(MailPreparationException.class, () -> userNotificationService.sendDeletedUserNotification("id","userid",userBinding, "name","surname")); - } - - @Test - void sendActivatedUserNotification(){ - User user1 = TestUtils.createSimpleUser(); - - Map workContacts1 = new HashMap<>(); - WorkContact workContact = new WorkContact(); - CertifiedField email = new CertifiedField<>(); - email.setValue("email"); - workContact.setEmail(email); - workContacts1.put("id",workContact); - - user1.setWorkContacts(workContacts1); - when(userService.retrieveUserFromUserRegistry(any())).thenReturn(user1); - - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("id"); - - Institution institution = new Institution(); - institution.setId("id"); - institution.setDescription("desc"); - - when(institutionService.retrieveInstitutionById(any())).thenReturn(institution); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setProductId("id"); - onboardedProduct.setRelationshipId("id"); - onboardedProduct.setProductRole("MANAGER"); - List onboardedProducts = new ArrayList<>(); - onboardedProducts.add(onboardedProduct); - - userBinding.setProducts(onboardedProducts); - - Product product = new Product(); - product.setId("id"); - product.setTitle("id"); - EnumMap map = new EnumMap<>(PartyRole.class); - ProductRoleInfo productRoleInfo = new ProductRoleInfo(); - List productRoles = new ArrayList<>(); - ProductRole productRole = new ProductRole(); - productRole.setLabel("MANAGER"); - productRole.setCode("MANAGER"); - productRoles.add(productRole); - productRoleInfo.setRoles(productRoles); - map.put(PartyRole.MANAGER, productRoleInfo); - - product.setRoleMappings(map); - - when(productsConnector.getProductById(any())).thenReturn(product); - - assertThrows(MailPreparationException.class, () -> userNotificationService.sendActivatedUserNotification("id","userid",userBinding,"name","surname")); - } - - - @Test - void sendSuspendedUserNotification() throws JsonProcessingException { - User user1 = TestUtils.createSimpleUser(); - - Map workContacts1 = new HashMap<>(); - WorkContact workContact = new WorkContact(); - CertifiedField email = new CertifiedField<>(); - email.setValue("email"); - workContact.setEmail(email); - workContacts1.put("id",workContact); - - user1.setWorkContacts(workContacts1); - when(userService.retrieveUserFromUserRegistry(any())).thenReturn(user1); - - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("id"); - - Institution institution = new Institution(); - institution.setId("id"); - institution.setDescription("desc"); - - when(institutionService.retrieveInstitutionById(any())).thenReturn(institution); - - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setProductId("id"); - onboardedProduct.setRelationshipId("id"); - onboardedProduct.setProductRole("MANAGER"); - List onboardedProducts = new ArrayList<>(); - onboardedProducts.add(onboardedProduct); - - userBinding.setProducts(onboardedProducts); - - Product product = new Product(); - product.setId("id"); - product.setTitle("id"); - EnumMap map = new EnumMap<>(PartyRole.class); - ProductRoleInfo productRoleInfo = new ProductRoleInfo(); - List productRoles = new ArrayList<>(); - ProductRole productRole = new ProductRole(); - productRole.setLabel("MANAGER"); - productRole.setCode("MANAGER"); - productRoles.add(productRole); - productRoleInfo.setRoles(productRoles); - map.put(PartyRole.MANAGER, productRoleInfo); - - product.setRoleMappings(map); - - when(productsConnector.getProductById(any())).thenReturn(product); - - assertThrows(MailPreparationException.class, () -> userNotificationService.sendSuspendedUserNotification("id","userid",userBinding, "name","surname")); - } } diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserRelationshipServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/UserRelationshipServiceImplTest.java deleted file mode 100644 index 17ce23192..000000000 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserRelationshipServiceImplTest.java +++ /dev/null @@ -1,518 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.constant.Env; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.exception.InvalidRequestException; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class UserRelationshipServiceImplTest { - @Mock - private InstitutionService institutionService; - - @Mock - private UserEventService userEventService; - - @Mock - private OnboardingDao onboardingDao; - - @Mock - private UserConnector userConnector; - - @InjectMocks - private UserRelationshipServiceImpl userRelationshipServiceImpl; - - @Mock - private UserNotificationService userNotificationService; - - /** - * Method under test: {@link UserRelationshipServiceImpl#findByRelationshipId(String)} - */ - @Test - void testFindByRelationshipId() { - OnboardedUser onboardedUser = new OnboardedUser(); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertSame(onboardedUser, userRelationshipServiceImpl.findByRelationshipId("42")); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#findByRelationshipId(String)} - */ - @Test - void testFindByRelationshipId2() { - OnboardedUser onboardedUser = new OnboardedUser(); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertSame(onboardedUser, userRelationshipServiceImpl.findByRelationshipId("42")); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#findByRelationshipId(String)} - */ - @Test - void testFindByRelationshipId3() { - when(userConnector.findByRelationshipId(any())) - .thenThrow(new InvalidRequestException("An error occurred", "Code")); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.findByRelationshipId("42")); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#activateRelationship(String, String, String)} - */ - @Test - void testActivateRelationship() { - doNothing().when(onboardingDao) - .updateUserProductState(any(), any(), any()); - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setId("id"); - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("42"); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setTokenId("tokenId"); - onboardedProduct.setProductId("productId"); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - userRelationshipServiceImpl.activateRelationship("42", "name","surname"); - verify(onboardingDao).updateUserProductState(any(), any(), any()); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#activateRelationship(String, String, String)} - */ - @Test - void testActivateRelationship2() { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setId("id"); - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("42"); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setTokenId("tokenId"); - onboardedProduct.setProductId("productId"); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - doThrow(new InvalidRequestException("An error occurred", "Code")).when(onboardingDao) - .updateUserProductState(any(), any(), any()); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.activateRelationship("42", "name","surname")); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#suspendRelationship(String, String, String)} - */ - @Test - void testSuspendRelationship() { - doNothing().when(onboardingDao) - .updateUserProductState(any(), any(), any()); - OnboardedUser onboardedUser = new OnboardedUser(); - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("42"); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setTokenId("tokenId"); - onboardedProduct.setProductId("productId"); - onboardedUser.setId("id"); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - userRelationshipServiceImpl.suspendRelationship("42", "name","surname"); - verify(onboardingDao).updateUserProductState(any(), any(), any()); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#suspendRelationship(String, String, String)} - */ - @Test - void testSuspendRelationship2() { - OnboardedUser onboardedUser = new OnboardedUser(); - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("42"); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setTokenId("tokenId"); - onboardedProduct.setProductId("productId"); - onboardedUser.setId("id"); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - doThrow(new InvalidRequestException("An error occurred", "Code")).when(onboardingDao) - .updateUserProductState(any(), any(), any()); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.suspendRelationship("42", "name","surname")); - verify(userConnector).findByRelationshipId(any()); - } - - @Test - void testSuspendRelationship3() { - OnboardedUser onboardedUser = new OnboardedUser(); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setTokenId("tokenId"); - onboardedProduct.setProductId("productId"); - onboardedUser.setId("id"); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.suspendRelationship("42", "name","surname")); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#deleteRelationship(String, String, String)} - */ - @Test - void testDeleteRelationship() { - doNothing().when(onboardingDao) - .updateUserProductState(any(), any(), any()); - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setId("id"); - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId("42"); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setTokenId("tokenId"); - onboardedProduct.setProductId("productId"); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - userRelationshipServiceImpl.deleteRelationship("42", "name","surname"); - verify(onboardingDao).updateUserProductState(any(), any(), any()); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship2() { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship3() { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(new ArrayList<>()); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - } - - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship4() { - when(userConnector.findByRelationshipId(any())) - .thenThrow(new InvalidRequestException("An error occurred", "Code")); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - } - - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship6() { - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(new ArrayList<>()); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship7() { - when(userConnector.findByRelationshipId(any())) - .thenThrow(new InvalidRequestException("An error occurred", "Code")); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - } - - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship8() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole(""); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - Institution institution = new Institution(); - when(institutionService.retrieveInstitutionById(any())).thenReturn(institution); - RelationshipInfo actualRetrieveRelationshipResult = userRelationshipServiceImpl.retrieveRelationship("42"); - assertSame(institution, actualRetrieveRelationshipResult.getInstitution()); - assertNull(actualRetrieveRelationshipResult.getUserId()); - assertSame(onboardedProduct, actualRetrieveRelationshipResult.getOnboardedProduct()); - verify(userConnector).findByRelationshipId(any()); - verify(institutionService).retrieveInstitutionById(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship9() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole(""); - onboardedProduct.setRelationshipId("Relationship Id"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship10() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole(""); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - when(institutionService.retrieveInstitutionById(any())) - .thenThrow(new InvalidRequestException("An error occurred", "Code")); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - verify(institutionService).retrieveInstitutionById(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship12() { - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(new ArrayList<>()); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship14() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - Institution institution = new Institution(); - when(institutionService.retrieveInstitutionById(any())).thenReturn(institution); - RelationshipInfo actualRetrieveRelationshipResult = userRelationshipServiceImpl.retrieveRelationship("42"); - assertSame(institution, actualRetrieveRelationshipResult.getInstitution()); - assertNull(actualRetrieveRelationshipResult.getUserId()); - assertSame(onboardedProduct, actualRetrieveRelationshipResult.getOnboardedProduct()); - verify(userConnector).findByRelationshipId(any()); - verify(institutionService).retrieveInstitutionById(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship15() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - OnboardedProduct onboardedProduct1 = new OnboardedProduct(); - onboardedProduct1.setContract("it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct"); - onboardedProduct1.setCreatedAt(null); - onboardedProduct1.setEnv(Env.DEV); - onboardedProduct1.setProductId("Product Id"); - onboardedProduct1.setProductRole("it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct"); - onboardedProduct1.setRelationshipId("Relationship Id"); - onboardedProduct1.setRole(PartyRole.DELEGATE); - onboardedProduct1.setStatus(RelationshipState.ACTIVE); - onboardedProduct1.setTokenId("ABC123"); - onboardedProduct1.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct1); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - Institution institution = new Institution(); - when(institutionService.retrieveInstitutionById(any())).thenReturn(institution); - RelationshipInfo actualRetrieveRelationshipResult = userRelationshipServiceImpl.retrieveRelationship("42"); - assertSame(institution, actualRetrieveRelationshipResult.getInstitution()); - assertNull(actualRetrieveRelationshipResult.getUserId()); - assertSame(onboardedProduct, actualRetrieveRelationshipResult.getOnboardedProduct()); - verify(userConnector).findByRelationshipId(any()); - verify(institutionService).retrieveInstitutionById(any()); - } - - /** - * Method under test: {@link UserRelationshipServiceImpl#retrieveRelationship(String)} - */ - @Test - void testRetrieveRelationship16() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("Contract"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole("Product Role"); - onboardedProduct.setRelationshipId("42"); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setTokenId("42"); - onboardedProduct.setUpdatedAt(null); - - ArrayList onboardedProductList = new ArrayList<>(); - onboardedProductList.add(onboardedProduct); - - UserBinding userBinding = new UserBinding(); - userBinding.setProducts(onboardedProductList); - - ArrayList userBindingList = new ArrayList<>(); - userBindingList.add(userBinding); - - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setBindings(userBindingList); - when(userConnector.findByRelationshipId(any())).thenReturn(onboardedUser); - when(institutionService.retrieveInstitutionById(any())) - .thenThrow(new InvalidRequestException("An error occurred", "Code")); - assertThrows(InvalidRequestException.class, () -> userRelationshipServiceImpl.retrieveRelationship("42")); - verify(userConnector).findByRelationshipId(any()); - verify(institutionService).retrieveInstitutionById(any()); - } -} diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/UserServiceImplTest.java deleted file mode 100644 index c2d18c43c..000000000 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserServiceImplTest.java +++ /dev/null @@ -1,546 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.api.UserConnector; -import it.pagopa.selfcare.mscore.api.UserRegistryConnector; -import it.pagopa.selfcare.mscore.constant.Env; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.util.NotificationMapper; -import it.pagopa.selfcare.mscore.core.util.NotificationMapperImpl; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapper; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapperImpl; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.Certification; -import it.pagopa.selfcare.mscore.model.CertifiedField; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionAggregation; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionBinding; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionFilter; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.WorkContact; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardingInfo; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.test.context.ContextConfiguration; - -import java.util.*; - -import static it.pagopa.selfcare.commons.utils.TestUtils.mockInstance; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -@ContextConfiguration(classes = {UserServiceImpl.class}) -@ExtendWith(MockitoExtension.class) -class UserServiceImplTest { - - @Mock - private UserRegistryConnector userRegistryConnector; - - @Mock - private UserConnector userConnector; - - @InjectMocks - private UserServiceImpl userServiceImpl; - - @Spy - private NotificationMapper notificationMapper = new NotificationMapperImpl(); - - @Spy - private UserNotificationMapper userNotificationMapper = new UserNotificationMapperImpl(); - - /** - * Method under test: {@link UserServiceImpl#findOnboardedManager(String, String, List)} - */ - @Test - void testFindOnboardedManager() { - OnboardedUser onboardedUser = new OnboardedUser(); - when(userConnector.findOnboardedManager(any(), any(), any())) - .thenReturn(onboardedUser); - assertSame(onboardedUser, userServiceImpl.findOnboardedManager("42", "42", new ArrayList<>())); - verify(userConnector).findOnboardedManager(any(), any(), any()); - } - - /** - * Method under test: {@link UserServiceImpl#findOnboardedManager(String, String, List)} - */ - @Test - void testFindOnboardedManager2() { - OnboardedUser onboardedUser = new OnboardedUser(); - when(userConnector.findOnboardedManager(any(), any(), any())) - .thenReturn(onboardedUser); - assertSame(onboardedUser, userServiceImpl.findOnboardedManager("42", "42", new ArrayList<>())); - verify(userConnector).findOnboardedManager(any(), any(), any()); - } - - /** - * Method under test: {@link UserServiceImpl#findOnboardedManager(String, String, List)} - */ - @Test - void testFindOnboardedManager3() { - when(userConnector.findOnboardedManager(any(), any(), any())) - .thenThrow(new ResourceNotFoundException("An error occurred", "Code")); - List states = new ArrayList<>(); - assertThrows(ResourceNotFoundException.class, - () -> userServiceImpl.findOnboardedManager("42", "42", states)); - verify(userConnector).findOnboardedManager(any(), any(), any()); - } - - /** - * Method under test: {@link UserServiceImpl#findOnboardedManager(String, String, List)} - */ - @Test - void testFindOnboardedManager4() { - when(userConnector.findOnboardedManager(any(), any(), any())) - .thenThrow(new ResourceNotFoundException("An error occurred", "Code")); - List states = new ArrayList<>(); - assertThrows(ResourceNotFoundException.class, - () -> userServiceImpl.findOnboardedManager("42", "42", states)); - verify(userConnector).findOnboardedManager(any(), any(), any()); - } - /** - * Method under test: {@link UserServiceImpl#retrieveUserFromUserRegistry(String)} - */ - @Test - void testRetrieveUserFromUserRegistry() { - CertifiedField certifiedField = new CertifiedField<>(); - certifiedField.setCertification(Certification.NONE); - certifiedField.setValue("42"); - - CertifiedField certifiedField1 = new CertifiedField<>(); - certifiedField1.setCertification(Certification.NONE); - certifiedField1.setValue("42"); - - CertifiedField certifiedField2 = new CertifiedField<>(); - certifiedField2.setCertification(Certification.NONE); - certifiedField2.setValue("42"); - - User user = new User(); - user.setEmail(certifiedField); - user.setFamilyName(certifiedField1); - user.setFiscalCode("Fiscal Code"); - user.setId("42"); - user.setName(certifiedField2); - user.setWorkContacts(new HashMap<>()); - when(userRegistryConnector.getUserByInternalIdWithFiscalCode( any())).thenReturn(user); - assertSame(user, userServiceImpl.retrieveUserFromUserRegistry("42")); - verify(userRegistryConnector).getUserByInternalIdWithFiscalCode( user.getId()); - } - - /** - * Method under test: {@link UserService#findAllByIds(List)} - */ - @Test - void testFindAllByIds() { - assertTrue(userServiceImpl.findAllByIds(new ArrayList<>()).isEmpty()); - } - @Test - void testFindAllExistingByIds_empty() { - assertTrue(userServiceImpl.findAllExistingByIds(new ArrayList<>()).isEmpty()); - } - @Test - void testFindAllExistingByIds_null() { - assertTrue(userServiceImpl.findAllExistingByIds(null).isEmpty()); - } - @Test - void testFindAllExistingByIds() { - List onboardedUserList = List.of(mockInstance(new OnboardedUser())); - when(userConnector.findAllByExistingIds(any())).thenReturn(onboardedUserList); - - List stringList = new ArrayList<>(); - stringList.add("foo"); - List actualFindAllByIdsResult = userServiceImpl.findAllExistingByIds(stringList); - assertSame(onboardedUserList, actualFindAllByIdsResult); - verify(userConnector).findAllByExistingIds(stringList); - } - - /** - * Method under test: {@link UserService#findAllByIds(List)} - */ - @Test - void testFindAllByIds2() { - ArrayList onboardedUserList = new ArrayList<>(); - when(userConnector.findAllByIds(any())).thenReturn(onboardedUserList); - - ArrayList stringList = new ArrayList<>(); - stringList.add("foo"); - List actualFindAllByIdsResult = userServiceImpl.findAllByIds(stringList); - assertSame(onboardedUserList, actualFindAllByIdsResult); - assertTrue(actualFindAllByIdsResult.isEmpty()); - verify(userConnector).findAllByIds(any()); - } - - @Test - void retrieveBindings_shouldReturnEmpty() { - ArrayList onboardedUserList = new ArrayList<>(); - when(userConnector.findWithFilter(any(), any(), any(), - any(), any(), any())).thenReturn(onboardedUserList); - - List actualRetrieveAdminUsersResult = userServiceImpl.retrieveBindings("42", "42", null, new ArrayList<>()); - assertTrue(actualRetrieveAdminUsersResult.isEmpty()); - } - - @Test - void retrieveBindings_shouldReturnData() { - String institutionId = "institutionId"; - OnboardedUser onboardedUser = dummyOnboardedUser("institutionId"); - when(userConnector.findWithFilter(any(), any(), any(), - any(), any(), any())).thenReturn(List.of(onboardedUser)); - - List actualRetrieveAdminUsersResult = userServiceImpl.retrieveBindings(onboardedUser.getId(), institutionId, null, new ArrayList<>()); - assertFalse(actualRetrieveAdminUsersResult.isEmpty()); - assertSame(onboardedUser.getBindings().get(0), actualRetrieveAdminUsersResult.get(0)); - } - - @Test - void retrieveBindings_shouldReturnDataFilteringOnStatus() { - //Given - RelationshipState filterStatus = RelationshipState.DELETED; - UserBinding userBindingDeleted = dummyUserBinding("institutionA"); - OnboardedProduct productDeleted = dummyOnboardedProduct(filterStatus); - userBindingDeleted.setProducts(List.of(productDeleted)); - - OnboardedUser expectedUser = new OnboardedUser(); - expectedUser.setId("id"); - expectedUser.setBindings(List.of(dummyUserBinding("institutionA"), userBindingDeleted)); - - when(userConnector.findWithFilter(anyString(), any(), any(), - any(), any(), any())).thenReturn(List.of(expectedUser)); - - //When - List actualRetrieveAdminUsersResult = userServiceImpl.retrieveBindings(expectedUser.getId(), - null, new String[]{filterStatus.name()}, new ArrayList<>()); - - //Then - assertFalse(actualRetrieveAdminUsersResult.isEmpty()); - assertEquals(1, actualRetrieveAdminUsersResult.size()); - UserBinding actualUserBinding = actualRetrieveAdminUsersResult.get(0); - assertEquals(userBindingDeleted.getInstitutionId(), actualUserBinding.getInstitutionId()); - - - - ArgumentCaptor> argumentCaptorStates = ArgumentCaptor.forClass(List.class); - verify(userConnector).findWithFilter(anyString(), any(), any(), argumentCaptorStates.capture(), any(), any()); - assertThat( argumentCaptorStates.getValue().get(0)).isEqualTo(filterStatus); - } - - private OnboardedProduct dummyOnboardedProduct(RelationshipState state) { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setProductId("productId"); - onboardedProduct.setProductRole("admin"); - onboardedProduct.setStatus(state); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setEnv(Env.PROD); - onboardedProduct.setContract("contract"); - onboardedProduct.setRelationshipId("setRelationshipId"); - onboardedProduct.setTokenId("setTokenId"); - return onboardedProduct; - } - - private UserBinding dummyUserBinding(String institutionId) { - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId(institutionId); - userBinding.setProducts(List.of(dummyOnboardedProduct(RelationshipState.ACTIVE))); - return userBinding; - } - - private OnboardedUser dummyOnboardedUser(String institutionId) { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setId("id"); - UserBinding userBinding = dummyUserBinding(institutionId); - onboardedUser.setBindings(List.of(userBinding)); - return onboardedUser; - } - - /** - * Method under test: {@link UserServiceImpl#checkIfInstitutionUser(String, String)} - */ - @Test - void testCheckIfAdmin() { - when(userConnector.findActiveInstitutionUser(any(), any() - )).thenReturn(new ArrayList<>()); - assertFalse(userServiceImpl.checkIfInstitutionUser("42", "42")); - verify(userConnector).findActiveInstitutionUser(any(), any() - ); - } - - /** - * Method under test: {@link UserServiceImpl#checkIfInstitutionUser(String, String)} - */ - @Test - void testCheckIfAdmin2() { - ArrayList onboardedUserList = new ArrayList<>(); - onboardedUserList.add(new OnboardedUser()); - when(userConnector.findActiveInstitutionUser(any(), any() - )).thenReturn(onboardedUserList); - assertTrue(userServiceImpl.checkIfInstitutionUser("42", "42")); - verify(userConnector).findActiveInstitutionUser(any(), any() - ); - } - - /** - * Method under test: {@link UserServiceImpl#checkIfInstitutionUser(String, String)} - */ - @Test - void testCheckIfAdmin3() { - when(userConnector.findActiveInstitutionUser(any(), any() - )).thenThrow(new ResourceNotFoundException("An error occurred", "Code")); - assertThrows(ResourceNotFoundException.class, () -> userServiceImpl.checkIfInstitutionUser("42", "42")); - verify(userConnector).findActiveInstitutionUser(any(), any() - ); - } - - /** - * Method under test: {@link UserServiceImpl#checkIfInstitutionUser(String, String)} - */ - @Test - void testCheckIfAdmin4() { - when(userConnector.findActiveInstitutionUser( any(), any() - )).thenReturn(new ArrayList<>()); - assertFalse(userServiceImpl.checkIfInstitutionUser("42", "42")); - verify(userConnector).findActiveInstitutionUser( any(), any() - ); - } - - /** - * Method under test: {@link UserServiceImpl#checkIfInstitutionUser(String, String)} - */ - @Test - void testCheckIfAdmin5() { - ArrayList onboardedUserList = new ArrayList<>(); - onboardedUserList.add(new OnboardedUser()); - when(userConnector.findActiveInstitutionUser( any(), any() - )).thenReturn(onboardedUserList); - assertTrue(userServiceImpl.checkIfInstitutionUser("42", "42")); - verify(userConnector).findActiveInstitutionUser( any(), any() - ); - } - - @Test - void findUserInstitutionAggregation() { - UserInstitutionAggregation userInstitutionAggregation = new UserInstitutionAggregation(); - userInstitutionAggregation.setId("id"); - when(userConnector.findUserInstitutionAggregation(any())).thenReturn(List.of(userInstitutionAggregation)); - UserInstitutionFilter filter = new UserInstitutionFilter(); - filter.setUserId("id"); - Assertions.assertDoesNotThrow(() -> userServiceImpl.findUserInstitutionAggregation(filter)); - } - - @Test - void updateUserStatus() { - - doNothing().when(userConnector).findAndUpdateStateWithOptionalFilter(anyString(),anyString(),anyString(), eq(null), anyString(), any()); - Assertions.assertDoesNotThrow(() -> userServiceImpl - .updateUserStatus("userId","institutionId","productId",null, "", RelationshipState.DELETED)); - } - - @Test - void retrievePersonOk(){ - OnboardedUser onboardedUser = new OnboardedUser(); - UserBinding binding = new UserBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("prod-pn"); - binding.setProducts(List.of(product)); - onboardedUser.setBindings(List.of(binding)); - when(userConnector.findById(any())).thenReturn(onboardedUser); - - User user = new User(); - user.setFiscalCode("taxCode"); - CertifiedField certName = new CertifiedField<>(); - certName.setValue("nome"); - user.setName(certName); - CertifiedField certSurname = new CertifiedField<>(); - certSurname.setValue("cognome"); - user.setFamilyName(certSurname); - CertifiedField certMail = new CertifiedField<>(); - certMail.setValue("mail@test.it"); - user.setEmail(certMail); - when(userRegistryConnector.getUserByInternalIdWithFiscalCode(any())).thenReturn(user); - Map map = new HashMap<>(); - WorkContact contact = new WorkContact(); - CertifiedField mail = new CertifiedField<>(); - mail.setValue("mail@test.it"); - contact.setEmail(mail); - map.put("id", contact); - user.setWorkContacts(map); - User response = userServiceImpl.retrievePerson("userId","prod-pn", "id"); - - Assertions.assertEquals("nome", response.getName()); - Assertions.assertEquals("cognome", response.getFamilyName()); - Assertions.assertEquals("mail@test.it", response.getEmail()); - Assertions.assertEquals("taxCode", response.getFiscalCode()); - } - - @Test - void retrievePersonOkWithoutProductFilter(){ - OnboardedUser onboardedUser = new OnboardedUser(); - UserBinding binding = new UserBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("prod-pn"); - binding.setProducts(List.of(product)); - onboardedUser.setBindings(List.of(binding)); - when(userConnector.findById(any())).thenReturn(onboardedUser); - - User user = new User(); - user.setFiscalCode("taxCode"); - CertifiedField certName = new CertifiedField<>(); - certName.setValue("nome"); - user.setName(certName); - CertifiedField certSurname = new CertifiedField<>(); - certSurname.setValue("cognome"); - user.setFamilyName(certSurname); - Map map = new HashMap<>(); - WorkContact contact = new WorkContact(); - CertifiedField mail = new CertifiedField<>(); - mail.setValue("mail@test.it"); - contact.setEmail(mail); - map.put("id", contact); - user.setWorkContacts(map); - when(userRegistryConnector.getUserByInternalIdWithFiscalCode(any())).thenReturn(user); - - User response = userServiceImpl.retrievePerson("userId",null, null); - - Assertions.assertEquals("nome", response.getName()); - Assertions.assertEquals("cognome", response.getFamilyName()); - Assertions.assertEquals("taxCode", response.getFiscalCode()); - } - - @Test - void retrievePersonProductNotFound(){ - OnboardedUser onboardedUser = new OnboardedUser(); - UserBinding binding = new UserBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("prod-pn"); - binding.setProducts(List.of(product)); - onboardedUser.setBindings(List.of(binding)); - when(userConnector.findById(any())).thenReturn(onboardedUser); - Assertions.assertThrows(ResourceNotFoundException.class, - () -> userServiceImpl.retrievePerson("userId","prod-io", null)); - } - - @Test - void retrievePersonNotFound(){ - OnboardedUser onboardedUser = new OnboardedUser(); - UserBinding binding = new UserBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("prod-pn"); - binding.setProducts(List.of(product)); - onboardedUser.setBindings(List.of(binding)); - when(userConnector.findById(any())).thenThrow(ResourceNotFoundException.class); - - Assertions.assertThrows(ResourceNotFoundException.class, - () -> userServiceImpl.retrievePerson("userId","prod-io", "id")); - } - - @Test - void retrieveUsersFromRegistry() { - User user = new User(); - user.setId("fiscalCode"); - when(userRegistryConnector.getUserByFiscalCode(any())).thenReturn(user); - Assertions.assertDoesNotThrow(() -> userServiceImpl.retrieveUserFromUserRegistryByFiscalCode("fiscalCode")); - assertEquals("fiscalCode", user.getId()); - } - - @Test - void persistUsersFromRegistry() { - User user = new User(); - user.setId("fiscalCode"); - when(userRegistryConnector.persistUserUsingPatch(any(), any(), any(), any(), any())).thenReturn(user); - Assertions.assertDoesNotThrow(() -> userServiceImpl.persistUserRegistry("name", "familyName", "fiscalCode", "email", "institutionId")); - } - - @Test - void persistWorksContractToUserRegistry() { - User user = new User(); - user.setId("fiscalCode"); - when(userRegistryConnector.persistUserWorksContractUsingPatch("fiscalCode", "email", "institutionId")).thenReturn(user); - Assertions.assertDoesNotThrow(() -> userServiceImpl.persistWorksContractToUserRegistry( "fiscalCode", "email", "institutionId")); - } - - @Test - void getUserInfo() { - UserInstitutionAggregation userInstitution = new UserInstitutionAggregation(); - userInstitution.setId("userId"); - UserInstitutionBinding binding = new UserInstitutionBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("prod-pn"); - binding.setProducts(product); - userInstitution.setBindings(binding); - Institution institution = new Institution(); - institution.setId("id"); - userInstitution.setInstitutions(List.of(institution)); - when(userConnector.getUserInfo(any(), any(), any())).thenReturn(List.of(userInstitution)); - List response = userServiceImpl.getUserInfo("userId",null, null); - assertNotNull(response); - assertFalse(response.isEmpty()); - assertEquals(1, response.size()); - assertEquals("userId", response.get(0).getUserId()); - assertNotNull(response.get(0).getBinding()); - assertEquals("prod-pn", response.get(0).getBinding().getProducts().getProductId()); - } - - /** - * Method under test: {@link UserServiceImpl#findAll(Optional, Optional, String)} - */ - @Test - void findAllUsers() { - OnboardedUser user = new OnboardedUser(); - user.setId("userId"); - UserBinding binding = new UserBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("prod-pn"); - product.setStatus(RelationshipState.ACTIVE); - binding.setProducts(List.of(product)); - binding.setInstitutionId("institutionId"); - user.setBindings(List.of(binding)); - when(userConnector.findAllValidUsers(any(), any(), any())).thenReturn(List.of(user)); - User pdvUser = new User(); - pdvUser.setId("userId"); - pdvUser.setWorkContacts(Map.of("institutionId", new WorkContact())); - when(userRegistryConnector.getUserByInternalId("userId")).thenReturn(pdvUser); - List response = userServiceImpl.findAll(Optional.empty(),Optional.empty(), "prod-pn"); - assertNotNull(response); - assertFalse(response.isEmpty()); - assertEquals(1, response.size()); - assertNotNull(response.get(0)); - assertNotNull(response.get(0).getUser()); - assertEquals("userId", response.get(0).getUser().getUserId()); - assertEquals("institutionId", response.get(0).getInstitutionId()); - assertEquals("prod-pn", response.get(0).getProductId()); - } - - /** - * Method under test: {@link UserServiceImpl#findAll(Optional, Optional, String)} - */ - @Test - void findNoUsers() { - OnboardedUser user = new OnboardedUser(); - user.setId("userId"); - UserBinding binding = new UserBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("prod-pn"); - product.setStatus(RelationshipState.PENDING); - binding.setProducts(List.of(product)); - binding.setInstitutionId("institutionId"); - user.setBindings(List.of(binding)); - when(userConnector.findAllValidUsers(any(), any(), any())).thenReturn(List.of(user)); - User pdvUser = new User(); - pdvUser.setId("userId"); - pdvUser.setWorkContacts(Map.of("institutionId", new WorkContact())); - when(userRegistryConnector.getUserByInternalId("userId")).thenReturn(pdvUser); - List response = userServiceImpl.findAll(Optional.empty(),Optional.empty(), "prod-pn"); - assertNotNull(response); - assertTrue(response.isEmpty()); - } -} - diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/ExternalController.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/ExternalController.java index e9d2d87e7..b3c5edc74 100644 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/ExternalController.java +++ b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/ExternalController.java @@ -8,8 +8,10 @@ import it.pagopa.selfcare.mscore.model.institution.GeographicTaxonomies; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.user.ProductManagerInfo; -import it.pagopa.selfcare.mscore.web.model.institution.*; +import it.pagopa.selfcare.mscore.web.model.institution.CreatePnPgInstitutionRequest; +import it.pagopa.selfcare.mscore.web.model.institution.InstitutionBillingResponse; +import it.pagopa.selfcare.mscore.web.model.institution.InstitutionPnPgResponse; +import it.pagopa.selfcare.mscore.web.model.institution.InstitutionResponse; import it.pagopa.selfcare.mscore.web.model.mapper.InstitutionMapperCustom; import it.pagopa.selfcare.mscore.web.model.mapper.InstitutionResourceMapper; import it.pagopa.selfcare.mscore.web.model.onboarding.OnboardedProducts; @@ -61,30 +63,6 @@ public ResponseEntity getByExternalId(@ApiParam("${swagger. } - /** - * The function returns Manager institution Data from its externalId - * - * @param externalId String - * @param productId String - * - * @return InstitutionManagerResponse - * * Code: 200, Message: successful operation, DataType: InstitutionManagerResponse - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Institution Manager not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.external.institution.manager}", notes = "${swagger.mscore.external.institution.manager}") - @GetMapping(value = "/{externalId}/products/{productId}/manager", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getManagerInstitutionByExternalId(@ApiParam("${swagger.mscore.institutions.model.externalId}") - @PathVariable("externalId") String externalId, - @ApiParam("${swagger.mscore.institutions.model.productId}") - @PathVariable("productId") String productId) { - CustomExceptionMessage.setCustomMessage(INSTITUTION_MANAGER_ERROR); - ProductManagerInfo manager = externalService.retrieveInstitutionManager(externalId, productId); - return ResponseEntity.ok(InstitutionMapperCustom.toInstitutionManagerResponse(manager, productId)); - } - - /** * The function returns billing institution Data from its externalId * diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java index 77f043e7e..2f8e55c24 100644 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java +++ b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java @@ -12,7 +12,6 @@ import it.pagopa.selfcare.mscore.core.InstitutionService; import it.pagopa.selfcare.mscore.core.OnboardingService; import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.user.UserInfo; import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import it.pagopa.selfcare.mscore.web.model.institution.*; import it.pagopa.selfcare.mscore.web.model.mapper.*; @@ -519,23 +518,4 @@ public Collection getInstitutionBrokers(@ApiParam("${swagger.msc return result; } - @Tags({@Tag(name = "support"), @Tag(name = "Institution")}) - @GetMapping(value = "/{institutionId}/users", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "", notes = "${swagger.mscore.institutions.api.getInstitutionUsers}") - public List getInstitutionUsers(@ApiParam("${swagger.mscore.institutions.model.id}") - @PathVariable("institutionId") - String institutionId) { - - log.trace("getInstitutionUsers start"); - log.debug("getInstitutionUsers institutionId = {}, role = {}", institutionId); - List userInfos = institutionService.getInstitutionUsers(institutionId); - List result = userInfos.stream() - .map(userInfo -> userMapper.toUserInfoResponse(userInfo, institutionId)) - .collect(Collectors.toList()); - log.debug("getInstitutionUsers result = {}", result); - log.trace("getInstitutionUsers end"); - - return result; - } } diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/OnboardingController.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/OnboardingController.java index f46094ebf..f1ff8e201 100644 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/OnboardingController.java +++ b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/OnboardingController.java @@ -3,27 +3,15 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -import it.pagopa.selfcare.commons.base.security.SelfCareUser; import it.pagopa.selfcare.mscore.constant.GenericError; import it.pagopa.selfcare.mscore.core.OnboardingService; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardingInfo; -import it.pagopa.selfcare.mscore.model.onboarding.ResourceResponse; import it.pagopa.selfcare.mscore.model.onboarding.VerifyOnboardingFilters; -import it.pagopa.selfcare.mscore.web.model.mapper.OnboardingMapper; -import it.pagopa.selfcare.mscore.web.model.onboarding.OnboardingInfoResponse; import it.pagopa.selfcare.mscore.web.util.CustomExceptionMessage; import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; -import java.util.List; - -import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; - @Slf4j @RestController @RequestMapping(value = "/onboarding") @@ -104,58 +92,4 @@ public ResponseEntity verifyOnboardingInfoByFilters(@ApiParam("${swagger.m return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } - /** - * The function return onboardingInfo - * - * @param institutionId String - * @param institutionExternalId String - * @param states String[] - * @return onboardingInfoResponse - *

- * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.onboarding.info}", notes = "${swagger.mscore.onboarding.info}") - @GetMapping(value = "/info", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity onboardingInfo(@ApiParam("${swagger.mscore.institutions.model.institutionId}") - @RequestParam(value = "institutionId", required = false) String institutionId, - @ApiParam("${swagger.mscore.institutions.model.externalId}") - @RequestParam(value = "institutionExternalId", required = false) String institutionExternalId, - @ApiParam("${swagger.mscore.institutions.model.relationshipState}") - @RequestParam(value = "states", required = false) String[] states, - Authentication authentication) { - CustomExceptionMessage.setCustomMessage(GenericError.GETTING_ONBOARDING_INFO_ERROR); - String userId = ((SelfCareUser) authentication.getPrincipal()).getId(); - List onboardingInfoList = onboardingService.getOnboardingInfo(institutionId, institutionExternalId, states, userId); - OnboardingInfoResponse onboardingInfoResponse = OnboardingMapper.toOnboardingInfoResponse(userId, onboardingInfoList); - log.debug("onboardingInfo result = {}", onboardingInfoResponse); - return ResponseEntity.ok().body(onboardingInfoResponse); - } - - /** - * The function retrieve the document of specific onboarding - * - * @param relationshipId String - * @return no content - * * Code: 200, Message: successful operation, DataType: Resource (signed onboarding document) - * * Code: 404, Message: Document Not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.onboarding.relationship.document}", notes = "${swagger.mscore.onboarding.relationship.document}") - @GetMapping(value = "/relationship/{relationshipId}/document", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getOnboardingDocument(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("relationshipId") String relationshipId) { - CustomExceptionMessage.setCustomMessage(GenericError.GETTING_ONBOARDING_INFO_ERROR); - ResourceResponse file = onboardingService.retrieveDocument(relationshipId); - var headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE); - headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFileName()); - log.info("contentType: {}", headers.getContentType()); - if (file.getData() != null) { - log.info("byteArray size: {}", file.getData().length); - } - return ResponseEntity.ok().headers(headers).body(file.getData()); - } } diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/UserController.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/UserController.java deleted file mode 100644 index 776b9ce26..000000000 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/UserController.java +++ /dev/null @@ -1,380 +0,0 @@ -package it.pagopa.selfcare.mscore.web.controller; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.tags.Tags; -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.commons.base.security.SelfCareUser; -import it.pagopa.selfcare.mscore.constant.GenericError; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.UserEventService; -import it.pagopa.selfcare.mscore.core.UserRelationshipService; -import it.pagopa.selfcare.mscore.core.UserService; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardingInfo; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.mscore.web.model.institution.RelationshipResult; -import it.pagopa.selfcare.mscore.web.model.mapper.OnboardingMapper; -import it.pagopa.selfcare.mscore.web.model.mapper.RelationshipMapper; -import it.pagopa.selfcare.mscore.web.model.mapper.UserMapper; -import it.pagopa.selfcare.mscore.web.model.onboarding.OnboardingInfoResponse; -import it.pagopa.selfcare.mscore.web.model.user.*; -import it.pagopa.selfcare.mscore.web.util.CustomExceptionMessage; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.web.bind.annotation.*; - -import java.util.*; -import java.util.stream.Collectors; - -import static it.pagopa.selfcare.mscore.constant.GenericError.*; - -@Slf4j -@RestController -@Api(tags = "Persons") -public class UserController { - - private final UserRelationshipService userRelationshipService; - private final UserService userService; - private final UserEventService userEventService; - private final UserMapper userMapper; - - public UserController(UserRelationshipService userRelationshipService, - UserService userService, - UserEventService userEventService, - UserMapper userMapper) { - this.userRelationshipService = userRelationshipService; - this.userService = userService; - this.userEventService = userEventService; - this.userMapper = userMapper; - } - - /** - * The function activate a suspended relationship - * - * @param relationshipId relationshipId - * @return no content - * * Code: 204 - * * Code: 400, Message: Invalid starter token status, DataType: Problem - * * Code: 404, Message: Token not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.NO_CONTENT) - @ApiOperation(value = "${swagger.mscore.relationship.activate}", notes = "${swagger.mscore.relationship.activate}") - @PostMapping(value = "/relationships/{relationshipId}/activate", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity activateRelationship(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("relationshipId") String relationshipId, - Authentication authentication) { - log.info("Activating relationship {}", relationshipId); - CustomExceptionMessage.setCustomMessage(ACTIVATE_RELATIONSHIP_ERROR); - SelfCareUser selfCareUser = (SelfCareUser) authentication.getPrincipal(); - userRelationshipService.activateRelationship(relationshipId, selfCareUser.getUserName(), selfCareUser.getSurname()); - return ResponseEntity.noContent().build(); - } - - /** - * The function suspend an active relationship - * - * @param relationshipId tokenId - * @return no content - * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid starter token status, DataType: Problem - * * Code: 404, Message: Token not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.NO_CONTENT) - @ApiOperation(value = "${swagger.mscore.relationship.suspend}", notes = "${swagger.mscore.relationship.suspend}") - @PostMapping(value = "/relationships/{relationshipId}/suspend", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity suspendRelationship(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("relationshipId") String relationshipId, - Authentication authentication) { - log.info("Suspending relationship {}", relationshipId); - CustomExceptionMessage.setCustomMessage(SUSPEND_RELATIONSHIP_ERROR); - SelfCareUser selfCareUser = (SelfCareUser) authentication.getPrincipal(); - userRelationshipService.suspendRelationship(relationshipId, selfCareUser.getUserName(), selfCareUser.getSurname()); - return ResponseEntity.noContent().build(); - } - - /** - * The function deleted the corresponding relationship - * - * @param relationshipId relationshipId - * @return RelationshipResponse - * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid starter token status, DataType: Problem - * * Code: 404, Message: Token not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.NO_CONTENT) - @ApiOperation(value = "${swagger.mscore.relationship.delete}", notes = "${swagger.mscore.relationship.delete}") - @DeleteMapping(value = "/relationships/{relationshipId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteRelationship(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("relationshipId") String relationshipId, - Authentication authentication) { - log.info("Getting relationship {}", relationshipId); - CustomExceptionMessage.setCustomMessage(GET_RELATIONSHIP_ERROR); - SelfCareUser selfCareUser = (SelfCareUser) authentication.getPrincipal(); - userRelationshipService.deleteRelationship(relationshipId, selfCareUser.getUserName(), selfCareUser.getSurname()); - return ResponseEntity.noContent().build(); - } - - /** - * The function Gets the corresponding relationship - * - * @param relationshipId relationshipId - * @return RelationshipResponse - * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid starter token status, DataType: Problem - * * Code: 404, Messa - */ - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.relationships}", notes = "${swagger.mscore.relationships}") - @GetMapping(value = "/relationships/{relationshipId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getRelationship(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("relationshipId") String relationshipId) { - log.info("Getting relationship {}", relationshipId); - CustomExceptionMessage.setCustomMessage(GET_RELATIONSHIP_ERROR); - RelationshipInfo relationship = userRelationshipService.retrieveRelationship(relationshipId); - return ResponseEntity.ok().body(RelationshipMapper.toRelationshipResult(relationship)); - } - - /** - * The function return onboardingInfo - * - * @param userId String - * @param institutionId String - * @return onboardingInfoResponse - *

- * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.onboarding.info}", notes = "${swagger.mscore.onboarding.info}") - @GetMapping(value = "/users/{userId}/institution-products", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getInstitutionProductsInfo(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("userId") String userId, - @ApiParam("${swagger.mscore.institutions.model.institutionId}") - @RequestParam(value = "institutionId", required = false) String institutionId, - @ApiParam("${swagger.mscore.institutions.model.relationshipState}") - @RequestParam(value = "states", required = false) String[] states) { - CustomExceptionMessage.setCustomMessage(GenericError.GETTING_ONBOARDING_INFO_ERROR); - List onboardingInfoList = userService.getUserInfo(userId, institutionId, states); - OnboardingInfoResponse onboardingInfoResponse = OnboardingMapper.toUserInfoResponse(userId, onboardingInfoList); - log.debug("getInstitutionProductsInfo result = {}", onboardingInfoResponse); - return ResponseEntity.ok().body(onboardingInfoResponse); - } - - /** - * The function retrieves products info and role which the user is enabled - * - * @param userId String - * @param institutionId String - * @return onboardingInfoResponse - *

- * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.users.products}", notes = "${swagger.mscore.users.products}") - @GetMapping(value = "/users/{userId}/products", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getUserProductsInfo(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("userId") String userId, - @ApiParam("${swagger.mscore.institutions.model.institutionId}") - @RequestParam(value = "institutionId", required = false) String institutionId, - @ApiParam("${swagger.mscore.institutions.model.relationshipState}") - @RequestParam(value = "states", required = false) String[] states) { - - List userBindings = userService.retrieveBindings(institutionId, userId, states, null); - if (Objects.isNull(userBindings) || userBindings.isEmpty()) - return ResponseEntity.notFound().build(); - - return ResponseEntity.ok().body(UserProductsResponse.builder() - .id(userId) - .bindings(userBindings.stream() - .map(userMapper::toInstitutionProducts) - .collect(Collectors.toList())) - .build()); - } - - - /** - * The function delete logically the association institution and product - * - * @param userId String - * @param institutionId String - * @param productId String - * @return onboardingInfoResponse - *

- * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.users.delete.products}", notes = "${swagger.mscore.users.delete.products}") - @DeleteMapping(value = "/users/{userId}/institutions/{institutionId}/products/{productId}") - public ResponseEntity deleteProducts(@ApiParam("${swagger.mscore.relationship.relationshipId}") - @PathVariable("userId") String userId, - @ApiParam("${swagger.mscore.institutions.model.institutionId}") - @PathVariable(value = "institutionId") String institutionId, - @ApiParam("${swagger.mscore.institutions.model.productId}") - @PathVariable(value = "productId") String productId) { - - userService.updateUserStatus(userId, institutionId, productId, null, null, RelationshipState.DELETED); - return ResponseEntity.ok().build(); - } - - /** - * The function retrieves userInfo given UserId and optional productId - * - * @param userId String - * @param productId String - * @param institutionId String - * @return onboardingInfoResponse - *

- * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Not found, DataType: Problem - */ - @Tags({@Tag(name = "support"), @Tag(name = "external-v2"), @Tag(name = "Persons")}) - @ResponseStatus(HttpStatus.OK) - @ApiOperation(value = "${swagger.mscore.users}", notes = "${swagger.mscore.users}") - @GetMapping(value = "/users/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getUserInfo(@ApiParam("${swagger.mscore.users.userId}") - @PathVariable("id") String userId, - @ApiParam("${swagger.mscore.institutions.model.productId}") - @RequestParam(value = "productId", required = false) String productId, - @ApiParam("${swagger.mscore.institutions.model.institutionId}") - @RequestParam(value = "institutionId", required = false) String institutionId) { - - User user = userService.retrievePerson(userId, productId, institutionId); - return ResponseEntity.ok().body(userMapper.toUserResponse(user, institutionId)); - } - - /** - * The function sends a notification to DL when a user's information are updated - * - * @param userId String - * @param institutionId String - * @return onboardingInfoResponse - *

- * * Code: 200, Message: successful operation, DataType: TokenId - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Not found, DataType: Problem - */ - @ResponseStatus(HttpStatus.NO_CONTENT) - @ApiOperation(value = "${swagger.mscore.api.users.updateUser}", notes = "${swagger.mscore.api.users.updateUser}") - @PostMapping(value = "/users/{id}/update", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateUser(@ApiParam("${swagger.mscore.users.userId}") - @PathVariable("id") String userId, - @ApiParam("${swagger.mscore.institutions.model.institutionId}") - @RequestParam(value = "institutionId") String institutionId) { - userEventService.sendUserNotificationToQueue(userId, institutionId, QueueEvent.UPDATE); - return ResponseEntity.noContent().build(); - } - - /** - * The function return onboardingInfo - * - * @param size Integer - * @param page Integer - * @param productId String - * @return {@link UsersNotificationResponse} - *

- * * Code: 200, Message: successful operation - * * Code: 400, Message: Invalid ID supplied, DataType: Problem - * * Code: 404, Message: Not found, DataType: Problem - */ - @ApiOperation(value = "", notes = "${swagger.mscore.api.users.findAll}") - @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - public ResponseEntity getUsers(@RequestParam(name = "size", required = false, defaultValue = "100") Optional size, - @RequestParam(name = "page", required = false, defaultValue = "0") Optional page, - @RequestParam(name = "productId", required = false) String productId) { - List users = userService.findAll(size, page, productId); - UsersNotificationResponse userNotificationResponse = new UsersNotificationResponse(); - List usersNotification = users.stream() - .map(userMapper::toUserNotification) - .toList(); - - Map> userNotificationMap = new HashMap<>(); - - for (UserNotificationResponse userNotification : usersNotification) { - if (userNotificationMap.containsKey(userNotification.getUser().getUserId())) { - userNotificationMap.get(userNotification.getUser().getUserId()).add(userNotification); - } else { - List usersNotificationResponse = new ArrayList<>(); - usersNotificationResponse.add(userNotification); - userNotificationMap.put(userNotification.getUser().getUserId(), usersNotificationResponse); - } - } - - userNotificationResponse.setUsers(userNotificationMap.values().stream() - .map(UserNotificationBindingsResponse::new) - .toList()); - - return ResponseEntity.ok(userNotificationResponse); - } - - /** - * Update user status and send notification to DL. - * - * @param userId User's unique identifier. - * @param institutionId User's institution identifier. - * @param productId User's product identifier. - * @param role User's role. - * @param productRole Product's role. - * @param status User's status. - * @return ResponseEntity - *

- * * Code: 204, Message: Update successful, DataType: No Content - * * Code: 400, Message: Bad Request, DataType: Problem - * * Code: 404, Message: Not Found, DataType: Problem - */ - @Tag(name = "support") - @ResponseStatus(HttpStatus.NO_CONTENT) - @ApiOperation(value = "${swagger.mscore.api.users.updateUserStatus}", notes = "${swagger.mscore.api.users.updateUserStatus}") - @PutMapping(value = "/users/{id}/status", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateUserStatus(@ApiParam(value = "${swagger.mscore.users.userId}", required = true) @PathVariable(value = "id") String userId, - @ApiParam(value = "${swagger.mscore.institutions.model.institutionId}") @RequestParam(value = "institutionId", required = false) String institutionId, - @ApiParam(value = "${swagger.mscore.institutions.model.productId}") @RequestParam(value = "productId", required = false) String productId, - @RequestParam(value = "role", required = false) PartyRole role, - @RequestParam(value = "productRole", required = false) String productRole, - @ApiParam(required = true) @RequestParam(value = "status") RelationshipState status) { - log.debug("updateProductStatus - userId: {}", userId); - userService.updateUserStatus(userId, institutionId, productId, role, productRole, status); - return ResponseEntity.noContent().build(); - } - - /** - * Get onboarded users from identifiers in input. - * - * @param userIds Users identifiers. - * @return ResponseEntity - *

- * * Code: 204, Message: Update successful, DataType: No Content - * * Code: 400, Message: Bad Request, DataType: Problem - * * Code: 404, Message: Not Found, DataType: Problem - */ - @ResponseStatus(HttpStatus.NO_CONTENT) - @ApiOperation(value = "${swagger.mscore.api.users.getOnboardedUsers}", notes = "${swagger.mscore.api.users.getOnboardedUsers}") - @GetMapping(value = "/onboarded-users", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getOnboardedUsers(@ApiParam(value = "${swagger.mscore.users.userIds}", required = true) - @RequestParam(value = "ids") List userIds) { - log.debug("getOnboardedUsers - userIds: {}", userIds); - final List onboardedUsers = userService.findAllByIds(userIds); - OnboardedUsersResponse response = OnboardedUsersResponse.builder() - .users(onboardedUsers.stream() - .map(userMapper::toOnboardedUserResponse) - .toList()) - .build(); - return ResponseEntity.ok(response); - } -} diff --git a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/ExternalControllerTest.java b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/ExternalControllerTest.java index 83edc86f5..ddfadd13f 100644 --- a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/ExternalControllerTest.java +++ b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/ExternalControllerTest.java @@ -5,8 +5,6 @@ import it.pagopa.selfcare.mscore.constant.RelationshipState; import it.pagopa.selfcare.mscore.core.ExternalService; import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.user.ProductManagerInfo; -import it.pagopa.selfcare.mscore.web.TestUtils; import it.pagopa.selfcare.mscore.web.model.institution.CreatePnPgInstitutionRequest; import it.pagopa.selfcare.mscore.web.model.mapper.InstitutionResourceMapper; import it.pagopa.selfcare.mscore.web.model.mapper.InstitutionResourceMapperImpl; @@ -428,137 +426,6 @@ void testGetByExternalId7() throws Exception { } - /** - * Method under test: {@link ExternalController#getManagerInstitutionByExternalId(String, String)} - */ - @Test - void testGetManagerInstitutionByExternalId2() throws Exception { - Billing billing = new Billing(); - billing.setPublicServices(true); - billing.setRecipientCode("?"); - billing.setVatNumber("42"); - - Premium premium = new Premium(); - premium.setContract("?"); - premium.setStatus(RelationshipState.PENDING); - - Onboarding onboarding = new Onboarding(); - onboarding.setBilling(billing); - onboarding.setContract("?"); - onboarding.setCreatedAt(null); - onboarding.setPricingPlan("?"); - onboarding.setProductId("42"); - onboarding.setStatus(RelationshipState.PENDING); - onboarding.setUpdatedAt(null); - - ArrayList onboardingList = new ArrayList<>(); - onboardingList.add(onboarding); - - Institution institution = new Institution(); - institution.setOnboarding(onboardingList); - - ProductManagerInfo productManagerInfo = new ProductManagerInfo(); - productManagerInfo.setProducts(new ArrayList<>()); - productManagerInfo.setInstitution(institution); - when(externalService.retrieveInstitutionManager(any(), any())).thenReturn(productManagerInfo); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/external/institutions/{externalId}/products/{productId}/manager", "42", "42"); - MockMvcBuilders.standaloneSetup(externalController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json")); - } - - /** - * Method under test: {@link ExternalController#getManagerInstitutionByExternalId(String, String)} - */ - @Test - void testGetManagerInstitutionByExternalId3() throws Exception { - Billing billing = new Billing(); - billing.setPublicServices(true); - billing.setRecipientCode("?"); - billing.setVatNumber("42"); - - Premium premium = new Premium(); - premium.setContract("?"); - premium.setStatus(RelationshipState.PENDING); - - Onboarding onboarding = new Onboarding(); - onboarding.setBilling(billing); - onboarding.setContract("?"); - onboarding.setCreatedAt(null); - onboarding.setPricingPlan("?"); - onboarding.setProductId("42"); - onboarding.setStatus(RelationshipState.PENDING); - onboarding.setUpdatedAt(null); - - ArrayList onboardingList = new ArrayList<>(); - onboardingList.add(onboarding); - - Institution institution = TestUtils.createSimpleInstitutionPA(); - institution.setId("?"); - institution.setOnboarding(onboardingList); - - ProductManagerInfo productManagerInfo = new ProductManagerInfo(); - productManagerInfo.setProducts(new ArrayList<>()); - productManagerInfo.setUserId("?"); - productManagerInfo.setInstitution(institution); - when(externalService.retrieveInstitutionManager(any(), any())).thenReturn(productManagerInfo); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/external/institutions/{externalId}/products/{productId}/manager", "42", "42"); - MockMvcBuilders.standaloneSetup(externalController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json")); - } - - /** - * Method under test: {@link ExternalController#getManagerInstitutionByExternalId(String, String)} - */ - @Test - void testGetManagerInstitutionByExternalId4() throws Exception { - Billing billing = new Billing(); - billing.setPublicServices(true); - billing.setRecipientCode("?"); - billing.setVatNumber("42"); - - Onboarding onboarding = new Onboarding(); - onboarding.setBilling(billing); - onboarding.setClosedAt(null); - onboarding.setContract("?"); - onboarding.setCreatedAt(null); - onboarding.setPricingPlan("?"); - onboarding.setProductId("42"); - onboarding.setStatus(RelationshipState.PENDING); - onboarding.setTokenId("42"); - onboarding.setUpdatedAt(null); - - ArrayList onboardingList = new ArrayList<>(); - onboardingList.add(onboarding); - - Institution institution = new Institution(); - institution.setOnboarding(onboardingList); - - ProductManagerInfo productManagerInfo = new ProductManagerInfo(); - productManagerInfo.setProducts(new ArrayList<>()); - productManagerInfo.setInstitution(institution); - when(externalService.retrieveInstitutionManager(any(), any())).thenReturn(productManagerInfo); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/external/institutions/{externalId}/products/{productId}/manager", "42", "42"); - MockMvcBuilders.standaloneSetup(externalController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json")) - .andExpect(MockMvcResultMatchers.content() - .string( - "{\"id\":null,\"from\":null,\"to\":null,\"role\":null,\"product\":null,\"state\":null,\"pricingPlan\":\"?\",\"institutionUpdate" - + "\":{\"imported\":false},\"billing\":{\"vatNumber\":\"42\",\"recipientCode\":\"?\",\"publicServices\":true" - + "},\"createdAt\":null,\"updatedAt\":null}")); - } - /** * Method under test: {@link ExternalController#retrieveInstitutionByIds(List)} diff --git a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java index dd6524b0b..d6da3c56f 100644 --- a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java +++ b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java @@ -10,8 +10,6 @@ import it.pagopa.selfcare.mscore.core.OnboardingService; import it.pagopa.selfcare.mscore.core.util.InstitutionPaSubunitType; import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserInfo; import it.pagopa.selfcare.mscore.web.TestUtils; import it.pagopa.selfcare.mscore.web.model.institution.*; import it.pagopa.selfcare.mscore.web.model.mapper.*; @@ -40,7 +38,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -1257,45 +1254,6 @@ void findFromProduct() throws Exception { verifyNoMoreInteractions(institutionService); } - /** - * Method under test: {@link InstitutionController#getInstitutionUsers(String)} - */ - @Test - void getInstitutionUsers() throws Exception { - // Given - final String institutionId = "test"; - - UserInfo userInfo = new UserInfo(); - userInfo.setId("userId"); - User user = new User(); - user.setWorkContacts(Map.of("test", new WorkContact())); - userInfo.setUser(user); - // When - when(institutionService.getInstitutionUsers(any())).thenReturn(List.of(userInfo)); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(BASE_URL + "/{institutionId}/users", institutionId); - ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(institutionController) - .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()) - .build() - .perform(requestBuilder); - MvcResult result = actualPerformResult - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json")) - .andReturn(); - - List response = objectMapper.readValue( - result.getResponse().getContentAsString(), - new TypeReference<>() { - }); - - // Then - assertNotNull(response); - assertNotNull(response.get(0)); - assertEquals(response.get(0).getId(), userInfo.getId()); - verify(institutionService, times(1)) - .getInstitutionUsers(institutionId); - verifyNoMoreInteractions(institutionService); - } - /** * Method under test: {@link InstitutionController#getInstitutionBrokers(String, InstitutionType)} */ diff --git a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/OnboardingControllerTest.java b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/OnboardingControllerTest.java index cef8b91e2..16758446d 100644 --- a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/OnboardingControllerTest.java +++ b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/OnboardingControllerTest.java @@ -1,20 +1,12 @@ package it.pagopa.selfcare.mscore.web.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import it.pagopa.selfcare.commons.base.security.SelfCareUser; import it.pagopa.selfcare.mscore.core.OnboardingService; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.onboarding.ResourceResponse; -import it.pagopa.selfcare.mscore.web.model.mapper.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.http.MediaType; -import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.web.servlet.ResultActions; @@ -24,10 +16,8 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.request.RequestContextHolder; -import java.nio.charset.StandardCharsets; - import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doNothing; @ContextConfiguration(classes = {OnboardingController.class}) @ExtendWith(MockitoExtension.class) @@ -38,64 +28,12 @@ class OnboardingControllerTest { @Mock private OnboardingService onboardingService; - @Spy - @InjectMocks - OnboardingResourceMapper onboardingResourceMapper = new OnboardingResourceMapperImpl(); - - @Spy - InstitutionUpdateMapper institutionUpdateMapper = new InstitutionUpdateMapperImpl(); - - @Spy - InstitutionResourceMapper institutionResourceMapper = new InstitutionResourceMapperImpl(); - - ObjectMapper objectMapper = new ObjectMapper(); - @BeforeEach void resetContext() { SecurityContextHolder.clearContext(); RequestContextHolder.resetRequestAttributes(); } - /** - * Method under test: {@link OnboardingController#getOnboardingDocument(String)} - */ - @Test - void testGetOnboardingDocument() throws Exception { - ResourceResponse resourceResponse = new ResourceResponse(); - resourceResponse.setData("AXAXAXAX".getBytes(StandardCharsets.UTF_8)); - resourceResponse.setFileName("foo.txt"); - resourceResponse.setMimetype("Mimetype"); - when(onboardingService.retrieveDocument(org.mockito.Mockito.any())).thenReturn(resourceResponse); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/onboarding/relationship/{relationshipId}/document", "42"); - MockMvcBuilders.standaloneSetup(onboardingController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/octet-stream")) - .andExpect(MockMvcResultMatchers.content().string("AXAXAXAX")); - } - - /** - * Method under test: {@link OnboardingController#getOnboardingDocument(String)} - */ - @Test - void testGetOnboardingDocument2() throws Exception { - ResourceResponse resourceResponse = new ResourceResponse(); - resourceResponse.setData(null); - resourceResponse.setFileName("foo.txt"); - resourceResponse.setMimetype("Mimetype"); - when(onboardingService.retrieveDocument(org.mockito.Mockito.any())).thenReturn(resourceResponse); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/onboarding/relationship/{relationshipId}/document", "42"); - MockMvcBuilders.standaloneSetup(onboardingController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/octet-stream")) - .andExpect(MockMvcResultMatchers.content().string("")); - } - /** * Method under test: {@link OnboardingController#verifyOnboardingInfo(String, String, String)} */ @@ -143,41 +81,5 @@ void shouldVerifyOnboardingInfoByExternalId() throws Exception { actualPerformResult.andExpect(MockMvcResultMatchers.status().isNoContent()); } - - - /** - * Method under test: {@link OnboardingController#verifyOnboardingInfo(String, String)} - */ - //@Test - void shouldNotFoundVerifyOnboardingInfoByExternalId() throws Exception { - doThrow(new ResourceNotFoundException("","")).when(onboardingService).verifyOnboardingInfo(any(), any()); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .head("/onboarding/institution/{externalId}/products/{productId}", "42", "42"); - ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(onboardingController) - .build() - .perform(requestBuilder); - actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); - } - - /** - * Method under test: {@link OnboardingController#onboardingInfo(String, String, String[], Authentication)} - */ - @Test - void testOnboardingInfo() throws Exception { - - Authentication authentication = mock(Authentication.class); - when(authentication.getPrincipal()).thenReturn(SelfCareUser.builder("id").build()); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/onboarding/info") - .principal(authentication) - .contentType(MediaType.APPLICATION_JSON); - - MockMvcBuilders.standaloneSetup(onboardingController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()); - } - } diff --git a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/UserControllerTest.java b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/UserControllerTest.java deleted file mode 100644 index fe737337a..000000000 --- a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/UserControllerTest.java +++ /dev/null @@ -1,669 +0,0 @@ -package it.pagopa.selfcare.mscore.web.controller; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.commons.base.security.SelfCareUser; -import it.pagopa.selfcare.commons.base.utils.InstitutionType; -import it.pagopa.selfcare.mscore.constant.Env; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.UserRelationshipService; -import it.pagopa.selfcare.mscore.core.UserService; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapper; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapperImpl; -import it.pagopa.selfcare.mscore.model.CertifiedField; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.UserToNotify; -import it.pagopa.selfcare.mscore.model.aggregation.UserInstitutionBinding; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.institution.WorkContact; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardingInfo; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.mscore.web.TestUtils; -import it.pagopa.selfcare.mscore.web.model.mapper.UserMapper; -import it.pagopa.selfcare.mscore.web.model.mapper.UserMapperImpl; -import it.pagopa.selfcare.mscore.web.model.onboarding.OnboardedInstitutionResponse; -import it.pagopa.selfcare.mscore.web.model.onboarding.OnboardingInfoResponse; -import it.pagopa.selfcare.mscore.web.model.user.*; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.http.MediaType; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.request.RequestContextHolder; - -import java.util.*; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class UserControllerTest { - - @InjectMocks - private UserController userController; - - @Mock - private UserRelationshipService userRelationshipService; - - @Mock - private UserService userService; - - @Spy - private UserMapper userMapper = new UserMapperImpl(); - - @Spy - private UserNotificationMapper userNotificationMapper = new UserNotificationMapperImpl(); - - @BeforeEach - void resetContext() { - SecurityContextHolder.clearContext(); - RequestContextHolder.resetRequestAttributes(); - } - - /** - * Method under test: {@link UserController#activateRelationship(String, org.springframework.security.core.Authentication)} - */ - @Test - void testActivateRelationship() throws Exception { - SelfCareUser selfCareUser = SelfCareUser.builder("id").name("nome").surname("cognome").build(); - Authentication authentication = mock(Authentication.class); - when(authentication.getPrincipal()).thenReturn(selfCareUser); - - doNothing().when(userRelationshipService).activateRelationship(org.mockito.Mockito.any(), any(), any()); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .post("/relationships/{relationshipId}/activate", "42") - .principal(authentication); - ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder); - actualPerformResult.andExpect(MockMvcResultMatchers.status().isNoContent()); - } - - /** - * Method under test: {@link UserController#activateRelationship(String, org.springframework.security.core.Authentication)} - */ - @Test - void testActivateRelationship2() throws Exception { - SecurityMockMvcRequestBuilders.FormLoginRequestBuilder requestBuilder = SecurityMockMvcRequestBuilders - .formLogin(); - ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder); - actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); - } - - /** - * Method under test: {@link UserController#activateRelationship(String, org.springframework.security.core.Authentication)} - */ - @Test - void testActivateRelationship3() throws Exception { - SelfCareUser selfCareUser = SelfCareUser.builder("id").name("nome").surname("cognome").build(); - Authentication authentication = mock(Authentication.class); - when(authentication.getPrincipal()).thenReturn(selfCareUser); - doNothing().when(userRelationshipService).activateRelationship(org.mockito.Mockito.any(), any(), any()); - MockHttpServletRequestBuilder postResult = MockMvcRequestBuilders.post("/relationships/{relationshipId}/activate", - "42").principal(authentication); - postResult.characterEncoding("Encoding"); - ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(userController).build().perform(postResult); - actualPerformResult.andExpect(MockMvcResultMatchers.status().isNoContent()); - } - - /** - * Method under test: {@link UserController#suspendRelationship(String, org.springframework.security.core.Authentication)} - */ - @Test - void testSuspendRelationship() throws Exception { - SelfCareUser selfCareUser = SelfCareUser.builder("id").name("nome").surname("cognome").build(); - Authentication authentication = mock(Authentication.class); - when(authentication.getPrincipal()).thenReturn(selfCareUser); - doNothing().when(userRelationshipService).suspendRelationship(org.mockito.Mockito.any(), any(), any()); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .post("/relationships/{relationshipId}/suspend", "42") - .principal(authentication); - ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder); - actualPerformResult.andExpect(MockMvcResultMatchers.status().isNoContent()); - } - - /** - * Method under test: {@link UserController#suspendRelationship(String, org.springframework.security.core.Authentication)} - */ - @Test - void testSuspendRelationship2() throws Exception { - SelfCareUser selfCareUser = SelfCareUser.builder("id").name("nome").surname("cognome").build(); - Authentication authentication = mock(Authentication.class); - when(authentication.getPrincipal()).thenReturn(selfCareUser); - doNothing().when(userRelationshipService).suspendRelationship(org.mockito.Mockito.any(), any(), any()); - MockHttpServletRequestBuilder postResult = MockMvcRequestBuilders.post("/relationships/{relationshipId}/suspend", - "42").principal(authentication); - postResult.characterEncoding("Encoding"); - ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(userController).build().perform(postResult); - actualPerformResult.andExpect(MockMvcResultMatchers.status().isNoContent()); - } - - /** - * Method under test: {@link UserController#deleteRelationship(String, org.springframework.security.core.Authentication)} - */ - @Test - void testDeleteRelationship() throws Exception { - SelfCareUser selfCareUser = SelfCareUser.builder("id").name("nome").surname("cognome").build(); - Authentication authentication = mock(Authentication.class); - when(authentication.getPrincipal()).thenReturn(selfCareUser); - doNothing().when(userRelationshipService).deleteRelationship(org.mockito.Mockito.any(), any(), any()); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.delete("/relationships/{relationshipId}", - "42").principal(authentication); - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isNoContent()); - } - - /** - * Method under test: {@link UserController#deleteRelationship(String, org.springframework.security.core.Authentication)} - */ - @Test - void testDeleteRelationship2() throws Exception { - SelfCareUser selfCareUser = SelfCareUser.builder("id").name("nome").surname("cognome").build(); - Authentication authentication = mock(Authentication.class); - when(authentication.getPrincipal()).thenReturn(selfCareUser); - doNothing().when(userRelationshipService).deleteRelationship(org.mockito.Mockito.any(), any(), any()); - MockHttpServletRequestBuilder deleteResult = MockMvcRequestBuilders.delete("/relationships/{relationshipId}", - "42").principal(authentication); - deleteResult.characterEncoding("Encoding"); - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(deleteResult) - .andExpect(MockMvcResultMatchers.status().isNoContent()); - } - - /** - * Method under test: {@link UserController#getRelationship(String)} - */ - @Test - void testGetRelationship() throws Exception { - Institution institution = new Institution(); - institution.setOnboarding(new ArrayList<>()); - - RelationshipInfo relationshipInfo = new RelationshipInfo(); - relationshipInfo.setInstitution(institution); - when(userRelationshipService.retrieveRelationship(org.mockito.Mockito.any())) - .thenReturn(relationshipInfo); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/relationships/{relationshipId}", - "42"); - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json")) - .andExpect(MockMvcResultMatchers.content() - .string( - "{\"institutionUpdate\":{\"imported\":false}}")); - } - - /** - * Method under test: {@link UserController#getRelationship(String)} - */ - @Test - void testGetRelationship2() throws Exception { - - Institution institution = TestUtils.createSimpleInstitutionPA(); - institution.setSupportPhone("8605550118"); - institution.setSupportEmail("john.smith@example.org"); - institution.setBusinessRegisterPlace("U"); - institution.setShareCapital("U"); - institution.setRea("U"); - institution.setTaxCode("U"); - institution.setZipCode("OX1 1PT"); - institution.setAddress("17 High St"); - institution.setDigitalAddress("17 High St"); - institution.setInstitutionType(InstitutionType.PG); - institution.setDescription("?"); - institution.setId("?"); - - RelationshipInfo relationshipInfo = new RelationshipInfo(); - relationshipInfo.setUserId("?"); - relationshipInfo.setInstitution(institution); - when(userRelationshipService.retrieveRelationship(org.mockito.Mockito.any())) - .thenReturn(relationshipInfo); - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/relationships/{relationshipId}", - "42"); - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().contentType("application/json")) - .andExpect(MockMvcResultMatchers.content() - .string( - "{\"to\":\"?\",\"from\":\"?\",\"institutionUpdate\":{\"institutionType\":\"PG\",\"description\":\"?\",\"digitalAddress\":\"17" - + " High St\",\"address\":\"17 High St\",\"taxCode\":\"U\",\"zipCode\":\"OX1 1PT\",\"paymentServiceProvider\":{\"abiCode" - + "\":\""+institution.getPaymentServiceProvider().getAbiCode()+"\",\"businessRegisterNumber\":\"42\",\"legalRegisterNumber\":\"42\"," + - "\"legalRegisterName\":\""+institution.getPaymentServiceProvider().getLegalRegisterName()+"\",\"vatNumberGroup" - + "\":true},\"dataProtectionOfficer\":{\"address\":\"42 Main St\",\"email\":\"jane.doe@example.org\",\"pec\":\""+institution.getDataProtectionOfficer().getPec()+"\"}," - + "\"geographicTaxonomyCodes\":[],\"rea\":\"U\",\"shareCapital\":\"U\",\"businessRegisterPlace\":\"U\",\"supportEmail\"" - + ":\"john.smith@example.org\",\"supportPhone\":\"8605550118\",\"imported\":false}}")); - } - - @Test - void verifyUser() throws Exception { - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .head("/persons/{id}", "42") - .contentType(MediaType.APPLICATION_JSON); - - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isNotFound()); - } - - - /** - * Method under test: {@link UserController#getInstitutionProductsInfo(String, String, String[])} - */ - @Test - void testGetInstitutionProductsInfo() throws Exception { - - OnboardingInfo onboardingInfo = new OnboardingInfo(); - onboardingInfo.setUserId("id"); - UserInstitutionBinding userInstitutionBinding = new UserInstitutionBinding(); - OnboardedProduct product = new OnboardedProduct(); - product.setProductId("productId"); - product.setStatus(RelationshipState.ACTIVE); - userInstitutionBinding.setProducts(product); - onboardingInfo.setBinding(userInstitutionBinding); - Institution institution = new Institution(); - institution.setId("institutionId"); - institution.setInstitutionType(InstitutionType.PA); - Onboarding onboarding = new Onboarding(); - onboarding.setProductId("productId"); - onboarding.setStatus(RelationshipState.ACTIVE); - institution.setOnboarding(List.of(onboarding)); - onboardingInfo.setInstitution(institution); - - when(userService.getUserInfo(anyString(), anyString(), any())).thenReturn(List.of(onboardingInfo)); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/users/id/institution-products?institutionId=test") - .contentType(MediaType.APPLICATION_JSON); - - MvcResult result = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn(); - - OnboardingInfoResponse response = new ObjectMapper().readValue( - result.getResponse().getContentAsString(), - new TypeReference<>() { - }); - - assertNotNull(response); - assertNotNull(response.getUserId()); - assertEquals(response.getUserId(), onboardingInfo.getUserId()); - assertNotNull(response.getInstitutions()); - assertEquals(1, response.getInstitutions().size()); - - OnboardedInstitutionResponse institutionResponse = response.getInstitutions().get(0); - - assertEquals(institutionResponse.getInstitutionType(), onboardingInfo.getInstitution().getInstitutionType()); - assertEquals(institutionResponse.getId(), onboardingInfo.getInstitution().getId()); - assertEquals(institutionResponse.getProductInfo().getId(), onboardingInfo.getBinding().getProducts().getProductId()); - assertEquals(institutionResponse.getInstitutionType(), onboardingInfo.getInstitution().getInstitutionType()); - - } - - /** - * Method under test: {@link UserController#getUserProductsInfo(String, String, String[])} - */ - @Test - void getUserProductsInfo_shouldNotFound() throws Exception { - - final String userId = "userId"; - final String institutionId = "institutionId"; - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/users/{id}/products?institutionId={test}", userId, institutionId) - .contentType(MediaType.APPLICATION_JSON); - - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isNotFound()); - } - - /** - * Method under test: {@link UserController#getUserProductsInfo(String, String, String[])} - */ - @Test - void getUserProductsInfo_shouldGetData() throws Exception { - - final String institutionId = "institutionId"; - - OnboardedUser expected = dummyOnboardedUser(institutionId); - - when(userService.retrieveBindings(anyString(), anyString(), any(), any())) - .thenReturn(expected.getBindings()); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/users/{id}/products?institutionId={test}", expected.getId(), institutionId) - .contentType(MediaType.APPLICATION_JSON); - - MvcResult result = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn(); - - UserProductsResponse actual = new ObjectMapper().readValue( - result.getResponse().getContentAsString(), UserProductsResponse.class); - - assertNotNull(actual); - assertEquals(expected.getId(), actual.getId()); - assertNotNull(actual.getBindings()); - assertEquals(1, actual.getBindings().size()); - - InstitutionProducts actualInstitutionProducts = actual.getBindings().get(0); - UserBinding expectedUserBinding = expected.getBindings().get(0); - - assertThat( actualInstitutionProducts.getInstitutionId()).isEqualTo(expectedUserBinding.getInstitutionId()); - - Product actualProduct = actualInstitutionProducts.getProducts().get(0); - OnboardedProduct expectedProduct = expectedUserBinding.getProducts().get(0); - - assertThat( actualProduct.getProductRole()).isEqualTo(expectedProduct.getProductRole()); - assertThat( actualProduct.getProductId()).isEqualTo(expectedProduct.getProductId()); - assertThat( actualProduct.getContract()).isEqualTo(expectedProduct.getContract()); - assertThat( actualProduct.getRole()).isEqualTo(expectedProduct.getRole()); - assertThat( actualProduct.getEnv()).isEqualTo(expectedProduct.getEnv()); - assertThat( actualProduct.getTokenId()).isEqualTo(expectedProduct.getTokenId()); - assertThat( actualProduct.getStatus()).isEqualTo(expectedProduct.getStatus()); - - } - - - /** - * Method under test: {@link UserController#getUserProductsInfo(String, String, String[])} - */ - @Test - void getUserProductsInfo_shouldGetDataWithStates() throws Exception { - //Given - - final String institutionId = "institutionId"; - final String state = "ACTIVE"; - - OnboardedUser expected = dummyOnboardedUser(institutionId); - - when(userService.retrieveBindings(anyString(), anyString(), any(), any())) - .thenReturn(expected.getBindings()); - - //When - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/users/{id}/products?institutionId={test}&states={state}", expected.getId(), institutionId, state) - .contentType(MediaType.APPLICATION_JSON); - - MvcResult result = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn(); - - //Then - UserProductsResponse actual = new ObjectMapper().readValue( - result.getResponse().getContentAsString(), UserProductsResponse.class); - - assertNotNull(actual); - assertEquals(expected.getId(), actual.getId()); - assertNotNull(actual.getBindings()); - assertEquals(1, actual.getBindings().size()); - - InstitutionProducts actualInstitutionProducts = actual.getBindings().get(0); - UserBinding expectedUserBinding = expected.getBindings().get(0); - - assertThat( actualInstitutionProducts.getInstitutionId()).isEqualTo(expectedUserBinding.getInstitutionId()); - - Product actualProduct = actualInstitutionProducts.getProducts().get(0); - OnboardedProduct expectedProduct = expectedUserBinding.getProducts().get(0); - - assertThat( actualProduct.getProductRole()).isEqualTo(expectedProduct.getProductRole()); - assertThat( actualProduct.getProductId()).isEqualTo(expectedProduct.getProductId()); - assertThat( actualProduct.getContract()).isEqualTo(expectedProduct.getContract()); - assertThat( actualProduct.getRole()).isEqualTo(expectedProduct.getRole()); - assertThat( actualProduct.getEnv()).isEqualTo(expectedProduct.getEnv()); - assertThat( actualProduct.getTokenId()).isEqualTo(expectedProduct.getTokenId()); - assertThat( actualProduct.getStatus()).isEqualTo(expectedProduct.getStatus()); - - } - - - /** - * Method under test: {@link UserController#deleteProducts(String, String, String)} - */ - @Test - void deleteProducts() throws Exception { - - final String userId = "userId"; - final String institutionId = "institutionId"; - final String productId = "productId"; - - doNothing().when(userService).updateUserStatus(userId, institutionId, productId, null, null, RelationshipState.DELETED); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .delete("/users/{userId}/institutions/{institutionId}/products/{productId}", userId, institutionId, productId) - .contentType(MediaType.APPLICATION_JSON); - - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()); - } - - private UserBinding dummyUserBinding(String institutionId) { - - UserBinding userBinding = new UserBinding(); - userBinding.setInstitutionId(institutionId); - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setProductId("productId"); - onboardedProduct.setProductRole("admin"); - onboardedProduct.setStatus(RelationshipState.ACTIVE); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setEnv(Env.PROD); - onboardedProduct.setContract("contract"); - onboardedProduct.setRelationshipId("setRelationshipId"); - onboardedProduct.setTokenId("setTokenId"); - - userBinding.setProducts(List.of(onboardedProduct)); - return userBinding; - } - - private OnboardedUser dummyOnboardedUser(String institutionId) { - OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setId("id"); - UserBinding userBinding = dummyUserBinding(institutionId); - onboardedUser.setBindings(List.of(userBinding)); - return onboardedUser; - } - - @Test - void testGetPersonOk() throws Exception { - - User user = new User(); - user.setFiscalCode("taxCode"); - CertifiedField certName = new CertifiedField<>(); - certName.setValue("nome"); - user.setName(certName); - CertifiedField certSurname = new CertifiedField<>(); - certSurname.setValue("cognome"); - user.setFamilyName(certSurname); - Map map = new HashMap<>(); - WorkContact contact = new WorkContact(); - CertifiedField mail = new CertifiedField<>(); - mail.setValue("mail@test.it"); - contact.setEmail(mail); - map.put("id", contact); - user.setWorkContacts(map); - when(userService.retrievePerson("userId", "prod-pn", "id")).thenReturn(user); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/users/userId?productId=prod-pn&institutionId=id") - .contentType(MediaType.APPLICATION_JSON); - - MvcResult result = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn(); - - UserResponse response = new ObjectMapper().readValue( - result.getResponse().getContentAsString(), - new TypeReference<>() { - }); - - Assertions.assertEquals("nome", response.getName()); - Assertions.assertEquals("cognome", response.getSurname()); - Assertions.assertEquals("mail@test.it", response.getEmail()); - Assertions.assertEquals("taxCode", response.getTaxCode()); - - } - - @Test - void testGetPersonOkWithoutMail() throws Exception { - - User user = new User(); - user.setFiscalCode("taxCode"); - CertifiedField certName = new CertifiedField<>(); - certName.setValue("nome"); - user.setName(certName); - CertifiedField certSurname = new CertifiedField<>(); - certSurname.setValue("cognome"); - user.setFamilyName(certSurname); - Map map = new HashMap<>(); - WorkContact contact = new WorkContact(); - CertifiedField mail = new CertifiedField<>(); - mail.setValue("mail@test.it"); - contact.setEmail(mail); - map.put("id", contact); - user.setWorkContacts(map); - when(userService.retrievePerson("userId", "prod-pn", null)).thenReturn(user); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/users/userId?productId=prod-pn") - .contentType(MediaType.APPLICATION_JSON); - - MvcResult result = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn(); - - UserResponse response = new ObjectMapper().readValue( - result.getResponse().getContentAsString(), - new TypeReference<>() { - }); - - Assertions.assertEquals("nome", response.getName()); - Assertions.assertEquals("cognome", response.getSurname()); - Assertions.assertEquals("taxCode", response.getTaxCode()); - - } - - /** - * Method under test: {@link UserController#getUsers(Optional, Optional, String)}} - */ - @Test - void testFindAllUsers() throws Exception { - - UserNotificationToSend user = new UserNotificationToSend(); - user.setInstitutionId("institutionId"); - UserToNotify userToNotify = new UserToNotify(); - userToNotify.setName("name"); - userToNotify.setFamilyName("surname"); - user.setUser(userToNotify); - user.setProductId("prod-io"); - - when(userService.findAll(any(), any(), anyString())).thenReturn(List.of(user)); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/users?productId=prod-io") - .contentType(MediaType.APPLICATION_JSON); - - MvcResult result = MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andReturn(); - - UsersNotificationResponse response = new ObjectMapper().readValue( - result.getResponse().getContentAsString(), - UsersNotificationResponse.class); - - Assertions.assertNotNull(response); - Assertions.assertNotNull(response.getUsers()); - Assertions.assertFalse(response.getUsers().isEmpty()); - Assertions.assertNotNull(response.getUsers().get(0)); - Assertions.assertNotNull(response.getUsers().get(0).getBindings().get(0).getUser()); - Assertions.assertEquals("name", response.getUsers().get(0).getBindings().get(0).getUser().getName()); - Assertions.assertEquals("surname", response.getUsers().get(0).getBindings().get(0).getUser().getFamilyName()); - Assertions.assertEquals("prod-io", response.getUsers().get(0).getBindings().get(0).getProductId()); - Assertions.assertEquals("institutionId", response.getUsers().get(0).getBindings().get(0).getInstitutionId()); - - } - - @Test - void updateUserStatus() throws Exception { - final String userId = "userId"; - - doNothing().when(userService).updateUserStatus(userId, null, null, null, null, RelationshipState.DELETED); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .put("/users/{id}/status", userId) - .queryParam("status","DELETED") - .contentType(MediaType.APPLICATION_JSON); - - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isNoContent()); - } - - @Test - void onboardedUsers() throws Exception { - final OnboardedUser onboardedUser = new OnboardedUser(); - onboardedUser.setId("userId"); - when(userService.findAllByIds(any())).thenReturn(List.of(onboardedUser)); - - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders - .get("/onboarded-users") - .queryParam("ids","userId") - .contentType(MediaType.APPLICATION_JSON); - - MockMvcBuilders.standaloneSetup(userController) - .build() - .perform(requestBuilder) - .andExpect(MockMvcResultMatchers.status().isOk()); - } - -} -