@@ -50,36 +50,38 @@ public class PollService {
50
50
@ Autowired
51
51
private GroupMemberRepository groupMemberRepository ;
52
52
53
-
54
- public PagedResponse <PollResponse > getAllPolls (UserPrincipal currentUser , int page , int size ) {
55
- validatePageNumberAndSize (page , size );
56
-
57
- // Retrieve Polls
58
- Pageable pageable = PageRequest .of (page , size , Sort .Direction .DESC , "createdAt" );
59
- Page <Poll > polls = pollRepository .findAll (pageable );
60
-
53
+ private PagedResponse <PollResponse > mapPollPagetoPageResponse (UserPrincipal currentUser , Page <Poll > polls ) {
61
54
if (polls .getNumberOfElements () == 0 ) {
62
55
return new PagedResponse <>(Collections .emptyList (), polls .getNumber (),
63
56
polls .getSize (), polls .getTotalElements (), polls .getTotalPages (), polls .isLast ());
64
57
}
65
58
66
- // Map Polls to PollResponses containing vote counts and poll creator details
67
59
List <Long > pollIds = polls .map (Poll ::getId ).getContent ();
68
60
Map <Long , Long > choiceVoteCountMap = getChoiceVoteCountMap (pollIds );
69
61
Map <Long , Long > pollUserVoteMap = getPollUserVoteMap (currentUser , pollIds );
70
62
Map <Long , User > creatorMap = getPollCreatorMap (polls .getContent ());
71
63
72
- List <PollResponse > pollResponses = polls .map (poll -> {
73
- return ModelMapper . mapPollToPollResponse ( poll ,
74
- choiceVoteCountMap ,
75
- creatorMap .get (poll .getCreatedBy ()),
76
- pollUserVoteMap == null ? null : pollUserVoteMap .getOrDefault (poll .getId (), null ));
77
- } ).getContent ();
64
+ List <PollResponse > pollResponses = polls .map (poll -> ModelMapper . mapPollToPollResponse (
65
+ poll ,
66
+ choiceVoteCountMap ,
67
+ creatorMap .get (poll .getCreatedBy ()),
68
+ pollUserVoteMap == null ? null : pollUserVoteMap .getOrDefault (poll .getId (), null )
69
+ ) ).getContent ();
78
70
79
71
return new PagedResponse <>(pollResponses , polls .getNumber (),
80
72
polls .getSize (), polls .getTotalElements (), polls .getTotalPages (), polls .isLast ());
81
73
}
82
74
75
+ public PagedResponse <PollResponse > getAllPolls (UserPrincipal currentUser , int page , int size ) {
76
+ validatePageNumberAndSize (page , size );
77
+
78
+ // Retrieve Polls
79
+ Pageable pageable = PageRequest .of (page , size , Sort .Direction .DESC , "createdAt" );
80
+ Page <Poll > polls = pollRepository .findAll (pageable );
81
+
82
+ return mapPollPagetoPageResponse (currentUser , polls );
83
+ }
84
+
83
85
public PagedResponse <PollResponse > getAllPollsInGroup (Long groupId , UserPrincipal userPrincipal , int page , int size ) {
84
86
//그룹 유효성검사
85
87
Group group = groupRepository .findById (groupId )
@@ -95,28 +97,7 @@ public PagedResponse<PollResponse> getAllPollsInGroup(Long groupId, UserPrincipa
95
97
//결과 데이터 가져오기
96
98
Page <Poll > polls = pollRepository .findByGroupId (groupId , pageable );
97
99
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
-
100
+ return mapPollPagetoPageResponse (userPrincipal , polls );
120
101
}
121
102
122
103
public PagedResponse <PollResponse > getPollsCreatedBy (String username , UserPrincipal currentUser , int page , int size ) {
@@ -188,57 +169,50 @@ public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipa
188
169
}
189
170
190
171
191
- public Poll createPoll (PollRequest pollRequest ) {
172
+ private Poll createPollInternal (PollRequest request , Long createdBy , Group group ) {
192
173
Poll poll = new Poll ();
193
- poll .setQuestion (pollRequest .getQuestion ());
194
-
195
- pollRequest .getChoices ().forEach (choiceRequest -> {
196
- poll .addChoice (new Choice (choiceRequest .getText ()));
197
- });
198
-
199
- Instant now = Instant .now ();
200
- Instant expirationDateTime = now .plus (Duration .ofDays (pollRequest .getPollLength ().getDays ()))
201
- .plus (Duration .ofHours (pollRequest .getPollLength ().getHours ()));
174
+ poll .setQuestion (request .getQuestion ());
202
175
203
- poll .setExpirationDateTime (expirationDateTime );
204
-
205
- return pollRepository .save (poll );
206
- }
176
+ if (createdBy != null ) {
177
+ poll .setCreatedBy (createdBy );
178
+ }
207
179
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 ());
180
+ if (group != null ) {
216
181
poll .setGroup (group );
217
- poll . setCreatedBy ( userPrincipal . getId ());
182
+ }
218
183
219
- //선택지 추가
220
184
request .getChoices ().forEach (choiceRequest -> {
221
185
poll .addChoice (new Choice (choiceRequest .getText ()));
222
186
});
223
187
224
- //종료시간 계산
225
188
Instant now = Instant .now ();
226
189
Instant expirationDateTime = now .plus (Duration .ofDays (request .getPollLength ().getDays ()))
227
190
.plus (Duration .ofHours (request .getPollLength ().getHours ()));
228
191
poll .setExpirationDateTime (expirationDateTime );
229
192
230
-
231
- //저장
232
193
return pollRepository .save (poll );
233
194
}
234
195
235
196
236
- public PollResponse getPollById ( Long pollId , UserPrincipal currentUser ) {
237
- Poll poll = pollRepository . findById ( pollId ). orElseThrow (
238
- () -> new ResourceNotFoundException ( "Poll" , "id" , pollId ));
197
+ public Poll createPoll ( PollRequest pollRequest ) {
198
+ return createPollInternal ( pollRequest , null , null );
199
+ }
239
200
240
- // Retrieve Vote Counts of every choice belonging to the current poll
241
- List <ChoiceVoteCount > votes = voteRepository .countByPollIdGroupByChoiceId (pollId );
201
+ //그룹 투표 생성
202
+ public Poll createPollInGroup (Long groupId , PollRequest request , UserPrincipal userPrincipal ) {
203
+ //그룹 엔티티 조회
204
+ Group group = groupRepository .findById (groupId )
205
+ .orElseThrow (() -> new ResourceNotFoundException ("Group" , "id" , groupId ));
206
+ boolean isMember = groupMemberRepository .existsByUserIdAndGroupId (userPrincipal .getId (), groupId );
207
+ if (!isMember ) {
208
+ throw new BadRequestException ("해당 그룹에 가입된 자만 투표할 수 있습니다." );
209
+ }
210
+ //저장
211
+ return createPollInternal (request , userPrincipal .getId (), group );
212
+ }
213
+
214
+ public PollResponse buildPollResponse (Poll poll , UserPrincipal currentUser ) {
215
+ List <ChoiceVoteCount > votes = voteRepository .countByPollIdGroupByChoiceId (poll .getId ());
242
216
243
217
Map <Long , Long > choiceVotesMap = votes .stream ()
244
218
.collect (Collectors .toMap (ChoiceVoteCount ::getChoiceId , ChoiceVoteCount ::getVoteCount ));
@@ -250,13 +224,38 @@ public PollResponse getPollById(Long pollId, UserPrincipal currentUser) {
250
224
// Retrieve vote done by logged in user
251
225
Vote userVote = null ;
252
226
if (currentUser != null ) {
253
- userVote = voteRepository .findByUserIdAndPollId (currentUser .getId (), pollId );
227
+ userVote = voteRepository .findByUserIdAndPollId (currentUser .getId (), poll . getId () );
254
228
}
255
229
256
230
return ModelMapper .mapPollToPollResponse (poll , choiceVotesMap ,
257
231
creator , userVote != null ? userVote .getChoice ().getId (): null );
258
232
}
259
233
234
+ public PollResponse getPollById (Long pollId , UserPrincipal currentUser ) {
235
+ Poll poll = pollRepository .findById (pollId ).orElseThrow (
236
+ () -> new ResourceNotFoundException ("Poll" , "id" , pollId ));
237
+
238
+ return buildPollResponse (poll , currentUser );
239
+ }
240
+
241
+ public PollResponse getPollByIdInGroup (Long pollId , Long groupId , UserPrincipal currentUser ) {
242
+ Group group = groupRepository .findById (groupId )
243
+ .orElseThrow (() -> new ResourceNotFoundException ("Group" , "id" , groupId ));
244
+ boolean isMember = groupMemberRepository .existsByUserIdAndGroupId (currentUser .getId (), groupId );
245
+ if (!isMember ) {
246
+ throw new BadRequestException ("해당 그룹에 가입된 사용자만 투표를 조회할 수 있습니다." );
247
+ }
248
+
249
+ Poll poll = pollRepository .findById (pollId ).orElseThrow (
250
+ () -> new ResourceNotFoundException ("Poll" , "id" , pollId )
251
+ );
252
+ if (poll .getGroup () != null && !poll .getGroup ().getId ().equals (groupId )) {
253
+ throw new BadRequestException ("해당 투표는 요청한 그룹에 속하지 않습니다." );
254
+ }
255
+
256
+ return buildPollResponse (poll , currentUser );
257
+ }
258
+
260
259
public PollResponse castVoteAndGetUpdatedPoll (Long pollId , VoteRequest voteRequest , UserPrincipal currentUser ) {
261
260
Poll poll = pollRepository .findById (pollId )
262
261
.orElseThrow (() -> new ResourceNotFoundException ("Poll" , "id" , pollId ));
0 commit comments