Skip to content

Commit 4841b43

Browse files
committed
그룹 내 투표 목록 조회 api
1 parent 1d9dfc6 commit 4841b43

File tree

5 files changed

+135
-5
lines changed

5 files changed

+135
-5
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.example.polls.controller;
2+
3+
import com.example.polls.payload.Request.PollRequest;
4+
import com.example.polls.payload.Response.ApiResponse;
5+
import com.example.polls.payload.Response.PagedResponse;
6+
import com.example.polls.payload.Response.PollResponse;
7+
import com.example.polls.security.CurrentUser;
8+
import com.example.polls.security.UserPrincipal;
9+
import com.example.polls.service.GroupService;
10+
import com.example.polls.service.PollService;
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.http.ResponseEntity;
13+
import org.springframework.web.bind.annotation.*;
14+
15+
import javax.validation.Valid;
16+
17+
@RestController
18+
@RequestMapping("/api/groups/{groupId}/polls")
19+
public class GroupPollController {
20+
@Autowired
21+
private PollService pollService;
22+
@Autowired
23+
private GroupService groupService;
24+
25+
@PostMapping
26+
public ResponseEntity<?> createPollInGroup (@PathVariable Long groupId,
27+
@CurrentUser UserPrincipal currentUser,
28+
@Valid @RequestBody PollRequest request) {
29+
groupService.validateGroupMember(groupId, currentUser.getId());
30+
pollService.createPollInGroup(groupId, request, currentUser);
31+
return ResponseEntity.ok(new ApiResponse(true, "Poll Created Successfully"));
32+
}
33+
34+
@GetMapping
35+
public ResponseEntity<PagedResponse<PollResponse>> getAllPollInGroup(@PathVariable Long groupId,
36+
@CurrentUser UserPrincipal userPrincipal,
37+
@RequestParam(value = "page", defaultValue="0") int page,
38+
@RequestParam(value = "size", defaultValue="10") int size){
39+
PagedResponse<PollResponse> response = pollService.getAllPollsInGroup(groupId, userPrincipal, page, size);
40+
return ResponseEntity.ok(response);
41+
}
42+
43+
}

