Skip to content

Commit

Permalink
adding update with profiles
Browse files Browse the repository at this point in the history
  • Loading branch information
LuciaM1 committed Jul 19, 2024
1 parent e939d5a commit ded8238
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,6 @@ public Uni<List<UserProfilesDTO>> update(@RequestBody(required = true) @Valid Us
.transform(updatedUserProfiles -> userProfilesMapper.toDtoList(updatedUserProfiles));
}

@GET
@Path("/insert-with-profiles")
@Produces(MediaType.APPLICATION_JSON)
public Uni<Response> checkSpecificProfiles() {
return userProfilesService.checkAtLeastTwoSpecificUserProfiles()
.onItem()
.transform(isAtLeastTwo -> Response.ok(isAtLeastTwo).build())
.onFailure()
.recoverWithItem(th -> Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(th.getMessage())
.build());
}

@GET
@Path("/userId/{userId}/profileId/{profileId}")
@Produces(MediaType.APPLICATION_JSON)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
Expand Down Expand Up @@ -59,12 +66,24 @@ public Uni<UserWithProfilesDTO> firstAccess(@PathParam("userId") String userId)
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Uni<UserWithProfilesDTO> update(@RequestBody(required = true) @Valid UserInsertionDTO userInsertionDTO) {
return this.userService.updateUser(userInsertionDTO)
public Uni<UserWithProfilesDTO> update(@RequestBody(required = true) @Valid UserInsertionDTO input) {
return this.userService.updateUser(input.getUserId(), input.getName(), input.getSurname())
.onItem()
.transformToUni(updatedUser -> Uni.createFrom().item(userMapper.toProfilesDTO(updatedUser)));
}

@PUT
@Path("/update-with-profiles")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Uni<UserWithProfilesDTO> updateWithProfiles(@RequestBody(required = true) @Valid UserInsertionWithProfilesDTO userInsertionWithProfilesDTO) {
return this.userService.updateWithProfiles(userInsertionWithProfilesDTO)
.onItem()
.transformToUni(updatedUser -> userRepository.findByIdCustom(userInsertionWithProfilesDTO.getUserId()))
.onItem()
.transformToUni(insertedUser -> Uni.createFrom().item(this.userMapper.toProfilesDTO(insertedUser)));
}


@POST
@Path("/insert-with-profiles")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import it.gov.pagopa.atmlayer.service.model.dto.UserInsertionWithProfilesDTO;
import it.gov.pagopa.atmlayer.service.model.dto.UserWithProfilesDTO;
import it.gov.pagopa.atmlayer.service.model.entity.User;
import jakarta.validation.constraints.NotBlank;

import java.util.List;

Expand All @@ -16,7 +17,9 @@ public interface UserService {

Uni<User> findUser(String userId);

Uni<User> updateUser(UserInsertionDTO userInsertionDTO);
Uni<User> updateUser(@NotBlank String userId, @NotBlank String name, @NotBlank String surname);

Uni<User> updateWithProfiles(UserInsertionWithProfilesDTO userInsertionWithProfilesDTO);

Uni<Boolean> deleteUser(String userId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,25 +171,35 @@ public Uni<List<UserProfiles>> updateUserProfiles(UserProfilesInsertionDTO userP
List<Integer> userProfilesToUpdateIds = userProfilesToUpdate.stream().map(y -> y.getUserProfilesPK().getProfileId()).toList();
List<UserProfiles> userProfilesToDelete = userProfilesSaved.stream().filter(w -> !userProfilesToUpdateIds.contains(w.getUserProfilesPK().getProfileId())).toList();
List<UserProfiles> userProfilesToAdd = userProfilesToUpdate.stream().filter(j -> !userProfilesSavedIds.contains(j.getUserProfilesPK().getProfileId())).toList();
if (userProfilesToDelete.stream().anyMatch(p -> p.getUserProfilesPK().getProfileId() == 5)){
return checkAtLeastTwoSpecificUserProfiles()
.onItem()
.transformToUni(canUpdate -> userProfilesRepository.deleteUserProfiles(userProfilesToDelete.stream().map(UserProfiles::getUserProfilesPK).toList())
.onItem()
.transformToUni(deletedRows -> userProfilesRepository.persist(userProfilesToAdd))
.onItem()
.transformToUni(persistedRows -> userProfilesRepository.findByUserId(userProfilesInsertionDTO.getUserId())));
}
return userProfilesRepository.deleteUserProfiles(userProfilesToDelete.stream().map(UserProfiles::getUserProfilesPK).toList())
.onItem()
.transformToUni(deletedRows -> userProfilesRepository.persist(userProfilesToAdd))
.onItem()
.transformToUni(persistedRows -> userProfilesRepository.findByUserId(userProfilesInsertionDTO.getUserId()));
.onItem()
.transformToUni(deletedRows -> userProfilesRepository.persist(userProfilesToAdd))
.onItem()
.transformToUni(persistedRows -> userProfilesRepository.findByUserId(userProfilesInsertionDTO.getUserId()));
})
)
);
}

