Skip to content

Commit

Permalink
adding update user with profiles (#174)
Browse files Browse the repository at this point in the history
Co-authored-by: ElisKina-dev <[email protected]>
  • Loading branch information
LuciaM1 and ElisKina-dev authored Jul 19, 2024
1 parent 61b96aa commit 9115929
Show file tree
Hide file tree
Showing 10 changed files with 95 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@ public class UserProfiles extends PanacheEntityBase implements Serializable {
private Timestamp lastUpdatedAt;
public UserProfiles(UserProfilesPK userProfilesPK) {
this.userProfilesPK = userProfilesPK;
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@

@ApplicationScoped
public class UserProfilesRepository implements PanacheRepositoryBase<UserProfiles, UserProfilesPK> {
/*public Uni<Long> deleteByUserId(String userId) {
return delete(
"delete from UserProfiles b where b.userProfilesPK.userId = :userId",
Parameters.with("userId", userId));
}*/

public Uni<Long> deleteUserProfiles(List<UserProfilesPK> pKList) {
return delete("delete from UserProfiles b where b.userProfilesPK in :pKList",
Expand All @@ -27,8 +22,8 @@ public Uni<List<UserProfiles>> findByUserId (String userId) {
Parameters.with("userId", userId)).list();
}

/*public Uni<List<UserProfiles>> findByIds (List<String> userProfilePkList) {
return find("select c from UserProfiles c where c.userProfilesPK in :userProfilePkList",
Parameters.with("userProfilePkList",userProfilePkList)).list();
}*/
public Uni<List<UserProfiles>> findUserProfilesWithSpecificProfile() {
return find("select a from UserProfiles a where a.userProfilesPK.profileId = 5").list();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
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 @@ -16,4 +16,6 @@ public interface UserProfilesService {
Uni<Void> deleteUserProfiles(UserProfilesPK userProfilesIDs);

Uni<List<UserProfiles>> updateUserProfiles(UserProfilesInsertionDTO userProfilesInsertionDTO);

Uni<Void> checkAtLeastTwoSpecificUserProfiles();
}
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,14 +171,43 @@ 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()));
})
)
);
}


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

@WithSession
public Uni<Boolean> hasAtLeastTwoSpecificUserProfiles() {
return userProfilesRepository.findUserProfilesWithSpecificProfile()
.onItem()
.transform(userProfiles -> userProfiles.size() >= 2);
}

}
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 9115929

Please sign in to comment.