This repository was archived by the owner on Jan 11, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStudyPostCommandServiceImpl.java
More file actions
731 lines (604 loc) · 37.5 KB
/
StudyPostCommandServiceImpl.java
File metadata and controls
731 lines (604 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
package com.example.spot.service.studypost;
import com.example.spot.api.code.status.ErrorStatus;
import com.example.spot.api.exception.handler.MemberHandler;
import com.example.spot.api.exception.handler.StudyHandler;
import com.example.spot.domain.Member;
import com.example.spot.domain.Notification;
import com.example.spot.domain.enums.ApplicationStatus;
import com.example.spot.domain.enums.NotifyType;
import com.example.spot.domain.mapping.MemberStudy;
import com.example.spot.domain.mapping.StudyLikedComment;
import com.example.spot.domain.mapping.StudyLikedPost;
import com.example.spot.domain.mapping.StudyPostImage;
import com.example.spot.domain.study.Study;
import com.example.spot.domain.study.StudyPost;
import com.example.spot.domain.study.StudyPostComment;
import com.example.spot.repository.*;
import com.example.spot.security.utils.SecurityUtils;
import com.example.spot.service.s3.S3ImageService;
import com.example.spot.web.dto.memberstudy.request.StudyPostCommentRequestDTO;
import com.example.spot.web.dto.memberstudy.request.StudyPostRequestDTO;
import com.example.spot.web.dto.memberstudy.response.StudyPostCommentResponseDTO;
import com.example.spot.web.dto.memberstudy.response.StudyPostResDTO;
import com.example.spot.web.dto.util.response.ImageResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
@RequiredArgsConstructor
public class StudyPostCommandServiceImpl implements StudyPostCommandService {
@Value("${image.post.anonymous.profile}")
private String defaultImage;
private final MemberRepository memberRepository;
private final StudyRepository studyRepository;
private final MemberStudyRepository memberStudyRepository;
private final StudyPostRepository studyPostRepository;
private final StudyPostImageRepository studyPostImageRepository;
private final StudyPostCommentRepository studyPostCommentRepository;
private final StudyLikedPostRepository studyLikedPostRepository;
private final StudyLikedCommentRepository studyLikedCommentRepository;
private final StudyPostReportRepository studyPostReportRepository;
private final NotificationRepository notificationRepository;
// S3 Service
private final S3ImageService s3ImageService;
/* ----------------------------- 스터디 게시글 관련 API ------------------------------------- */
/**
* 스터디 내부 게시판에 게시글을 작성하는 메서드입니다.
* @param studyId 게시글을 작성할 타겟 스터디의 아이디를 입력 받습니다.
* @param postRequestDTO 게시글의 입력 형식(StudyPostRequestDTO.PostDTO)에 맞추어 게시글 정보를 입력 받습니다.
* @return 작성된 스터디 게시글의 Preview(게시글 아이디, 제목)를 반환합니다.
*/
@Override
public StudyPostResDTO.PostPreviewDTO createPost(Long studyId, StudyPostRequestDTO.PostDTO postRequestDTO) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
Study study = studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 스터디장만 공지 가능
MemberStudy memberStudy = memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
if (!memberStudy.getIsOwned() && postRequestDTO.getIsAnnouncement()) {
throw new StudyHandler(ErrorStatus._STUDY_POST_ANNOUNCEMENT_INVALID);
}
//=== Feature ===//
StudyPost studyPost = StudyPost.builder()
.isAnnouncement(postRequestDTO.getIsAnnouncement())
.theme(postRequestDTO.getTheme())
.title(postRequestDTO.getTitle())
.content(postRequestDTO.getContent())
.likeNum(0)
.hitNum(0)
.commentNum(0)
.member(member)
.study(study)
.build();
// 공지면 announcedAt 설정
if (studyPost.getIsAnnouncement()) {
studyPost.setAnnouncedAt(LocalDateTime.now());
}
studyPost = studyPostRepository.save(studyPost);
member.addStudyPost(studyPost);
study.addStudyPost(studyPost);
// 이미지가 있는 경우 이미지 저장
if (postRequestDTO.getImage() != null) {
String imageUrl = s3ImageService.upload(postRequestDTO.getImage());
StudyPostImage studyPostImage = StudyPostImage.builder()
.url(imageUrl)
.studyPost(studyPost)
.build();
studyPostImage = studyPostImageRepository.save(studyPostImage);
studyPost.addImage(studyPostImage);
}
if (studyPost.getIsAnnouncement()){
// 스터디에 참여중인 회원들에게 알림 전송 위해 회원 조회
List<Member> members = memberStudyRepository.findAllByStudyIdAndStatus(
studyPost.getStudy().getId(), ApplicationStatus.APPROVED).stream()
.map(MemberStudy::getMember)
.toList();
if (members.isEmpty())
throw new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND);
// 알림 생성
for (Member studyMember : members) {
Notification notification = Notification.builder()
.study(studyPost.getStudy())
.member(studyMember)
.studyPostId(studyPost.getId())
.notifierName(member.getName()) // 글을 작성한 회원 이름
.type(NotifyType.ANNOUNCEMENT)
.isChecked(false)
.build();
notificationRepository.save(notification);
}
}
member.updateStudyPost(studyPost);
study.updateStudyPost(studyPost);
return StudyPostResDTO.PostPreviewDTO.toDTO(studyPost);
}
@Override
public StudyPostResDTO.PostPreviewDTO updatePost(Long studyId, Long postId, StudyPostRequestDTO.PostDTO postDTO) {
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPost studyPost = studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
MemberStudy memberStudy = memberStudyRepository.findByMemberIdAndStudyIdAndStatus(memberId, studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 로그인한 회원이 게시글 작성자인지 확인
studyPostRepository.findByIdAndMemberId(postId, memberId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_UPDATE_INVALID));
// 스터디장만 공지 가능
if (!memberStudy.getIsOwned() && postDTO.getIsAnnouncement()) {
throw new StudyHandler(ErrorStatus._STUDY_POST_ANNOUNCEMENT_INVALID);
}
// 스터디 게시글 이미지 업데이트
updateStudyPostImage(postDTO, studyPost);
// 스터디 게시글 업데이트
studyPost.updatePost(postDTO);
return StudyPostResDTO.PostPreviewDTO.toDTO(studyPost);
}
private void updateStudyPostImage(StudyPostRequestDTO.PostDTO postDTO, StudyPost studyPost) {
List<StudyPostImage> studyPostImages = studyPost.getImages();
// 기존 이미지가 존재하는 경우 이미지 유지
if (!StringUtils.hasText(postDTO.getExistingImage())) {
// 기존 이미지가 없고 새로운 이미지를 등록한 경우 이미지 url 변경
if (postDTO.getImage() != null) {
String imageUrl = s3ImageService.upload(postDTO.getImage());
studyPostImages.forEach(studyPostImage -> {
studyPostImage.setUrl(imageUrl);
studyPost.updateImage(studyPostImage);
});
}
}
}
/**
* 스터디 내부 게시판에 작성된 게시글을 삭제합니다.
* @param studyId 게시글을 삭제할 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 삭제할 스터디 게시글의 아이디를 입력 받습니다.
* @return 삭제된 스터디 게시글의 Preview(게시글 아이디, 제목)를 반환합니다.
*/
@Override
public StudyPostResDTO.PostPreviewDTO deletePost(Long studyId, Long postId) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
Study study = studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPost studyPost = studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 해당 스터디의 게시글인지 확인
studyPostRepository.findByIdAndStudyId(postId, studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인 회원이 게시글 작성자거나 owner인지 확인
Long ownerId = studyPost.getStudy().getMemberStudies().stream()
.filter(MemberStudy::getIsOwned)
.map(memberStudy -> memberStudy.getMember().getId())
.findFirst()
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_OWNER_NOT_FOUND));
if (studyPost.getMember().getId().equals(memberId) ||
memberId.equals(ownerId)) {
studyPostImageRepository.deleteAllByStudyPostId(postId);
studyPostCommentRepository.deleteAllByStudyPostId(postId);
studyLikedPostRepository.deleteAllByStudyPostId(postId);
studyPostReportRepository.deleteAllByStudyPostId(postId);
member.deleteStudyPost(studyPost);
study.deleteStudyPost(studyPost);
studyPostRepository.delete(studyPost);
} else {
throw new StudyHandler(ErrorStatus._STUDY_POST_DELETION_INVALID);
}
return StudyPostResDTO.PostPreviewDTO.toDTO(studyPost);
}
/**
* 스터디 내부 게시판에 작성된 게시글에 좋아요를 누르는 메서드입니다.
* 게시글에 좋아요를 누른 회원의 정보가 StudyLikedPost에 저장되고 스터디 게시글의 좋아요 개수가 업데이트 됩니다.
* @param studyId 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 좋아요를 누를 타겟 게시글의 아이디를 입력 받습니다.
* @return 게시글의 Preview(게시글 아이디, 제목)와 함께 좋아요 개수가 반환됩니다.
*/
@Override
public StudyPostResDTO.PostLikeNumDTO likePost(Long studyId, Long postId) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPost studyPost = studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 해당 스터디의 게시글인지 확인
studyPostRepository.findByIdAndStudyId(postId, studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 이미 좋아요를 눌렀다면 다시 좋아요 할 수 없음
if (studyLikedPostRepository.findByMemberIdAndStudyPostId(memberId, postId).isPresent()) {
throw new StudyHandler(ErrorStatus._STUDY_POST_ALREADY_LIKED);
}
//=== Feature ===//
StudyLikedPost studyLikedPost = StudyLikedPost.builder()
.member(member)
.studyPost(studyPost)
.build();
studyLikedPost = studyLikedPostRepository.save(studyLikedPost);
member.addStudyLikedPost(studyLikedPost);
studyPost.addLikedPost(studyLikedPost);
studyPost.plusLikeNum();
studyPost = studyPostRepository.save(studyPost);
return StudyPostResDTO.PostLikeNumDTO.toDTO(studyPost);
}
/**
* 스터디 내부 게시판에 작성된 게시글에 누른 좋아요를 취소하는 메서드입니다.
* 게시글에 좋아요를 누른 회원의 정보가 StudyLikedPost에서 삭제되고 스터디 게시글의 좋아요 개수가 업데이트 됩니다.
* @param studyId 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 좋아요를 취소할 타겟 게시글의 아이디를 입력 받습니다.
* @return 게시글의 Preview(게시글 아이디, 제목)와 함께 좋아요 개수가 반환됩니다.
*/
@Override
public StudyPostResDTO.PostLikeNumDTO cancelPostLike(Long studyId, Long postId) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPost studyPost = studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 해당 스터디의 게시글인지 확인
studyPostRepository.findByIdAndStudyId(postId, studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
//=== Feature ===//
StudyLikedPost studyLikedPost = studyLikedPostRepository.findByMemberIdAndStudyPostId(memberId, postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_LIKED_POST_NOT_FOUND));
member.deleteStudyLikedPost(studyLikedPost);
studyPost.deleteLikedPost(studyLikedPost);
studyPost.minusLikeNum();
studyLikedPostRepository.delete(studyLikedPost);
studyPostRepository.save(studyPost);
return StudyPostResDTO.PostLikeNumDTO.toDTO(studyPost);
}
/* ----------------------------- 스터디 게시글 댓글 관련 API ------------------------------------- */
/**
* 스터디 게시글에 댓글을 추가하는 메서드입니다. 답글 추가 메서드는 하단에 별도로 구현되어 있습니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디를 입력 받습니다.
* @param postId 댓글을 추가할 스터디 게시글의 아이디를 입력 받습니다.
* @param commentRequestDTO 추가할 댓글(내용, 익명 여부)을 입력 받습니다.
* @return 댓글 아이디와 작성자, 내용, 좋아요와 싫어요 개수를 함께 반환합니다.
*/
@Override
public StudyPostCommentResponseDTO.CommentDTO createComment(Long studyId, Long postId, StudyPostCommentRequestDTO.CommentDTO commentRequestDTO) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPost studyPost = studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 해당 스터디의 게시글인지 확인
studyPostRepository.findByIdAndStudyId(postId, studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
//=== Feature ===//
Integer anonymousNum = getAnonymousNum(postId, commentRequestDTO, member);
StudyPostComment studyPostComment = StudyPostComment.builder()
.studyPost(studyPost)
.member(member)
.content(commentRequestDTO.getContent())
.likeCount(0)
.dislikeCount(0)
.isAnonymous(commentRequestDTO.getIsAnonymous())
.parentComment(null)
.isDeleted(false)
.anonymousNum(anonymousNum)
.build();
studyPostCommentRepository.save(studyPostComment);
studyPost.setCommentNum(studyPostCommentRepository.findAllByStudyPostId(postId).size());
studyPostRepository.save(studyPost);
studyPost.addComment(studyPostComment);
member.addComment(studyPostComment);
return StudyPostCommentResponseDTO.CommentDTO.toDTO(studyPostComment, "익명"+anonymousNum, defaultImage);
}
/**
* 스터디 게시글에 답글을 추가하는 메서드입니다. 댓글 추가 메서드는 상단에 별도로 구현되어 있습니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디를 입력 받습니다.
* @param postId 댓글을 추가할 스터디 게시글의 아이디를 입력 받습니다.
* @param commentRequestDTO 추가할 댓글(내용, 익명 여부)을 입력 받습니다.
* @return 댓글 아이디와 작성자, 내용, 좋아요와 싫어요 개수를 함께 반환합니다.
*/
@Override
public StudyPostCommentResponseDTO.CommentDTO createReply(Long studyId, Long postId, Long commentId, StudyPostCommentRequestDTO.CommentDTO commentRequestDTO) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPost studyPost = studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 해당 스터디의 게시글인지 확인
studyPostRepository.findByIdAndStudyId(postId, studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 부모 댓글이 존재하는지 확인
StudyPostComment parentComment = studyPostCommentRepository.findById(commentId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_NOT_FOUND));
//=== Feature ===//
Integer anonymousNum = getAnonymousNum(postId, commentRequestDTO, member);
StudyPostComment studyPostComment = StudyPostComment.builder()
.studyPost(studyPost)
.member(member)
.content(commentRequestDTO.getContent())
.likeCount(0)
.dislikeCount(0)
.isAnonymous(commentRequestDTO.getIsAnonymous())
.anonymousNum(anonymousNum)
.parentComment(parentComment)
.isDeleted(false)
.build();
studyPostCommentRepository.save(studyPostComment);
studyPost.setCommentNum(studyPostCommentRepository.findAllByStudyPostId(postId).size());
studyPostRepository.save(studyPost);
studyPost.addComment(studyPostComment);
member.addComment(studyPostComment);
parentComment.addChildrenComment(studyPostComment);
return StudyPostCommentResponseDTO.CommentDTO.toDTO(studyPostComment, "익명"+anonymousNum, defaultImage);
}
/**
* 스터디 게시글 댓글마다 익명 번호를 부여하는 메서드입니다.
* 회원이 이미 타겟 스터디 게시글에 익명으로 댓글을 작성한 이력이 있는 경우 해당 번호를 반환합니다.
* @param postId 댓글을 작성할 타겟 스터디 게시글의 아이디를 입력 받습니다.
* @param commentRequestDTO 추가할 댓글(내용, 익명 여부)을 입력 받습니다.
* @param member 댓글 작성자를 입력 받습니다.
* @return 댓글 작성자의 익명 번호를 반환합니다.
* 회원이 이미 타겟 스터디 게시글에 익명으로 댓글을 작성한 이력이 있는 경우 해당 번호를 반환합니다.
*/
private Integer getAnonymousNum(Long postId, StudyPostCommentRequestDTO.CommentDTO commentRequestDTO, Member member) {
Integer anonymousNum = null;
List<StudyPostComment> studyPostComments = studyPostCommentRepository.findAllByStudyPostId(postId);
List<StudyPostComment> myStudyPostComments = studyPostCommentRepository.findAllByMemberIdAndStudyPostId(member.getId(), postId);
// 회원이 익명 댓글을 요청할 경우 anonymousNum 부여
if (commentRequestDTO.getIsAnonymous()) {
// anonymousNum의 (최댓값+1) 계산
int maxAnonymousNum = 0;
for (StudyPostComment studyPostComment : studyPostComments) {
if (studyPostComment.getAnonymousNum() != null && studyPostComment.getAnonymousNum() > maxAnonymousNum) {
maxAnonymousNum = studyPostComment.getAnonymousNum();
}
}
anonymousNum = maxAnonymousNum+1;
// 회원의 댓글 이력이 존재하는 경우 익명 작성 여부 확인
// 해당 post에 익명으로 댓글을 남긴 이력이 있으면 해당 번호를 가져옴
if (!myStudyPostComments.isEmpty()) {
for (StudyPostComment myStudyPostComment : myStudyPostComments) {
if (myStudyPostComment.getIsAnonymous()) {
anonymousNum = myStudyPostComment.getAnonymousNum();
}
}
// 댓글은 있지만 익명으로 댓글을 남긴 이력이 없으면 그대로 최댓값+1 부여
}
}
return anonymousNum;
}
/**
* 스터디 게시글에 작성한 댓글을 삭제하는 메서드입니다. 댓글 삭제와 답글 삭제 모두 해당 메서드를 활용합니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 댓글을 삭제할 타겟 스터디 게시글의 아이디를 입력 받습니다.
* @param commentId 삭제할 댓글의 아이디를 입력 받습니다.
* @return 삭제한 댓글의 아이디를 반환합니다.
*/
@Override
public StudyPostCommentResponseDTO.CommentIdDTO deleteComment(Long studyId, Long postId, Long commentId) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPost studyPost = studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(memberId, studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 해당 스터디의 게시글인지 확인
studyPostRepository.findByIdAndStudyId(postId, studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
StudyPostComment studyPostComment = studyPostCommentRepository.findById(commentId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_NOT_FOUND));
// 댓글 작성자인지 확인
if(!studyPostComment.getMember().equals(member)) {
throw new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_DELETE_INVALID);
}
//=== Feature ===//
if (studyPostComment.getIsDeleted()) {
throw new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_ALREADY_DELETED);
}
studyPostComment.deleteComment();
studyPost.updateComment(studyPostComment);
member.updateComment(studyPostComment);
studyPostCommentRepository.save(studyPostComment);
return new StudyPostCommentResponseDTO.CommentIdDTO(commentId);
}
/**
* 댓글에 좋아요를 누르는 메서드입니다. 댓글 좋아요와 답글 좋아요 모두 해당 메서드를 활용합니다.
* 댓글에 좋아요를 누른 회원의 정보가 StudyLikedComment에 저장되고 타겟 댓글의 좋아요 개수가 업데이트 됩니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 타겟이 되는 스터디 게시글의 아이디를 입력 받습니다.
* @param commentId 좋아요를 누를 타겟 댓글의 아이디를 입력 받습니다.
* @return 댓글 아이디와 타겟 댓글의 좋아요 수와 싫어요 수가 반환됩니다.
*/
@Override
public StudyPostCommentResponseDTO.CommentPreviewDTO likeComment(Long studyId, Long postId, Long commentId) {
StudyPostComment studyPostComment = saveStudyPostComment(studyId, postId, commentId, Boolean.TRUE);
return StudyPostCommentResponseDTO.CommentPreviewDTO.toDTO(studyPostComment);
}
/**
* 댓글에 싫어요를 누르는 메서드입니다. 댓글 싫어요와 답글 싫어요 모두 해당 메서드를 활용합니다.
* 댓글에 싫어요를 누른 회원의 정보가 StudyLikedComment에 저장되고 타겟 댓글의 싫어요 개수가 업데이트 됩니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 타겟이 되는 스터디 게시글의 아이디를 입력 받습니다.
* @param commentId 싫어요를 누를 타겟 댓글의 아이디를 입력 받습니다.
* @return 댓글 아이디와 타겟 댓글의 좋아요 수와 싫어요 수가 반환됩니다.
*/
@Override
public StudyPostCommentResponseDTO.CommentPreviewDTO dislikeComment(Long studyId, Long postId, Long commentId) {
StudyPostComment studyPostComment = saveStudyPostComment(studyId, postId, commentId, Boolean.FALSE);
return StudyPostCommentResponseDTO.CommentPreviewDTO.toDTO(studyPostComment);
}
/**
* 댓글 좋아요/싫어요 메서드에서 사용되는 내부 메서드입니다.
* isLiked = true면 좋아요 정보를, isLiked = false면 싫어요 정보를 DB에 저장합니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 타겟이 되는 스터디 게시글의 아이디를 입력 받습니다.
* @param commentId 좋아요 혹은 싫어요를 누를 타겟 댓글의 아이디를 입력 받습니다.
* @param isLiked 좋아요 혹은 싫어요 어부를 입력 받습니다.
* @return SavePostComment 객체를 반환합니다.
*/
private StudyPostComment saveStudyPostComment(Long studyId, Long postId, Long commentId, Boolean isLiked) {
//=== Exception ===//
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
StudyPostComment studyPostComment = studyPostCommentRepository.findById(commentId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 해당 스터디의 게시글인지 확인
studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
// 이미 좋아요나 싫어요를 눌렀다면 싫어요 할 수 없음
if (studyLikedCommentRepository.findByMemberIdAndStudyPostCommentIdAndIsLiked(memberId, commentId, Boolean.TRUE).isPresent()) {
throw new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_ALREADY_LIKED);
}
if (studyLikedCommentRepository.findByMemberIdAndStudyPostCommentIdAndIsLiked(memberId, commentId, Boolean.FALSE).isPresent()) {
throw new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_ALREADY_DISLIKED);
}
//=== Feature ===//
StudyLikedComment studyLikedComment = StudyLikedComment.builder()
.studyPostComment(studyPostComment)
.member(member)
.isLiked(isLiked)
.build();
studyLikedComment = studyLikedCommentRepository.save(studyLikedComment);
member.addStudyLikedComment(studyLikedComment);
studyPostComment.addLikedComment(studyLikedComment);
if (studyLikedComment.getIsLiked()) {
studyPostComment.plusLikeCount();
} else {
studyPostComment.plusDislikeCount();
}
studyPostCommentRepository.save(studyPostComment);
return studyPostComment;
}
/**
* 댓글 좋아요를 취소하는 메서드입니다. 댓글 좋아요와 답글 좋아요 모두 해당 메서드를 활용합니다.
* 댓글 좋아요를 취소한 회원의 정보가 StudyLikedComment에서 삭제되고 타겟 댓글의 싫어요 개수가 업데이트 됩니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 타겟이 되는 스터디 게시글의 아이디를 입력 받습니다.
* @param commentId 싫어요를 취소할 타겟 댓글의 아이디를 입력 받습니다.
* @return 댓글 아이디와 타겟 댓글의 좋아요 수와 싫어요 수가 반환됩니다.
*/
@Override
public StudyPostCommentResponseDTO.CommentPreviewDTO cancelCommentLike(Long studyId, Long postId, Long commentId) {
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
StudyLikedComment studyLikedComment = studyLikedCommentRepository.findByMemberIdAndStudyPostCommentIdAndIsLiked(memberId, commentId, Boolean.TRUE)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_LIKED_COMMENT_NOT_FOUND));
StudyPostComment studyPostComment = deleteStudyLikedComment(studyId, postId, commentId, memberId, studyLikedComment);
return StudyPostCommentResponseDTO.CommentPreviewDTO.toDTO(studyPostComment);
}
/**
* 댓글 싫어요를 취소하는 메서드입니다. 댓글 싫어요와 답글 싫어요 모두 해당 메서드를 활용합니다.
* 댓글 싫어요를 취소한 회원의 정보가 StudyLikedComment에서 삭제되고 타겟 댓글의 싫어요 개수가 업데이트 됩니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 타겟이 되는 스터디 게시글의 아이디를 입력 받습니다.
* @param commentId 싫어요를 취소할 타겟 댓글의 아이디를 입력 받습니다.
* @return 댓글 아이디와 타겟 댓글의 좋아요 수와 싫어요 수가 반환됩니다.
*/
@Override
public StudyPostCommentResponseDTO.CommentPreviewDTO cancelCommentDislike(Long studyId, Long postId, Long commentId) {
Long memberId = SecurityUtils.getCurrentUserId();
SecurityUtils.verifyUserId(memberId);
StudyLikedComment studyLikedComment = studyLikedCommentRepository.findByMemberIdAndStudyPostCommentIdAndIsLiked(memberId, commentId, Boolean.FALSE)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_DISLIKED_COMMENT_NOT_FOUND));
StudyPostComment studyPostComment = deleteStudyLikedComment(studyId, postId, commentId, memberId, studyLikedComment);
return StudyPostCommentResponseDTO.CommentPreviewDTO.toDTO(studyPostComment);
}
/**
* 댓글 좋아요/싫어요 취소 메서드에서 사용되는 내부 메서드입니다.
* @param studyId 스터디 게시글이 작성된 타겟 스터디의 아이디를 입력 받습니다.
* @param postId 타겟이 되는 스터디 게시글의 아이디를 입력 받습니다.
* @param commentId 좋아요 혹은 싫어요를 취소할 타겟 댓글의 아이디를 입력 받습니다.
* @param memberId 댓글에 좋아요 혹은 싫어요를 누른 회원의 아이디를 입력 받습니다.
* @param studyLikedComment DB에서 삭제할 StudyLikedComment 객체를 입력 받습니다.
* @return 삭제된 StudyLikedComment 객체를 반환합니다.
*/
private StudyPostComment deleteStudyLikedComment(Long studyId, Long postId, Long commentId, Long memberId, StudyLikedComment studyLikedComment) {
//=== Exception ===//
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberHandler(ErrorStatus._MEMBER_NOT_FOUND));
studyRepository.findById(studyId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_NOT_FOUND));
studyPostRepository.findById(postId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_NOT_FOUND));
StudyPostComment studyPostComment = studyPostCommentRepository.findById(commentId)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_NOT_FOUND));
// 로그인한 회원이 스터디 회원인지 확인
memberStudyRepository.findByMemberIdAndStudyIdAndStatus(member.getId(), studyId, ApplicationStatus.APPROVED)
.orElseThrow(() -> new StudyHandler(ErrorStatus._STUDY_MEMBER_NOT_FOUND));
// 로그인한 회원이 댓글에 반응한 사람인지 확인
if (!studyLikedComment.getMember().equals(member)) {
throw new StudyHandler(ErrorStatus._STUDY_POST_COMMENT_DELETE_INVALID);
}
//=== Feature ===//
member.deleteStudyLikedComment(studyLikedComment);
studyPostComment.deleteLikedComment(studyLikedComment);
if (studyLikedComment.getIsLiked()) {
studyPostComment.minusLikeCount();
} else {
studyPostComment.minusDislikeCount();
}
studyLikedCommentRepository.delete(studyLikedComment);
studyPostCommentRepository.save(studyPostComment);
return studyPostComment;
}
}