@WithSession

@Override
public Uni<Void> checkAtLeastTwoSpecificUserProfiles() {
return hasAtLeastTwoSpecificUserProfiles()
.onItem()
.transform(isAtLeastTwo -> {
.transformToUni(isAtLeastTwo -> {
if (!isAtLeastTwo) {
throw new AtmLayerException("Meno di due occorrenze trovate per il profilo specificato.", Response.Status.BAD_REQUEST, AppErrorCodeEnum.NO_ASSOCIATION_FOUND);
throw new AtmLayerException("Un solo utente ha i permessi di 'Gestione utenti': impossibile eliminarli.", Response.Status.BAD_REQUEST, AppErrorCodeEnum.NO_ASSOCIATION_FOUND);
}
return null;
return Uni.createFrom().voidItem();
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@
import io.smallrye.mutiny.unchecked.Unchecked;
import it.gov.pagopa.atmlayer.service.model.dto.UserInsertionDTO;
import it.gov.pagopa.atmlayer.service.model.dto.UserInsertionWithProfilesDTO;
import it.gov.pagopa.atmlayer.service.model.dto.UserProfilesInsertionDTO;
import it.gov.pagopa.atmlayer.service.model.dto.UserWithProfilesDTO;
import it.gov.pagopa.atmlayer.service.model.entity.User;
import it.gov.pagopa.atmlayer.service.model.entity.UserProfiles;
import it.gov.pagopa.atmlayer.service.model.enumeration.AppErrorCodeEnum;
import it.gov.pagopa.atmlayer.service.model.exception.AtmLayerException;
import it.gov.pagopa.atmlayer.service.model.mapper.UserMapper;
import it.gov.pagopa.atmlayer.service.model.repository.UserRepository;
import it.gov.pagopa.atmlayer.service.model.service.UserProfilesService;
import it.gov.pagopa.atmlayer.service.model.service.UserService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -33,17 +37,18 @@ public class UserServiceImpl implements UserService {
@Inject
UserMapper userMapper;

@Inject
UserProfilesService userProfilesService;

@Override
@WithTransaction
public Uni<User> insertUser(UserInsertionDTO userInsertionDTO) {
String userId = userInsertionDTO.getUserId();
log.info("Inserting user with userId : {}", userId);
User user = userMapper.toEntityInsertion(userInsertionDTO);
return this.userRepository.findById(user.getUserId())
.onItem()
.transformToUni(Unchecked.function(x -> {
if (x != null) {
log.error("userId {} already exists", userId);
throw new AtmLayerException(Response.Status.BAD_REQUEST, AppErrorCodeEnum.USER_WITH_SAME_ID_ALREADY_EXIST);
}
return userRepository.persist(user);
Expand All @@ -64,7 +69,6 @@ public Uni<User> insertUserWithProfiles(UserInsertionWithProfilesDTO userInserti
.onItem()
.transformToUni(Unchecked.function(x -> {
if (x != null) {
log.error("userId {} already exists", user.getUserId());
throw new AtmLayerException(Response.Status.BAD_REQUEST, AppErrorCodeEnum.USER_WITH_SAME_ID_ALREADY_EXIST);
}
return userRepository.persist(user);
Expand All @@ -73,31 +77,29 @@ public Uni<User> insertUserWithProfiles(UserInsertionWithProfilesDTO userInserti

@Override
@WithTransaction
public Uni<User> updateUser(UserInsertionDTO userInsertionDTO) {
String userId = userInsertionDTO.getUserId();
log.info("Updating user with userId : {}", userId);
return this.getById(userInsertionDTO.getUserId())
public Uni<User> updateUser(@NotBlank String userId, @NotBlank String name, @NotBlank String surname) {
return this.getById(userId)
.onItem()
.transformToUni(Unchecked.function(userFound -> {
if (userInsertionDTO.getName().isBlank() && userInsertionDTO.getSurname().isBlank()) {
throw new AtmLayerException(Response.Status.BAD_REQUEST, AppErrorCodeEnum.ALL_FIELDS_ARE_BLANK);
} else if (userInsertionDTO.getSurname().isBlank()) {
userFound.setName(userInsertionDTO.getName());
} else if (userInsertionDTO.getName().isBlank()) {
userFound.setSurname(userInsertionDTO.getSurname());
} else {
userFound.setName(userInsertionDTO.getName());
userFound.setSurname(userInsertionDTO.getSurname());
}
userFound.setLastUpdatedAt(new Timestamp(System.currentTimeMillis()));
userFound.setName(name);
userFound.setSurname(surname);
return userRepository.persist(userFound);
}));
}

@Override
@WithTransaction
public Uni<User> updateWithProfiles(UserInsertionWithProfilesDTO input) {
return userProfilesService.updateUserProfiles(new UserProfilesInsertionDTO(input.getUserId(), input.getProfileIds()))
.onItem()
.transformToUni(updatedProfiles ->
this.updateUser(input.getUserId(), input.getName(), input.getSurname())
);
}

@Override
@WithTransaction
public Uni<Boolean> deleteUser(String userId) {
log.info("Deleting user with userId : {}", userId);
return this.getById(userId)
.onItem()
.transformToUni(x -> this.userRepository.deleteById(userId));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ void testUpdate() {
userInsertionDTO.setName("Paolo");
userInsertionDTO.setSurname("Rossi");

when(userService.updateUser(any(UserInsertionDTO.class))).thenReturn(Uni.createFrom().item(user));
when(userService.updateUser(any(String.class), any(String.class), any(String.class))).thenReturn(Uni.createFrom().item(user));
when(userMapper.toProfilesDTO(user)).thenReturn(userWithProfilesDTO);

UserWithProfilesDTO result = given()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,18 +167,13 @@ void testInsertUserExceptionCase() {

@Test
void testUpdateUser() {
UserInsertionDTO dto = new UserInsertionDTO();
dto.setUserId("[email protected]");
dto.setName("Paolo");
dto.setSurname("Rossi");

User user = new User();
user.setUserId(dto.getUserId());
user.setUserId("[email protected]");

when(userServiceImpl.getById(any(String.class))).thenReturn(Uni.createFrom().item(user));
when(userRepository.persist(any(User.class))).thenReturn(Uni.createFrom().item(user));

userServiceImpl.updateUser(dto).subscribe().withSubscriber(UniAssertSubscriber.create())
userServiceImpl.updateUser("[email protected]", "Paolo", "Rossi").subscribe().withSubscriber(UniAssertSubscriber.create())
.assertCompleted()
.assertItem(user);

Expand All @@ -187,18 +182,13 @@ void testUpdateUser() {

@Test
void testUpdateUserSuccessPartialNameOnly() {
UserInsertionDTO dto = new UserInsertionDTO();
dto.setUserId("[email protected]");
dto.setName("Paolo");
dto.setSurname("");

User user = new User();
user.setUserId(dto.getUserId());
user.setUserId("[email protected]");

when(userServiceImpl.getById(any(String.class))).thenReturn(Uni.createFrom().item(user));
when(userRepository.persist(any(User.class))).thenReturn(Uni.createFrom().item(user));

userServiceImpl.updateUser(dto).subscribe().withSubscriber(UniAssertSubscriber.create())
userServiceImpl.updateUser("[email protected]", "Paolo", "Rossi").subscribe().withSubscriber(UniAssertSubscriber.create())
.assertCompleted()
.assertItem(user);

Expand All @@ -207,39 +197,18 @@ void testUpdateUserSuccessPartialNameOnly() {

@Test
void testUpdateUserSuccessPartialSurnameOnly() {
UserInsertionDTO dto = new UserInsertionDTO();
dto.setUserId("[email protected]");
dto.setName("");
dto.setSurname("Rossi");

User user = new User();
user.setUserId(dto.getUserId());
user.setUserId("[email protected]");

when(userServiceImpl.getById(any(String.class))).thenReturn(Uni.createFrom().item(user));
when(userRepository.persist(any(User.class))).thenReturn(Uni.createFrom().item(user));

userServiceImpl.updateUser(dto).subscribe().withSubscriber(UniAssertSubscriber.create())
userServiceImpl.updateUser("[email protected]", "Paolo", "Rossi").subscribe().withSubscriber(UniAssertSubscriber.create())
.assertCompleted()
.assertItem(user);

}

@Test
void testUpdateUserErrorAllFieldsBlank() {
UserInsertionDTO dto = new UserInsertionDTO();
dto.setUserId("");
dto.setName("");
dto.setSurname("");

when(userServiceImpl.getById(any(String.class))).thenReturn(Uni.createFrom().item(new User()));

userServiceImpl.updateUser(dto).subscribe().withSubscriber(UniAssertSubscriber.create())
.assertFailed()
.assertFailedWith(AtmLayerException.class, "Tutti i campi sono vuoti");

verify(userRepository, never()).persist(any(User.class));
}

@Test
void testGetById() {
String userId = "existentId";
Expand Down

0 comments on commit ded8238

Please sign in to comment.