-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCardSetService.java
More file actions
404 lines (340 loc) · 13.7 KB
/
CardSetService.java
File metadata and controls
404 lines (340 loc) · 13.7 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
package project.flipnote.cardset.service;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import project.flipnote.bookmark.entity.BookmarkTargetType;
import project.flipnote.bookmark.service.BookmarkReader;
import project.flipnote.bookmark.service.BookmarkWriter;
import project.flipnote.cardset.entity.CardSet;
import project.flipnote.cardset.entity.CardSetManager;
import project.flipnote.cardset.entity.CardSetMetadata;
import project.flipnote.cardset.exception.CardSetErrorCode;
import project.flipnote.cardset.model.CardSetDetailResponse;
import project.flipnote.cardset.model.CardSetInfo;
import project.flipnote.cardset.model.CardSetSearchRequest;
import project.flipnote.cardset.model.CardSetSummaryResponse;
import project.flipnote.cardset.model.CardSetUpdatePayload;
import project.flipnote.cardset.model.CardSetUpdateRequest;
import project.flipnote.cardset.model.CreateCardSetRequest;
import project.flipnote.cardset.model.CreateCardSetResponse;
import project.flipnote.cardset.repository.CardSetContentRepository;
import project.flipnote.cardset.repository.CardSetIncrementalRepository;
import project.flipnote.cardset.repository.CardSetManagerRepository;
import project.flipnote.cardset.repository.CardSetMetadataRepository;
import project.flipnote.cardset.repository.CardSetRepository;
import project.flipnote.common.exception.BizException;
import project.flipnote.common.model.response.IdResponse;
import project.flipnote.common.model.response.PagingResponse;
import project.flipnote.common.security.dto.AuthPrinciple;
import project.flipnote.group.entity.Category;
import project.flipnote.group.entity.Group;
import project.flipnote.group.exception.GroupErrorCode;
import project.flipnote.group.repository.GroupMemberRepository;
import project.flipnote.group.repository.GroupRepository;
import project.flipnote.group.service.GroupService;
import project.flipnote.image.entity.ImageMeta;
import project.flipnote.image.entity.ImageRef;
import project.flipnote.image.entity.ReferenceType;
import project.flipnote.image.service.ImageRefService;
import project.flipnote.image.service.ImageService;
import project.flipnote.like.entity.LikeTargetType;
import project.flipnote.like.service.LikeReader;
import project.flipnote.like.service.LikeWriter;
import project.flipnote.user.entity.UserProfile;
import project.flipnote.user.entity.UserStatus;
import project.flipnote.user.exception.UserErrorCode;
import project.flipnote.user.repository.UserProfileRepository;
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CardSetService {
private final CardSetRepository cardSetRepository;
private final UserProfileRepository userProfileRepository;
private final GroupRepository groupRepository;
private final GroupMemberRepository groupMemberRepository;
private final CardSetManagerRepository cardSetManagerRepository;
private final CardSetPolicyService cardSetPolicyService;
private final CardSetMetadataRepository cardSetMetadataRepository;
private final ImageService imageService;
private final ImageRefService imageRefService;
private final GroupService groupService;
private final LikeReader likeReader;
private final BookmarkReader bookmarkReader;
private final LikeWriter likeWriter;
private final BookmarkWriter bookmarkWriter;
private final CardSetContentRepository cardSetContentRepository;
private final CardSetIncrementalRepository cardSetIncrementalRepository;
@Value("${image.default.cardSet}")
private String defaultCardSetImage;
private static final ReferenceType REFERENCE_TYPE = ReferenceType.CARD_SET;
private UserProfile validateUser(Long userId) {
return userProfileRepository.findByIdAndStatus(userId, UserStatus.ACTIVE).orElseThrow(
() -> new BizException(UserErrorCode.USER_NOT_FOUND)
);
}
private Group findGroup(Long groupId) {
return groupRepository.findById(groupId).orElseThrow(
() -> new BizException(GroupErrorCode.GROUP_NOT_FOUND)
);
}
private boolean existGroupMember(Group group, UserProfile user) {
return groupMemberRepository.existsByGroup_idAndUser_id((group.getId()), user.getId());
}
@Transactional
public CreateCardSetResponse createCardSet(Long groupId, AuthPrinciple authPrinciple, CreateCardSetRequest req) {
//유저 정보 찾기
UserProfile user = validateUser(authPrinciple.userId());
//그룹 정보 찾기
Group group = findGroup(groupId);
//그룹 내 유저 있는지 확인
if (!existGroupMember(group, user)) {
throw new BizException(CardSetErrorCode.GROUP_MEMBER_NOT_FOUND);
}
//해시태그가 없으면 null로 저장
String hashtags = (req.hashtag() != null && !req.hashtag().isEmpty())
? String.join(",", req.hashtag())
: null;
//이미지 url 찾기
String url = imageService.assignImageUrl(REFERENCE_TYPE, req.imageRefId());
CardSet cardSet = CardSet.builder()
.name(req.name())
.group(group)
.publicVisible(req.publicVisible())
.category(req.category())
.hashtag(hashtags)
.imageUrl(url)
.build();
cardSetRepository.save(cardSet);
if (req.imageRefId() != null) {
// 이미지 활성화
imageService.changeUrlStatus(req.imageRefId(), REFERENCE_TYPE, cardSet.getId());
}
CardSetMetadata metadata = CardSetMetadata.builder()
.id(cardSet.getId())
.build();
cardSetMetadataRepository.save(metadata);
//카드셋 매니저도 저장
CardSetManager cardSetManager = CardSetManager.builder()
.user(user)
.cardSet(cardSet)
.build();
cardSetManagerRepository.save(cardSetManager);
return CreateCardSetResponse.from(cardSet.getId());
}
/**
* 카드셋 목록을 페이지 단위로 조회
*
* @param req 조회 조건 및 페이징 정보를 포함한 요청 DTO
* @return 페이지 단위로 조회된 카드셋 목록
* @author 윤정환
*/
public PagingResponse<CardSetSummaryResponse> getCardSets(CardSetSearchRequest req) {
// TODO: Projection 튜닝 필요
Page<CardSetInfo> cardSetPage = cardSetRepository.searchByNameContainingAndCategory(
req.getKeyword(), Category.from(req.getCategory()), req.getPageRequest()
);
Page<CardSetSummaryResponse> res = cardSetPage.map(CardSetSummaryResponse::from);
return PagingResponse.from(res);
}
/**
* 카드셋 상세 조회
*
* @param userId 카드셋 상세 조회하는 회원 ID
* @param groupId 카드셋을 생성한 그룹 ID
* @param cardSetId 상세 조회하려는 카드셋 ID
* @return 카드셋 상세 조회 정보
* @author 윤정환
*/
public CardSetDetailResponse getCardSet(Long userId, Long groupId, Long cardSetId) {
CardSet cardSet = cardSetPolicyService.findByIdAndGroupIdOrThrow(groupId, cardSetId);
cardSetPolicyService.validateCardSetViewable(cardSet, userId);
boolean liked = likeReader.isLiked(userId, LikeTargetType.CARD_SET, cardSetId);
boolean bookmarked = bookmarkReader.isBookmarked(userId, BookmarkTargetType.CARD_SET, cardSetId);
Long imageRefId = imageRefService.findByTypeAndReferenceId(REFERENCE_TYPE, cardSetId)
.map(ImageRef::getId)
.orElse(null);
return CardSetDetailResponse.from(cardSet, liked, bookmarked, imageRefId);
}
/**
* 카드셋 수정
*
* @param userId 카드셋 수정하는 회원 ID
* @param groupId 카드셋을 생성한 그룹 ID
* @param cardSetId 수정하려는 카드셋 ID
* @param req 카드셋의 수정 내용을 담은 요청 정보
* @return 수정된 카드셋 정보
* @author 윤정환
*/
@Transactional
public CardSetDetailResponse updateCardSet(Long userId, Long groupId, Long cardSetId, CardSetUpdateRequest req) {
CardSet cardSet = cardSetPolicyService.findByIdAndGroupIdOrThrow(groupId, cardSetId);
cardSetPolicyService.validateCardSetEditable(userId, cardSetId);
ImageMeta imageMeta = imageService.changeImage(REFERENCE_TYPE, cardSetId, req.imageRefId());
CardSetUpdatePayload updatePayload = CardSetUpdatePayload.from(req);
cardSet.update(updatePayload, imageMeta.url());
cardSetRepository.saveAndFlush(cardSet);
boolean liked = likeReader.isLiked(userId, LikeTargetType.CARD_SET, cardSetId);
boolean bookmarked = bookmarkReader.isBookmarked(userId, BookmarkTargetType.CARD_SET, cardSetId);
return CardSetDetailResponse.from(cardSet, liked, bookmarked, imageMeta.imageRefId());
}
/**
* 카드셋 존재 여부 확인
*
* @param cardSetId 존재하는지 확인할 카드셋 ID
* @return 카드셋 존재 여부
* @author 윤정환
*/
public boolean existsById(Long cardSetId) {
return cardSetRepository.existsById(cardSetId);
}
/**
* 카드셋 좋아요 수를 1 증가
*
* @param cardSetId 좋아요 수를 증가시킬 카드셋 ID
* @author 윤정환
*/
@Transactional
public void incrementLikeCount(Long cardSetId) {
cardSetMetadataRepository.incrementLikeCount(cardSetId);
}
/**
* 카드셋 좋아요 수를 1 감소
*
* @param cardSetId 좋아요 수를 감소시킬 카드셋 ID
* @author 윤정환
*/
@Transactional
public void decrementLikeCount(Long cardSetId) {
cardSetMetadataRepository.decrementLikeCount(cardSetId);
}
/**
* 카드셋 ID 목록에 해당하는 카드셋 목록 조회
*
* @param targetIds 조회할 카드셋 ID 목록
* @return 조회된 카드셋 목록
* @author 윤정환
*/
@Transactional
public List<CardSetSummaryResponse> getCardSetsByIds(Set<Long> targetIds) {
// TODO: MSA로 전환시 전용 DTO로 변경 필요
return cardSetRepository.findAllByIdWithImageRefId(targetIds).stream()
.map(CardSetSummaryResponse::from)
.toList();
}
/**
* 사용자가 특정 카드셋에 접근할 수 있는지 여부를 확인
*
* @param cardSetId 확인할 카드셋의 ID
* @param userId 접근 권한을 확인할 사용자의 ID
* @return 접근 가능 여부
* @author 윤정환
*/
public boolean isCardSetViewable(Long cardSetId, Long userId) {
return cardSetRepository.findById(cardSetId)
.map(cardSet -> cardSetPolicyService.isCardSetViewable(cardSet, userId))
.orElse(false);
}
/**
* 카드셋 ID 목록에 해당하는 카드셋 목록 조회
*
* @param targetIds 조회할 카드셋 ID 목록
* @param userId 카드셋 목록을 조회하는 회원 ID
* @return 조회된 카드셋 목록
* @author 윤정환
*/
@Transactional
public List<CardSetSummaryResponse> findViewableCardSetsByIds(Set<Long> targetIds, Long userId) {
// TODO: MSA로 전환시 전용 DTO로 변경 필요
return cardSetRepository.findAllByIdWithImageRefId(targetIds).stream()
.filter(cardSetInfo -> cardSetPolicyService.isCardSetViewable(cardSetInfo.cardSet(), userId))
.map(CardSetSummaryResponse::from)
.toList();
}
/**
* 해당 그룹의 비공개인 카드셋의 ID들을 조회
*
* @param groupId 조회할 그룹의 ID
* @return 그룹에 속한 비공개 카드셋 ID의 집합
* @author 윤정환
*/
public Set<Long> findPrivateCardSetIds(Long groupId) {
return cardSetRepository.findPrivateIdsByGroupId(groupId);
}
/**
* 카드셋 즐겨찾기 수를 1 증가
*
* @param cardSetId 즐겨찾기 수를 증가시킬 카드셋 ID
* @author 윤정환
*/
@Transactional
public void incrementBookmarkCount(Long cardSetId) {
cardSetMetadataRepository.incrementBookmarkCount(cardSetId);
}
/**
* 카드셋 즐겨찾기 수를 1 감소
*
* @param cardSetId 즐겨찾기 수를 감소시킬 카드셋 ID
* @author 윤정환
*/
@Transactional
public void decrementBookmarkCount(Long cardSetId) {
cardSetMetadataRepository.decrementBookmarkCount(cardSetId);
}
/**
* 여러 카드셋 즐겨찾기 수를 1 감소
*
* @param cardSetIds 즐겨찾기 수를 감소시킬 카드셋 ID 목록
* @author 윤정환
*/
@Transactional
public void decrementBookmarkCount(List<Long> cardSetIds) {
cardSetMetadataRepository.decrementBookmarkCount(cardSetIds);
}
/**
* 특정 그룹의 카드셋 목록을 페이지 단위로 조회
*
* @param groupId 조회할 그룹의 ID
* @param req 조회 조건 및 페이징 정보를 포함한 요청 DTO
* @return 페이지 단위로 조회된 카드셋 목록
* @author 윤정환
*/
public PagingResponse<CardSetSummaryResponse> getCardSets(long groupId, CardSetSearchRequest req) {
groupService.validateGroupExists(groupId);
// TODO: Projection 튜닝 필요
Page<CardSetInfo> cardSetPage = cardSetRepository.searchByGroupIdAndNameContainingAndCategory(
groupId, req.getKeyword(), Category.from(req.getCategory()), req.getPageRequest()
);
Page<CardSetSummaryResponse> res = cardSetPage.map(CardSetSummaryResponse::from);
return PagingResponse.from(res);
}
@Transactional
public IdResponse deleteCardSet(Long userId, Long groupId, Long cardSetId) {
CardSet cardSet = cardSetPolicyService.findByIdAndGroupIdOrThrow(groupId, cardSetId);
cardSetPolicyService.validateCardSetEditable(userId, cardSetId);
// 카드셋 관리자
cardSetManagerRepository.deleteByCardSet_Id(cardSetId);
// 카드셋 내용
cardSetContentRepository.deleteByCardSetId(cardSetId);
// 카드셋 증분값
cardSetIncrementalRepository.deleteByCardSetId(cardSetId);
// 카드셋 스냅샷
// 카드셋 메타데이터
cardSetMetadataRepository.deleteById(cardSetId);
// 이미지
imageRefService.findByTypeAndReferenceId(REFERENCE_TYPE, cardSetId)
.ifPresent(imageRef -> imageRefService.deleteByReferenceAndId(REFERENCE_TYPE, imageRef.getId()));
// 카드셋
cardSetRepository.delete(cardSet);
// 좋아요
likeWriter.delete(LikeTargetType.CARD_SET, cardSetId);
// 즐겨찾기
bookmarkWriter.delete(BookmarkTargetType.CARD_SET, cardSetId);
return IdResponse.from(cardSetId);
}
}