diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/GroupController.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/GroupController.java index 3163e7518bf7a1b7129989b8d5b84302abc6e805..6b428b67307cbff9bd65222481cfb615b77dfdbe 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/GroupController.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/controller/group/GroupController.java @@ -4,12 +4,12 @@ import lombok.AllArgsConstructor; import ntnu.idatt2016.v233.SmartMat.entity.group.Group; import ntnu.idatt2016.v233.SmartMat.entity.group.UserGroupAsso; import ntnu.idatt2016.v233.SmartMat.service.group.GroupService; -import ntnu.idatt2016.v233.SmartMat.service.group.UserGroupAssoService; import ntnu.idatt2016.v233.SmartMat.service.user.UserService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; +import java.util.Optional; /** * Controller for groups API, providing endpoints for group management @@ -23,7 +23,8 @@ import java.util.List; @RequestMapping("/api/groups") public class GroupController { private final GroupService groupService; - private final UserGroupAssoService userGroupAssoService; + + private final UserService userService; /** * Gets a group by its name @@ -58,15 +59,23 @@ public class GroupController { @PostMapping("/{username}") public ResponseEntity<Group> createGroup(@RequestBody Group group, @PathVariable("username") String username) { - if(groupService.getGroupById(group.getGroupId()).isPresent()) { - return ResponseEntity.badRequest().build(); - } - if(group.getGroupName().equals("")) { + + if(group.getGroupName().equals("") || + userService.getUserFromUsername(username).isEmpty() || + groupService.getGroupById(group.getGroupId()).isPresent()) { return ResponseEntity.badRequest().build(); } + + Group group1 = groupService.createGroup(group); - userGroupAssoService.addPersonToGroup(username,group1.getLinkCode(), "ADMIN"); - return ResponseEntity.ok(group1); + group1.addUser(UserGroupAsso.builder() + .groupAuthority("ADMIN") + .group(group1) + .user(userService.getUserFromUsername(username).get()) + .build()); + + return groupService.updateGroup(group1).map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.badRequest().build()); } /** @@ -132,23 +141,37 @@ public class GroupController { */ @GetMapping("/information/{groupId}") public ResponseEntity<List<UserGroupAsso>> getInformationByGroupId(@PathVariable("groupId") long groupId){ - return userGroupAssoService.getInformationByGroupId(groupId).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + return groupService.getGroupById(groupId) + .map(group -> ResponseEntity.ok(group.getUser())) + .orElseGet(() -> ResponseEntity.notFound().build()); } /** * Handles the HTTP PUT request to change the primary group of a user. * * @param username the username of the user whose primary group is to be changed - * @param newId the ID of the new primary group - * @param oldId the ID of the old primary group + * @param groupId the ID of the group * @return a ResponseEntity object containing an HTTP status code and the updated UserGroupAsso object, * or a ResponseEntity object with an HTTP status code indicating that the request was not successful */ - @PutMapping("/markNewPrimary/{username}/{oldId}/{newId}") + @PutMapping("/markNewPrimary/{username}/{groupId}/{newId}") public ResponseEntity<?> markNewPrimaryGroup(@PathVariable("username") String username, - @PathVariable("newId") long newId, - @PathVariable("oldId") long oldId){ - return userGroupAssoService.changePrimaryGroup(oldId,newId,username).map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); + @PathVariable("groupId") long groupId){ + return userService.getUserFromUsername(username) + .flatMap(user ->{ + user.getGroup().forEach(userGroupAsso -> { + if(userGroupAsso.getGroup().getGroupId() != groupId){ + userGroupAsso.setPrimaryGroup(false); + } + if(userGroupAsso.getGroup().getGroupId() == groupId){ + userGroupAsso.setPrimaryGroup(true); + } + }); + return Optional.of(userService.updateUser(user)); + } + ) + .map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.notFound().build()); } /** @@ -162,7 +185,19 @@ public class GroupController { @PostMapping("/connection/{username}/{linkCode}") public ResponseEntity<?> addConnection(@PathVariable("username") String username, @PathVariable("linkCode") String linkCode){ - return userGroupAssoService.addPersonToGroup(username,linkCode,"USER").map(ResponseEntity::ok).orElseGet(()-> ResponseEntity.notFound().build()); + return groupService.getGroupByLinkCode(linkCode) + .flatMap(group -> userService.getUserFromUsername(username) + .flatMap(user -> { + UserGroupAsso userGroupAsso = UserGroupAsso.builder() + .group(group) + .user(user) + .build(); + user.addGroup(userGroupAsso); + userService.updateUser(user); + return Optional.of(userGroupAsso); + })) + .map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.notFound().build()); } /** @@ -178,6 +213,21 @@ public class GroupController { public ResponseEntity<?> changeAuthority(@PathVariable("groupId") long groupId, @PathVariable("username") String username, @PathVariable("authority") String authority){ - return userGroupAssoService.changeAuthorityOfUser(username,groupId,authority).map(ResponseEntity::ok).orElseGet(() ->ResponseEntity.notFound().build()); + return groupService.getGroupById(groupId).flatMap(group -> userService.getUserFromUsername(username) + .flatMap(user -> { + UserGroupAsso userGroupAsso = user.getGroup().stream() + .filter(asso -> asso.getGroup().getGroupId() == groupId) + .findFirst() + .orElse(null); + if(userGroupAsso != null){ + userGroupAsso.setGroupAuthority(authority); + userService.updateUser(user); + return Optional.of(userGroupAsso); + } + return Optional.empty(); + })) + .map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.notFound().build()); } + } diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Fridge.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Fridge.java index da4f5e880f4125d8084a85a47b4660af06e7fcc1..9e975a5578542e4f657d6a015848b7918fc92b20 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Fridge.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Fridge.java @@ -38,7 +38,7 @@ public class Fridge{ @JsonIgnoreProperties("fridge") Group group; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @OneToMany(cascade = CascadeType.ALL) @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(name = "fridge_id") @JsonIgnoreProperties("fridge") diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Group.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Group.java index c5fa77898b6a9c4b22dd775bf9c9f9b8f045d4e2..b0bb05e03edf431c0af32cf36aec4396f94dbda8 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Group.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/Group.java @@ -8,6 +8,8 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import ntnu.idatt2016.v233.SmartMat.entity.user.User; +import org.hibernate.annotations.OnDelete; +import org.hibernate.annotations.OnDeleteAction; import java.util.ArrayList; import java.util.List; @@ -47,9 +49,10 @@ public class Group { @Column(name = "is_open") Boolean open; - @OneToMany + @OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.LAZY) @JoinColumn(name = "group_id") @JsonIgnoreProperties("group") + @OnDelete(action = OnDeleteAction.CASCADE) private List<UserGroupAsso> user = new ArrayList<>(); @@ -64,9 +67,10 @@ public class Group { @OneToOne @JoinColumn(name = "group_id") @JsonIgnoreProperties("group") + @OnDelete(action = OnDeleteAction.CASCADE) private Fridge fridge; - @ManyToMany + @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.LAZY) @JoinTable(name = "group_achievement", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "achievement_name")) diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/UserGroupAsso.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/UserGroupAsso.java index dcbb4544d5bb68fea2c2cb2582e4eeae7425f251..5c90e08c389f8ddf218412386a0bf3ccd156f082 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/UserGroupAsso.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/group/UserGroupAsso.java @@ -16,6 +16,7 @@ import ntnu.idatt2016.v233.SmartMat.entity.user.User; @AllArgsConstructor @NoArgsConstructor @Getter @Setter +@Builder @Table(name = "user_group") public class UserGroupAsso { diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Product.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Product.java index 33fb63daf55f26f23eb784f15c3043a8eb783d75..304abf83500fa3e188ee078b61d1a1bee8762dc8 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Product.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/product/Product.java @@ -72,7 +72,7 @@ public class Product{ inverseJoinColumns = @JoinColumn(name = "allergy_name")) List<Allergy> allergies; - @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @OneToMany(cascade = CascadeType.ALL) @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(name = "ean") @JsonIgnoreProperties({"products"}) diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java index 0bc5b0fc56245c1d4d981cfd2b71d12a6bbda617..a3a5b43202ebc8d08784cfe51382cefedb533d5b 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/entity/user/User.java @@ -55,7 +55,7 @@ public class User implements UserDetails { private Date dateOfBirth; - @OneToMany + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "username") @JsonIgnoreProperties("user") private List<UserGroupAsso> group; diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/GroupService.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/GroupService.java index 615b3e29c0a13bd2e134eeba6eb7bcf34e733674..83428ebe3ee937794de18b2fddbaf08e4f035e2c 100644 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/GroupService.java +++ b/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/GroupService.java @@ -147,4 +147,17 @@ public class GroupService { fridgeRepository.save(fridge.get()); } } + + /** + * Updates a group + * @param group the group to update + * @return an optional containing the updated group + */ + public Optional<Group> updateGroup(Group group){ + return Optional.of(groupRepository.save(group)); + } + + public Optional<Group> getGroupByLinkCode(String linkCode) { + return groupRepository.findByLinkCode(linkCode); + } } diff --git a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/UserGroupAssoService.java b/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/UserGroupAssoService.java deleted file mode 100644 index f07f9e911527497f0c8c60ba6bd020337ac3d5e0..0000000000000000000000000000000000000000 --- a/src/main/java/ntnu/idatt2016/v233/SmartMat/service/group/UserGroupAssoService.java +++ /dev/null @@ -1,125 +0,0 @@ -package ntnu.idatt2016.v233.SmartMat.service.group; - - -import lombok.AllArgsConstructor; -import ntnu.idatt2016.v233.SmartMat.entity.group.Group; -import ntnu.idatt2016.v233.SmartMat.entity.group.UserGroupId; -import ntnu.idatt2016.v233.SmartMat.entity.group.UserGroupAsso; -import ntnu.idatt2016.v233.SmartMat.entity.user.User; -import ntnu.idatt2016.v233.SmartMat.repository.group.GroupRepository; -import ntnu.idatt2016.v233.SmartMat.repository.group.UserGroupAssoRepository; -import ntnu.idatt2016.v233.SmartMat.repository.user.UserRepository; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Optional; - -@Service -@AllArgsConstructor -public class UserGroupAssoService { - - private UserGroupAssoRepository userGroupAssoRepository; - private GroupRepository groupRepository; - private final UserRepository userRepository; - - public void save(User user, Group group, String authority) { - UserGroupAsso userGroupTable1 = new UserGroupAsso(); - userGroupTable1.setGroup(group); - userGroupTable1.setUser(user); - userGroupTable1.setPrimaryGroup(false); - userGroupTable1.setGroupAuthority(authority); - userGroupTable1.setId(UserGroupId.builder() - .groupId(group.getGroupId()) - .username(user.getUsername()) - .build()); - - userGroupAssoRepository.save(userGroupTable1); - - user.addGroup(userGroupTable1); - group.addUser(userGroupTable1); - - groupRepository.save(group); - userRepository.save(user); - - } - - /** - * Retrieves a list of UserGroupAsso objects for the specified group ID. - * - * @param id the ID of the group to retrieve information for - * @return an Optional containing a list of UserGroupAsso objects for the specified group ID, or an empty Optional if no information is found - */ - public Optional<List<UserGroupAsso>> getInformationByGroupId(long id){ - if (groupRepository.findByGroupId(id).isPresent()){ - List<UserGroupAsso> list = userGroupAssoRepository.findAllByGroup(groupRepository.findByGroupId(id).get()); - if(!list.isEmpty()) return Optional.of(list); - } - return Optional.empty(); - } - - /** - * Changes the primary group of a user by unmarking the current primary group and marking a new primary group. - * - * @param newId The ID of the new primary group. - * @param username The username of the user whose primary group is being changed. - */ - public Optional<Object> changePrimaryGroup(long oldId, long newId, String username){ - Optional<Group> oldGroup = groupRepository.findByGroupId(oldId); - Optional<Group> newGroup = groupRepository.findByGroupId(newId); - Optional<User> user = userRepository.findByUsername(username); - - if (newGroup.isEmpty()) return Optional.empty(); - if (user.isEmpty()) return Optional.empty(); - - UserGroupAsso userGroupAsso; - if (oldGroup.isPresent()){ - userGroupAsso = userGroupAssoRepository.findAllByGroupAndUser(oldGroup.get(),user.get()).get(); - userGroupAsso.setPrimaryGroup(false); - userGroupAssoRepository.save(userGroupAsso); - } - userGroupAsso = userGroupAssoRepository.findAllByGroupAndUser(newGroup.get(),user.get()).get(); - userGroupAsso.setPrimaryGroup(true); - userGroupAssoRepository.save(userGroupAsso); - - return Optional.of(userGroupAsso); - } - - /** - * Adds a new user to a group. - * - * @param username the username of the user to add - * @param linkCode the link code of the group to which the user is to be added - * @param authority the authority level of the user in the group - * @return an Optional object containing the UserGroupAsso object of the user in the group, - * or an empty Optional if the group or user does not exist, or if the user is already in the group - */ - public Optional<Object> addPersonToGroup(String username, String linkCode, String authority){ - Optional<Group> group = groupRepository.findByLinkCode(linkCode); - Optional<User> user = userRepository.findByUsername(username); - if(group.isEmpty()) return Optional.empty(); - if(user.isEmpty()) return Optional.empty(); - if(userGroupAssoRepository.findAllByGroupAndUser(group.get(),user.get()).isPresent()) return Optional.of("User is already in this group!"); - save(user.get(),group.get(),authority); - changePrimaryGroup(userGroupAssoRepository.findFirstByUserAndPrimaryGroup(user.get(),true).get().getGroup().getGroupId(), group.get().getGroupId(),username); - return Optional.of(userGroupAssoRepository.findAllByGroupAndUser(group.get(),user.get()).get()); - } - - /** - * Changes the authority of a user in a group and updates the primary group if necessary. - * @param username the username of the user whose authority will be changed. - * @param groupId the ID of the group in which the user's authority will be changed. - * @param authority the new authority level for the user in the group. - * @return an Optional containing the updated UserGroupAsso object, or an empty Optional if the user or group does not exist, or if the user is not in the group. - */ - public Optional<Object> changeAuthorityOfUser(String username, long groupId, String authority){ - Optional<Group> group = groupRepository.findByGroupId(groupId); - Optional<User> user = userRepository.findByUsername(username); - if(group.isEmpty()) return Optional.empty(); - if(user.isEmpty()) return Optional.empty(); - if(userGroupAssoRepository.findAllByGroupAndUser(group.get(),user.get()).isEmpty()) return Optional.of("User is not in this group!"); - save(user.get(),group.get(),authority); - changePrimaryGroup(userGroupAssoRepository.findFirstByUserAndPrimaryGroup(user.get(),true).get().getGroup().getGroupId(), group.get().getGroupId(),username); - return Optional.of(userGroupAssoRepository.findAllByGroupAndUser(group.get(),user.get()).get()); - } - -} diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/repository/group/GroupRepositoryTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/repository/group/GroupRepositoryTest.java index 4b5ecc435167317fc086976de7a76b193bbe8912..5f549192b67a56f5ff3e1f2bd0c45961340d705f 100644 --- a/src/test/java/ntnu/idatt2016/v233/SmartMat/repository/group/GroupRepositoryTest.java +++ b/src/test/java/ntnu/idatt2016/v233/SmartMat/repository/group/GroupRepositoryTest.java @@ -60,7 +60,6 @@ public class GroupRepositoryTest { Group group2 = Group.builder().groupName("group 2").achievements(List.of(achievement)).build(); Group group3 = Group.builder().groupName("group 3").build(); - achievementRepository.save(achievement); groupRepository.saveAll(List.of(group1, group2, group3)); @@ -130,9 +129,7 @@ public class GroupRepositoryTest { assertTrue(tempGroupe.isPresent()); - Achievement tempAchievement = Achievement.builder().achievementName("test").build(); - - achievementRepository.save(tempAchievement); + Achievement tempAchievement = Achievement.builder().achievementName("test2").build(); Group tempGroup = tempGroupe.get(); diff --git a/src/test/java/ntnu/idatt2016/v233/SmartMat/service/group/UserGroupAssoServiceTest.java b/src/test/java/ntnu/idatt2016/v233/SmartMat/service/group/UserGroupAssoServiceTest.java deleted file mode 100644 index 2c705f3ed275a488c5db55fb0079075f1ce74c35..0000000000000000000000000000000000000000 --- a/src/test/java/ntnu/idatt2016/v233/SmartMat/service/group/UserGroupAssoServiceTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package ntnu.idatt2016.v233.SmartMat.service.group; - -import ntnu.idatt2016.v233.SmartMat.entity.group.Group; -import ntnu.idatt2016.v233.SmartMat.entity.group.UserGroupId; -import ntnu.idatt2016.v233.SmartMat.entity.group.UserGroupAsso; -import ntnu.idatt2016.v233.SmartMat.entity.user.User; -import ntnu.idatt2016.v233.SmartMat.repository.group.GroupRepository; -import ntnu.idatt2016.v233.SmartMat.repository.group.UserGroupAssoRepository; -import ntnu.idatt2016.v233.SmartMat.repository.user.UserRepository; -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.junit.jupiter.MockitoExtension; - -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -public class UserGroupAssoServiceTest { - - @Mock - private UserGroupAssoRepository userGroupAssoRepository; - - @Mock - private GroupRepository groupRepository; - - @Mock - private UserRepository userRepository; - - @InjectMocks - private UserGroupAssoService userGroupAssoService; - - private User user; - private Group group; - private UserGroupAsso userGroupAsso; - - @BeforeEach - public void setUp() { - user = new User(); - user.setUsername("testUser"); - - group = new Group(); - group.setGroupId(1L); - - userGroupAsso = new UserGroupAsso(); - userGroupAsso.setUser(user); - userGroupAsso.setGroup(group); - userGroupAsso.setPrimaryGroup(true); - userGroupAsso.setGroupAuthority("ADMIN"); - userGroupAsso.setId(UserGroupId.builder() - .groupId(group.getGroupId()) - .username(user.getUsername()) - .build()); - } - - @Test - public void testSave() { - userGroupAssoService.save(user, group, "ADMIN"); - - verify(userGroupAssoRepository, times(1)).save(any(userGroupAsso.getClass())); - verify(userRepository, times(1)).save(user); - verify(groupRepository, times(1)).save(group); - } -}