3
3
import com .example .polls .exception .BadRequestException ;
4
4
import com .example .polls .exception .ResourceNotFoundException ;
5
5
import com .example .polls .model .*;
6
- import com .example .polls .payload .Response .PagedResponse ;
7
6
import com .example .polls .payload .Request .PollRequest ;
8
- import com .example .polls .payload .Response .PollResponse ;
9
7
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 .* ;
13
11
import com .example .polls .security .UserPrincipal ;
14
12
import com .example .polls .util .AppConstants ;
15
13
import com .example .polls .util .ModelMapper ;
31
29
import java .util .function .Function ;
32
30
import java .util .stream .Collectors ;
33
31
32
+
34
33
@ Service
35
34
public class PollService {
36
35
@@ -44,36 +43,66 @@ public class PollService {
44
43
private UserRepository userRepository ;
45
44
46
45
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 ;
47
52
48
- public PagedResponse <PollResponse > getAllPolls (UserPrincipal currentUser , int page , int size ) {
49
- validatePageNumberAndSize (page , size );
50
-
51
- // Retrieve Polls
52
- Pageable pageable = PageRequest .of (page , size , Sort .Direction .DESC , "createdAt" );
53
- Page <Poll > polls = pollRepository .findAll (pageable );
54
53
54
+ private PagedResponse <PollResponse > mapPollPagetoPageResponse (UserPrincipal currentUser , Page <Poll > polls ) {
55
55
if (polls .getNumberOfElements () == 0 ) {
56
56
return new PagedResponse <>(Collections .emptyList (), polls .getNumber (),
57
57
polls .getSize (), polls .getTotalElements (), polls .getTotalPages (), polls .isLast ());
58
58
}
59
59
60
- // Map Polls to PollResponses containing vote counts and poll creator details
61
60
List <Long > pollIds = polls .map (Poll ::getId ).getContent ();
62
61
Map <Long , Long > choiceVoteCountMap = getChoiceVoteCountMap (pollIds );
63
62
Map <Long , Long > pollUserVoteMap = getPollUserVoteMap (currentUser , pollIds );
64
63
Map <Long , User > creatorMap = getPollCreatorMap (polls .getContent ());
65
64
66
- List <PollResponse > pollResponses = polls .map (poll -> {
67
- return ModelMapper . mapPollToPollResponse ( poll ,
68
- choiceVoteCountMap ,
69
- creatorMap .get (poll .getCreatedBy ()),
70
- pollUserVoteMap == null ? null : pollUserVoteMap .getOrDefault (poll .getId (), null ));
71
- } ).getContent ();
65
+ List <PollResponse > pollResponses = polls .map (poll -> ModelMapper . mapPollToPollResponse (
66
+ poll ,
67
+ choiceVoteCountMap ,
68
+ creatorMap .get (poll .getCreatedBy ()),
69
+ pollUserVoteMap == null ? null : pollUserVoteMap .getOrDefault (poll .getId (), null )
70
+ ) ).getContent ();
72
71
73
72
return new PagedResponse <>(pollResponses , polls .getNumber (),
74
73
polls .getSize (), polls .getTotalElements (), polls .getTotalPages (), polls .isLast ());
75
74
}
76
75
76
+
77
+ public PagedResponse <PollResponse > getAllPolls (UserPrincipal currentUser , int page , int size ) {
78
+ validatePageNumberAndSize (page , size );
79
+
80
+ // Retrieve Polls
81
+ Pageable pageable = PageRequest .of (page , size , Sort .Direction .DESC , "createdAt" );
82
+ Page <Poll > polls = pollRepository .findAll (pageable );
83
+
84
+ return mapPollPagetoPageResponse (currentUser , polls );
85
+ }
86
+
87
+ public PagedResponse <PollResponse > getAllPollsInGroup (Long groupId , UserPrincipal userPrincipal , int page , int size ) {
88
+ //그룹 유효성검사
89
+ Group group = groupRepository .findById (groupId )
90
+ .orElseThrow (() -> new ResourceNotFoundException ("Group" , "id" , groupId ));
91
+
92
+ //그룹 멤버 인증
93
+ if (!groupMemberRepository .existsByUserIdAndGroupId (userPrincipal .getId (), groupId )) {
94
+ throw new BadRequestException ("그룹에 가입된 사용자만 투표를 조회할 수 있습니다." );
95
+ }
96
+
97
+ //page 표시 정보 설정하기
98
+ Pageable pageable = PageRequest .of (page , size , Sort .by ("createdAt" ).descending ());
99
+ //결과 데이터 가져오기
100
+ Page <Poll > polls = pollRepository .findByGroupId (groupId , pageable );
101
+
102
+ return mapPollPagetoPageResponse (userPrincipal , polls );
103
+ }
104
+
105
+
77
106
public PagedResponse <PollResponse > getPollsCreatedBy (String username , UserPrincipal currentUser , int page , int size ) {
78
107
validatePageNumberAndSize (page , size );
79
108
@@ -143,29 +172,49 @@ public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipa
143
172
}
144
173
145
174
146
- public Poll createPoll (PollRequest pollRequest ) {
175
+ private Poll createPollInternal (PollRequest request , Long createdBy , Group group ) {
147
176
Poll poll = new Poll ();
148
- poll .setQuestion (pollRequest .getQuestion ());
177
+ poll .setQuestion (request .getQuestion ());
178
+
179
+ if (createdBy != null ) {
180
+ poll .setCreatedBy (createdBy );
181
+ }
182
+
183
+ if (group != null ) {
184
+ poll .setGroup (group );
185
+ }
149
186
150
- pollRequest .getChoices ().forEach (choiceRequest -> {
187
+ request .getChoices ().forEach (choiceRequest -> {
151
188
poll .addChoice (new Choice (choiceRequest .getText ()));
152
189
});
153
190
154
191
Instant now = Instant .now ();
155
- Instant expirationDateTime = now .plus (Duration .ofDays (pollRequest .getPollLength ().getDays ()))
156
- .plus (Duration .ofHours (pollRequest .getPollLength ().getHours ()));
157
-
192
+ Instant expirationDateTime = now .plus (Duration .ofDays (request .getPollLength ().getDays ()))
193
+ .plus (Duration .ofHours (request .getPollLength ().getHours ()));
158
194
poll .setExpirationDateTime (expirationDateTime );
159
195
160
196
return pollRepository .save (poll );
161
197
}
162
198
163
- public PollResponse getPollById ( Long pollId , UserPrincipal currentUser ) {
164
- Poll poll = pollRepository . findById ( pollId ). orElseThrow (
165
- () -> new ResourceNotFoundException ( "Poll" , "id" , pollId ));
199
+ public Poll createPoll ( PollRequest pollRequest ) {
200
+ return createPollInternal ( pollRequest , null , null );
201
+ }
166
202
167
- // Retrieve Vote Counts of every choice belonging to the current poll
168
- List <ChoiceVoteCount > votes = voteRepository .countByPollIdGroupByChoiceId (pollId );
203
+ //그룹 투표 생성
204
+ public Poll createPollInGroup (Long groupId , PollRequest request , UserPrincipal userPrincipal ) {
205
+ //그룹 엔티티 조회
206
+ Group group = groupRepository .findById (groupId )
207
+ .orElseThrow (() -> new ResourceNotFoundException ("Group" , "id" , groupId ));
208
+ boolean isMember = groupMemberRepository .existsByUserIdAndGroupId (userPrincipal .getId (), groupId );
209
+ if (!isMember ) {
210
+ throw new BadRequestException ("해당 그룹에 가입된 자만 투표할 수 있습니다." );
211
+ }
212
+ //저장
213
+ return createPollInternal (request , userPrincipal .getId (), group );
214
+ }
215
+
216
+ public PollResponse buildPollResponse (Poll poll , UserPrincipal currentUser ) {
217
+ List <ChoiceVoteCount > votes = voteRepository .countByPollIdGroupByChoiceId (poll .getId ());
169
218
170
219
Map <Long , Long > choiceVotesMap = votes .stream ()
171
220
.collect (Collectors .toMap (ChoiceVoteCount ::getChoiceId , ChoiceVoteCount ::getVoteCount ));
@@ -177,13 +226,38 @@ public PollResponse getPollById(Long pollId, UserPrincipal currentUser) {
177
226
// Retrieve vote done by logged in user
178
227
Vote userVote = null ;
179
228
if (currentUser != null ) {
180
- userVote = voteRepository .findByUserIdAndPollId (currentUser .getId (), pollId );
229
+ userVote = voteRepository .findByUserIdAndPollId (currentUser .getId (), poll . getId () );
181
230
}
182
231
183
232
return ModelMapper .mapPollToPollResponse (poll , choiceVotesMap ,
184
233
creator , userVote != null ? userVote .getChoice ().getId (): null );
185
234
}
186
235
236
+ public PollResponse getPollById (Long pollId , UserPrincipal currentUser ) {
237
+ Poll poll = pollRepository .findById (pollId ).orElseThrow (
238
+ () -> new ResourceNotFoundException ("Poll" , "id" , pollId ));
239
+
240
+ return buildPollResponse (poll , currentUser );
241
+ }
242
+
243
+ public PollResponse getPollByIdInGroup (Long pollId , Long groupId , UserPrincipal currentUser ) {
244
+ Group group = groupRepository .findById (groupId )
245
+ .orElseThrow (() -> new ResourceNotFoundException ("Group" , "id" , groupId ));
246
+ boolean isMember = groupMemberRepository .existsByUserIdAndGroupId (currentUser .getId (), groupId );
247
+ if (!isMember ) {
248
+ throw new BadRequestException ("해당 그룹에 가입된 사용자만 투표를 조회할 수 있습니다." );
249
+ }
250
+
251
+ Poll poll = pollRepository .findById (pollId ).orElseThrow (
252
+ () -> new ResourceNotFoundException ("Poll" , "id" , pollId )
253
+ );
254
+ if (poll .getGroup () != null && !poll .getGroup ().getId ().equals (groupId )) {
255
+ throw new BadRequestException ("해당 투표는 요청한 그룹에 속하지 않습니다." );
256
+ }
257
+
258
+ return buildPollResponse (poll , currentUser );
259
+ }
260
+
187
261
public PollResponse castVoteAndGetUpdatedPoll (Long pollId , VoteRequest voteRequest , UserPrincipal currentUser ) {
188
262
Poll poll = pollRepository .findById (pollId )
189
263
.orElseThrow (() -> new ResourceNotFoundException ("Poll" , "id" , pollId ));
0 commit comments