Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(backend): users can follow/unfollow tags #566

Merged
merged 1 commit into from
Nov 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public static class SparqlEndpoints {
public static class TagEndpoints {
public static final String BASE_PATH = "/tags";
public static final String TAG_ID = BASE_PATH + "/{id}";
public static final String TAG_FOLLOW = BASE_PATH + "/{id}/follow";
public static final String SEARCH = "/search" + BASE_PATH;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,16 @@
import com.group1.programminglanguagesforum.DTOs.Responses.ErrorResponse;
import com.group1.programminglanguagesforum.DTOs.Responses.GenericApiResponse;
import com.group1.programminglanguagesforum.DTOs.Responses.GetTagDetailsResponseDto;
import com.group1.programminglanguagesforum.DTOs.Responses.TagDto;
import com.group1.programminglanguagesforum.DTOs.Responses.TagSearchResponseDto;
import com.group1.programminglanguagesforum.Entities.User;
import com.group1.programminglanguagesforum.Exceptions.ExceptionResponseHandler;
import com.group1.programminglanguagesforum.Exceptions.UnauthorizedAccessException;
import com.group1.programminglanguagesforum.Services.TagService;
import com.group1.programminglanguagesforum.Services.UserContextService;
import com.group1.programminglanguagesforum.Util.ApiResponseBuilder;

import jakarta.persistence.EntityExistsException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
Expand All @@ -20,11 +27,15 @@
import java.util.Arrays;
import java.util.NoSuchElementException;


@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1")
public class TagController extends BaseController {

private final TagService tagService;
private final UserContextService userContextService;

@GetMapping(value = EndpointConstants.TagEndpoints.SEARCH)
public ResponseEntity<GenericApiResponse<TagSearchResponseDto>> tagSearch(
@RequestParam String q,
Expand Down Expand Up @@ -107,4 +118,37 @@ public ResponseEntity<GenericApiResponse<GetTagDetailsResponseDto>> createTag(@R
}

}

@PostMapping(value = EndpointConstants.TagEndpoints.TAG_FOLLOW)
public ResponseEntity<GenericApiResponse<TagDto>> postMethodName(@PathVariable(value = "id") Long tagId) {
try {
User user = userContextService.getCurrentUser();
TagDto tagDto = tagService.followTag(user, tagId);
GenericApiResponse<TagDto> response = ApiResponseBuilder.buildSuccessResponse(TagDto.class, "Tag followed successfully", 200, tagDto);
return buildResponse(response, HttpStatus.OK);

} catch (UnauthorizedAccessException e) {
return ExceptionResponseHandler.UnauthorizedAccessException(e);
} catch (NoSuchElementException e) {
return ExceptionResponseHandler.NoSuchElementException(e);
} catch (EntityExistsException e) {
return ExceptionResponseHandler.EntityExistsException(e);
}
}

@DeleteMapping(value = EndpointConstants.TagEndpoints.TAG_FOLLOW)
public ResponseEntity<GenericApiResponse<TagDto>> deleteMethodName(@PathVariable(value = "id") Long tagId) {
try {
User user = userContextService.getCurrentUser();
TagDto tagDto = tagService.unfollowTag(user, tagId);
GenericApiResponse<TagDto> response = ApiResponseBuilder.buildSuccessResponse(TagDto.class, "Tag unfollowed successfully", 200, tagDto);
return buildResponse(response, HttpStatus.OK);

} catch (UnauthorizedAccessException e) {
return ExceptionResponseHandler.UnauthorizedAccessException(e);
} catch (NoSuchElementException e) {
return ExceptionResponseHandler.NoSuchElementException(e);
}
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.group1.programminglanguagesforum.Entities;

import java.util.HashSet;
import java.util.Set;

import jakarta.persistence.*;
import lombok.*;

Expand All @@ -18,6 +21,14 @@ public class Tag {
private String wikidataId;
private String tagName;
private String tagDescription;

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "USER_TAGS",
joinColumns = @JoinColumn(name = "tag_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private Set<User> followers = new HashSet<>();

public Tag(String wikidataId, String tagName, String tagDescription) {
this.wikidataId = wikidataId;
this.tagName = tagName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ public class User implements UserDetails {
private int followingCount = 0;
@Builder.Default
private Long reputationPoints = 0L;

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
name = "USER_TAGS",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
@Builder.Default
private Set<Tag> followedTags = new HashSet<>();

@OneToMany(mappedBy = "askedBy", cascade = CascadeType.ALL, orphanRemoval = true)
@Builder.Default
private List<Question> questions = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import com.group1.programminglanguagesforum.DTOs.Responses.GenericApiResponse;
import com.group1.programminglanguagesforum.DTOs.Responses.UserProfileResponseDto;
import com.group1.programminglanguagesforum.Util.ApiResponseBuilder;

import jakarta.persistence.EntityExistsException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

Expand Down Expand Up @@ -88,4 +91,43 @@ public static <T> ResponseEntity<GenericApiResponse<T>> NoSuchElementException(N
);

}

public static <T> ResponseEntity<GenericApiResponse<T>> IllegalArgumentException(IllegalArgumentException e) {
ErrorResponse errorResponse = ErrorResponse.builder()
.errorMessage(e.getMessage())
.stackTrace(Arrays.toString(e.getStackTrace()))
.build();

GenericApiResponse<T> response = ApiResponseBuilder.buildErrorResponse(
UserProfileResponseDto.class,
e.getMessage(),
HttpStatus.BAD_REQUEST.value(),
errorResponse
);

return new ResponseEntity<>(
response,
HttpStatus.valueOf(response.getStatus())
);
}

public static <T> ResponseEntity<GenericApiResponse<T>> EntityExistsException(EntityExistsException e) {
ErrorResponse errorResponse = ErrorResponse.builder()
.errorMessage(e.getMessage())
.stackTrace(Arrays.toString(e.getStackTrace()))
.build();

GenericApiResponse<T> response = ApiResponseBuilder.buildErrorResponse(
UserProfileResponseDto.class,
e.getMessage(),
HttpStatus.CONFLICT.value(),
errorResponse
);

return new ResponseEntity<>(
response,
HttpStatus.valueOf(response.getStatus())
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import com.group1.programminglanguagesforum.Entities.*;
import com.group1.programminglanguagesforum.Repositories.QuestionRepository;
import com.group1.programminglanguagesforum.Repositories.TagRepository;
import com.group1.programminglanguagesforum.Repositories.UserRepository;

import jakarta.persistence.EntityExistsException;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
Expand All @@ -21,6 +24,7 @@ public class TagService {
private final TagRepository tagRepository;
private final ModelMapper modelMapper;
private final QuestionRepository questionRepository;
private final UserRepository userRepository;

public List<Tag> findAllByIdIn(List<Long> tagIds) {
return tagRepository.findAllByIdIn(tagIds);
Expand Down Expand Up @@ -103,4 +107,49 @@ public Page<GetTagDetailsResponseDto> searchTags(String q, Pageable pageable) {
.tagType(getTagType(tag).toString())
.build());
}

public TagDto followTag(User user, Long tagId) {

Optional<Tag> tag = tagRepository.findById(tagId);
if (tag.isEmpty()) {
throw new NoSuchElementException("Tag not found");
}

Tag tagEntity = tag.get();

if (user.getFollowedTags().stream().anyMatch(t -> t.getId().equals(tagId))) {
throw new EntityExistsException("User already follows this tag");
}

user.getFollowedTags().add(tagEntity);
userRepository.save(user);

return TagDto.builder()
.id(tagEntity.getId())
.name(tagEntity.getTagName())
.build();
}

public TagDto unfollowTag(User user, Long tagId) {

Optional<Tag> tag = tagRepository.findById(tagId);
if (tag.isEmpty()) {
throw new NoSuchElementException("Tag not found");
}

Tag tagEntity = tag.get();

if (!user.getFollowedTags().stream().anyMatch(t -> t.getId().equals(tagId))) {
throw new NoSuchElementException("User does not follow this tag");
}

user.getFollowedTags().removeIf(t -> t.getId().equals(tagId));
userRepository.save(user);

return TagDto.builder()
.id(tagEntity.getId())
.name(tagEntity.getTagName())
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ void testCreateTag() {
.build();

// Mock the Tag returned by the repository save method
Tag savedTag = new Tag(1L, null, "New Tag", "Tag description");
Tag savedTag = new Tag(1L, null, "New Tag", "Tag description", null);

// Mock tagRepository behavior
when(tagRepository.save(any(Tag.class))).thenReturn(savedTag);
Expand All @@ -90,7 +90,7 @@ void testCreateTag() {
void testGetTagDetails_Success() {
Long tagId = 1L;

Tag mockTag = new Tag(1L, null, "Tag1", "Description1");
Tag mockTag = new Tag(1L, null, "Tag1", "Description1", null);
List<Question> mockQuestions = Arrays.asList(
new Question(1L, "Question1", "Body1", DifficultyLevel.EASY, 0L, 0L, null, null, null, null, null,null),
new Question(2L, "Question2", "Body2", DifficultyLevel.MEDIUM, 0L, 0L, null, null, null, null, null,null));
Expand Down
Loading