polling-app-server/src/main/java/com/example/polls/model/Poll.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,13 @@ public class Poll extends UserDateAudit {
4141
@JoinColumn(name = "group_id", nullable = false)
4242
private Group group;
4343

44+
public Group getGroup() {
45+
return group;
46+
}
4447

48+
public void setGroup(Group group) {
49+
this.group = group;
50+
}
4551

4652
public Long getId() {
4753
return id;

polling-app-server/src/main/java/com/example/polls/repository/PollRepository.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,6 @@ public interface PollRepository extends JpaRepository<Poll, Long> {
2222
List<Poll> findByIdIn(List<Long> pollIds);
2323

2424
List<Poll> findByIdIn(List<Long> pollIds, Sort sort);
25+
26+
Page<Poll> findByGroupId(Long groupId, Pageable pageable);
2527
}

polling-app-server/src/main/java/com/example/polls/service/GroupService.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,10 @@ public GroupDetailResponse getGroupDetail(Long groupId, Long userId) {
124124
return new GroupDetailResponse(group.getId(),group.getName(),group.getImageUrl(),members);
125125

126126
}
127+
128+
public void validateGroupMember(Long groupId, Long userId){
129+
if(!groupMemberRepository.existsByUserIdAndGroupId(userId, groupId)){
130+
throw new BadRequestException("해당 그룹에 소속되지 않았습니다.");
131+
}
132+
}
127133
}

polling-app-server/src/main/java/com/example/polls/service/PollService.java

Lines changed: 78 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@
33
import com.example.polls.exception.BadRequestException;
44
import com.example.polls.exception.ResourceNotFoundException;
55
import com.example.polls.model.*;
6-
import com.example.polls.payload.Response.PagedResponse;
76
import com.example.polls.payload.Request.PollRequest;
8-
import com.example.polls.payload.Response.PollResponse;
97
import com.example.polls.payload.Request.VoteRequest;
10-
import com.example.polls.repository.PollRepository;
11-
import com.example.polls.repository.UserRepository;
12-
import com.example.polls.repository.VoteRepository;
8+
import com.example.polls.payload.Response.PagedResponse;
9+
import com.example.polls.payload.Response.PollResponse;
10+
import com.example.polls.repository.*;
1311
import com.example.polls.security.UserPrincipal;
1412
import com.example.polls.util.AppConstants;
1513
import com.example.polls.util.ModelMapper;
@@ -31,6 +29,7 @@
3129
import java.util.function.Function;
3230
import java.util.stream.Collectors;
3331

32+
3433
@Service
3534
public class PollService {
3635

@@ -44,6 +43,13 @@ public class PollService {
4443
private UserRepository userRepository;
4544

4645
private static final Logger logger = LoggerFactory.getLogger(PollService.class);
46+
@Autowired
47+
private GroupRepository groupRepository;
48+
@Autowired
49+
private GroupService groupService;
50+
@Autowired
51+
private GroupMemberRepository groupMemberRepository;
52+
4753

4854
public PagedResponse<PollResponse> getAllPolls(UserPrincipal currentUser, int page, int size) {
4955
validatePageNumberAndSize(page, size);
@@ -74,6 +80,45 @@ public PagedResponse<PollResponse> getAllPolls(UserPrincipal currentUser, int pa
7480
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
7581
}
7682

83+
public PagedResponse<PollResponse> getAllPollsInGroup(Long groupId, UserPrincipal userPrincipal, int page, int size) {
84+
//그룹 유효성검사
85+
Group group = groupRepository.findById(groupId)
86+
.orElseThrow(() -> new ResourceNotFoundException("Group", "id", groupId));
87+
88+
//그룹 멤버 인증
89+
if(!groupMemberRepository.existsByUserIdAndGroupId(userPrincipal.getId(), groupId)) {
90+
throw new BadRequestException("그룹에 가입된 사용자만 투표를 조회할 수 있습니다.");
91+
}
92+
93+
//page 표시 정보 설정하기
94+
Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
95+
//결과 데이터 가져오기
96+
Page<Poll> polls = pollRepository.findByGroupId(groupId, pageable);
97+
98+
if(polls.getNumberOfElements() == 0) {
99+
return new PagedResponse<>(Collections.emptyList(), polls.getNumber(),
100+
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
101+
}
102+
103+
// Map Polls to PollResponses containing vote counts and poll creator details
104+
List<Long> pollIds = polls.map(Poll::getId).getContent();
105+
Map<Long, Long> choiceVoteCountMap = getChoiceVoteCountMap(pollIds);
106+
Map<Long, Long> pollUserVoteMap = getPollUserVoteMap(userPrincipal, pollIds);
107+
Map<Long, User> creatorMap = getPollCreatorMap(polls.getContent());
108+
109+
110+
List<PollResponse> pollResponses = polls.map(poll -> {
111+
return ModelMapper.mapPollToPollResponse(poll,
112+
choiceVoteCountMap,
113+
creatorMap.get(poll.getCreatedBy()),
114+
pollUserVoteMap == null ? null : pollUserVoteMap.getOrDefault(poll.getId(), null));
115+
}).getContent();
116+
117+
return new PagedResponse<>(pollResponses, polls.getNumber(),
118+
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
119+
120+
}
121+
77122
public PagedResponse<PollResponse> getPollsCreatedBy(String username, UserPrincipal currentUser, int page, int size) {
78123
validatePageNumberAndSize(page, size);
79124

@@ -160,6 +205,34 @@ public Poll createPoll(PollRequest pollRequest) {
160205
return pollRepository.save(poll);
161206
}
162207

208+
//그룹 투표 생성
209+
public Poll createPollInGroup(Long groupId, PollRequest request, UserPrincipal userPrincipal) {
210+
//그룹 엔티티 조회
211+
Group group = groupRepository.findById(groupId)
212+
.orElseThrow(() -> new ResourceNotFoundException("Group", "id", groupId));
213+
//투표 객체 생성
214+
Poll poll = new Poll();
215+
poll.setQuestion(request.getQuestion());
216+
poll.setGroup(group);
217+
poll.setCreatedBy(userPrincipal.getId());
218+
219+
//선택지 추가
220+
request.getChoices().forEach(choiceRequest -> {
221+
poll.addChoice(new Choice(choiceRequest.getText()));
222+
});
223+
224+
//종료시간 계산
225+
Instant now = Instant.now();
226+
Instant expirationDateTime = now.plus(Duration.ofDays(request.getPollLength().getDays()))
227+
.plus(Duration.ofHours(request.getPollLength().getHours()));
228+
poll.setExpirationDateTime(expirationDateTime);
229+
230+
231+
//저장
232+
return pollRepository.save(poll);
233+
}
234+
235+
163236
public PollResponse getPollById(Long pollId, UserPrincipal currentUser) {
164237
Poll poll = pollRepository.findById(pollId).orElseThrow(
165238
() -> new ResourceNotFoundException("Poll", "id", pollId));

0 commit comments

Comments
 (0)