-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryService.java
More file actions
535 lines (456 loc) · 29.6 KB
/
LibraryService.java
File metadata and controls
535 lines (456 loc) · 29.6 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
package DiffLens.back_end.domain.library.service;
import DiffLens.back_end.domain.library.dto.LibraryRequestDto;
import DiffLens.back_end.domain.library.dto.LibraryResponseDTO;
import DiffLens.back_end.domain.library.dto.LibraryCompareRequestDTO;
import DiffLens.back_end.domain.library.dto.LibraryCompareResponseDTO;
import DiffLens.back_end.domain.library.entity.Library;
import DiffLens.back_end.domain.library.entity.LibraryPanel;
import DiffLens.back_end.domain.library.entity.LibraryPanelKey;
import DiffLens.back_end.domain.library.entity.SearchHistoryLibrary;
import DiffLens.back_end.domain.library.entity.SearchHistoryLibraryKey;
import DiffLens.back_end.domain.library.repository.LibraryPanelRepository;
import DiffLens.back_end.domain.library.repository.LibraryRepository;
import DiffLens.back_end.domain.library.repository.SearchHistoryLibraryRepository;
import DiffLens.back_end.domain.members.entity.Member;
import DiffLens.back_end.domain.panel.entity.Panel;
import DiffLens.back_end.domain.panel.repository.PanelRepository;
import DiffLens.back_end.domain.search.entity.Filter;
import DiffLens.back_end.domain.search.entity.SearchFilter;
import DiffLens.back_end.domain.search.entity.SearchHistory;
import DiffLens.back_end.domain.search.enums.filters.Gender;
import DiffLens.back_end.domain.search.repository.FilterRepository;
import DiffLens.back_end.domain.search.repository.SearchFilterRepository;
import DiffLens.back_end.domain.search.repository.SearchHistoryRepository;
import DiffLens.back_end.global.fastapi.FastApiService;
import DiffLens.back_end.global.fastapi.dto.request.FastLibraryRequestDTO;
import DiffLens.back_end.global.fastapi.dto.response.FastLibraryCompareResponseDTO;
import DiffLens.back_end.global.responses.code.status.error.ErrorStatus;
import DiffLens.back_end.global.responses.exception.handler.ErrorHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
@RequiredArgsConstructor
public class LibraryService {
private final LibraryRepository libraryRepository;
private final LibraryPanelRepository libraryPanelRepository;
private final SearchHistoryLibraryRepository searchHistoryLibraryRepository;
private final SearchHistoryRepository searchHistoryRepository;
private final PanelRepository panelRepository;
private final FastApiService fastApiService;
private final SearchFilterRepository searchFilterRepository;
private final FilterRepository filterRepository;
@Transactional
public LibraryCreateResult createLibrary(LibraryRequestDto.Create request, Member member) {
// 1. SearchHistory 검증
SearchHistory history = searchHistoryRepository.findById(request.getSearchHistoryId())
.orElseThrow(() -> new ErrorHandler(ErrorStatus.BAD_REQUEST));
// 2. 권한 검증 - 본인의 검색 기록만 라이브러리로 저장 가능
if (!history.getMember().getId().equals(member.getId())) {
throw new ErrorHandler(ErrorStatus.FORBIDDEN);
}
// 3. Library 생성 (SearchHistory 참조 제거)
// 패널 ID 결정: 요청에 있으면 사용, 없으면 검색기록의 패널 ID 사용
List<String> panelIds = request.getPanelIds() != null
? request.getPanelIds()
: history.getPanelIds();
Library library = Library.builder()
.libraryName(request.getLibraryName())
.tags(request.getTags())
.panelIds(panelIds != null ? panelIds : List.of())
.member(member)
.build();
library = libraryRepository.save(library);
// 4. Library-SearchHistory 다대다 관계 생성
SearchHistoryLibrary searchHistoryLibrary = SearchHistoryLibrary.builder()
.id(new SearchHistoryLibraryKey(history.getId(), library.getId()))
.library(library)
.history(history)
.build();
searchHistoryLibraryRepository.save(searchHistoryLibrary);
// 5. Panel 관계 생성
int panelCount = 0;
if (panelIds != null && !panelIds.isEmpty()) {
createLibraryPanels(library, panelIds);
panelCount = panelIds.size();
}
return new LibraryCreateResult(library, panelCount);
}
@Transactional
public LibraryCreateResult addSearchHistoryToLibrary(Long libraryId, Long searchHistoryId, Member member) {
// 1. 라이브러리 조회 및 권한 검증
Library library = libraryRepository.findById(libraryId)
.orElseThrow(() -> new ErrorHandler(ErrorStatus.BAD_REQUEST));
if (!library.getMember().getId().equals(member.getId())) {
throw new ErrorHandler(ErrorStatus.FORBIDDEN);
}
// 2. 검색기록 조회 및 권한 검증
SearchHistory searchHistory = searchHistoryRepository.findById(searchHistoryId)
.orElseThrow(() -> new ErrorHandler(ErrorStatus.BAD_REQUEST));
if (!searchHistory.getMember().getId().equals(member.getId())) {
throw new ErrorHandler(ErrorStatus.FORBIDDEN);
}
// 3. 패널 ID 병합 (중복 제거)
List<String> existingPanelIds = library.getPanelIds();
List<String> newPanelIds = searchHistory.getPanelIds();
List<String> mergedPanelIds = Stream.concat(
existingPanelIds.stream(),
newPanelIds.stream()).distinct().collect(Collectors.toList());
// 4. 새로운 패널들만 LibraryPanel에 추가
List<String> newPanelsToAdd = newPanelIds.stream()
.filter(panelId -> !existingPanelIds.contains(panelId))
.collect(Collectors.toList());
int addedPanelCount = 0;
if (!newPanelsToAdd.isEmpty()) {
createLibraryPanels(library, newPanelsToAdd);
addedPanelCount = newPanelsToAdd.size();
}
// 5. Library 엔티티의 panelIds 업데이트
// 기존 엔티티의 panelIds만 업데이트 (AuditingEntityListener가 updatedAt 자동 관리)
library.setPanelIds(mergedPanelIds);
library = libraryRepository.save(library);
// 6. SearchHistoryLibrary 관계 생성 (존재하지 않을 때만)
SearchHistoryLibraryKey searchHistoryLibraryKey = new SearchHistoryLibraryKey(searchHistoryId,
libraryId);
boolean relationshipExists = searchHistoryLibraryRepository.existsById(searchHistoryLibraryKey);
if (!relationshipExists) {
SearchHistoryLibrary searchHistoryLibrary = SearchHistoryLibrary.builder()
.id(searchHistoryLibraryKey)
.library(library)
.history(searchHistory)
.build();
searchHistoryLibraryRepository.save(searchHistoryLibrary);
}
return new LibraryCreateResult(library, addedPanelCount);
}
@Transactional(readOnly = true)
public LibraryResponseDTO.ListResult getLibrariesByMember(Member member) {
List<Library> libraries = libraryRepository.findByMemberOrderByCreatedDateDesc(member);
List<LibraryResponseDTO.ListResult.LibraryItem> libraryItems = libraries.stream()
.map(library -> {
int panelCount = libraryPanelRepository.countByLibraryId(library.getId());
return LibraryResponseDTO.ListResult.LibraryItem.from(library, panelCount);
})
.toList();
return LibraryResponseDTO.ListResult.builder()
.libraries(libraryItems)
.cursorPageInfo(null) // 페이징이 필요하면 추후 구현
.build();
}
@Transactional(readOnly = true)
public LibraryResponseDTO.LibraryDetail getLibraryDetail(Long libraryId, Member member) {
// 1. 라이브러리 조회 및 권한 검증
Library library = libraryRepository.findById(libraryId)
.orElseThrow(() -> new ErrorHandler(ErrorStatus.BAD_REQUEST));
if (!library.getMember().getId().equals(member.getId())) {
throw new ErrorHandler(ErrorStatus.FORBIDDEN);
}
// 2. 패널 정보 조회
List<Panel> panels = panelRepository.findByIdList(library.getPanelIds());
List<LibraryResponseDTO.LibraryDetail.PanelInfo> panelInfos = panels.stream()
.map(panel -> LibraryResponseDTO.LibraryDetail.PanelInfo.builder()
.panelId(panel.getId())
.gender(panel.getGender() != null ? panel.getGender().toString() : null)
.age(panel.getAge())
.ageGroup(panel.getAgeGroup())
.residence(panel.getRegion())
.maritalStatus(panel.getMaritalStatus())
.childrenCount(panel.getChildrenCount())
.occupation(panel.getOccupation())
.profileSummary(panel.getProfileSummary())
.build())
.toList();
// 3. 연결된 검색기록 조회
List<SearchHistoryLibrary> searchHistoryLibraries = searchHistoryLibraryRepository
.findByLibraryId(libraryId);
List<LibraryResponseDTO.LibraryDetail.SearchHistoryInfo> searchHistoryInfos = searchHistoryLibraries
.stream()
.map(shl -> {
SearchHistory history = shl.getHistory();
return LibraryResponseDTO.LibraryDetail.SearchHistoryInfo.builder()
.searchHistoryId(history.getId())
.content(history.getContent())
.date(history.getDate() != null ? history.getDate().toString()
: null)
.panelCount(history.getPanelIds() != null
? history.getPanelIds().size()
: 0)
.createdAt(history.getCreatedDate() != null
? history.getCreatedDate().toString()
: null)
.build();
})
.toList();
// 4. 통계 정보 생성
LibraryResponseDTO.LibraryDetail.Statistics statistics = createStatistics(panels);
return LibraryResponseDTO.LibraryDetail.builder()
.libraryId(library.getId())
.libraryName(library.getLibraryName())
.tags(library.getTags())
.panelCount(panels.size())
.panelIds(library.getPanelIds())
.panels(panelInfos)
.searchHistories(searchHistoryInfos)
.statistics(statistics)
.createdAt(library.getCreatedDate() != null ? library.getCreatedDate().toString()
: null)
.updatedAt(library.getUpdatedAt() != null ? library.getUpdatedAt().toString() : null)
.build();
}
// 추후 혹시 라이브러리 상세 페이지에서 간단한 통계 디자인 생길 것 대비해 작성해둠
private LibraryResponseDTO.LibraryDetail.Statistics createStatistics(List<Panel> panels) {
// 성별 분포
long maleCount = panels.stream()
.filter(p -> p.getGender() != null && p.getGender().toString().equals("MALE")).count();
long femaleCount = panels.stream()
.filter(p -> p.getGender() != null && p.getGender().toString().equals("FEMALE"))
.count();
long noneCount = panels.stream()
.filter(p -> p.getGender() != null && p.getGender().toString().equals("NONE")).count();
LibraryResponseDTO.LibraryDetail.Statistics.GenderDistribution genderDistribution = LibraryResponseDTO.LibraryDetail.Statistics.GenderDistribution
.builder()
.male((int) maleCount)
.female((int) femaleCount)
.none((int) noneCount)
.build();
// 연령대 분포
long twenties = panels.stream().filter(p -> "20대".equals(p.getAgeGroup())).count();
long thirties = panels.stream().filter(p -> "30대".equals(p.getAgeGroup())).count();
long forties = panels.stream().filter(p -> "40대".equals(p.getAgeGroup())).count();
long fifties = panels.stream().filter(p -> "50대".equals(p.getAgeGroup())).count();
long sixtiesPlus = panels.stream().filter(p -> p.getAgeGroup() != null &&
(p.getAgeGroup().contains("60") || p.getAgeGroup().contains("70")
|| p.getAgeGroup().contains("80")))
.count();
LibraryResponseDTO.LibraryDetail.Statistics.AgeGroupDistribution ageGroupDistribution = LibraryResponseDTO.LibraryDetail.Statistics.AgeGroupDistribution
.builder()
.twenties((int) twenties)
.thirties((int) thirties)
.forties((int) forties)
.fifties((int) fifties)
.sixtiesPlus((int) sixtiesPlus)
.build();
// 거주지 분포
long seoul = panels.stream().filter(p -> p.getRegion() != null && p.getRegion().contains("서울"))
.count();
long gyeonggi = panels.stream().filter(p -> p.getRegion() != null && p.getRegion().contains("경기"))
.count();
long busan = panels.stream().filter(p -> p.getRegion() != null && p.getRegion().contains("부산"))
.count();
long other = panels.size() - seoul - gyeonggi - busan;
LibraryResponseDTO.LibraryDetail.Statistics.ResidenceDistribution residenceDistribution = LibraryResponseDTO.LibraryDetail.Statistics.ResidenceDistribution
.builder()
.seoul((int) seoul)
.gyeonggi((int) gyeonggi)
.busan((int) busan)
.other((int) other)
.build();
return LibraryResponseDTO.LibraryDetail.Statistics.builder()
.totalPanels(panels.size())
.genderDistribution(genderDistribution)
.ageGroupDistribution(ageGroupDistribution)
.residenceDistribution(residenceDistribution)
.build();
}
@Transactional(readOnly = true)
public LibraryCompareResponseDTO.CompareResult compareLibraries(LibraryCompareRequestDTO.Compare request, Member member) {
// 1. 요청 검증 - 같은 라이브러리 비교 불가
if (request.getLibraryId1().equals(request.getLibraryId2())) {
throw new ErrorHandler(ErrorStatus.BAD_REQUEST);
}
// 2. 라이브러리 조회 및 권한 확인
Library library1 = libraryRepository.findById(request.getLibraryId1())
.orElseThrow(() -> new ErrorHandler(ErrorStatus.BAD_REQUEST));
Library library2 = libraryRepository.findById(request.getLibraryId2())
.orElseThrow(() -> new ErrorHandler(ErrorStatus.BAD_REQUEST));
// 3. 권한 검증 - 본인의 라이브러리만 비교 가능
if (!library1.getMember().getId().equals(member.getId()) ||
!library2.getMember().getId().equals(member.getId())) {
throw new ErrorHandler(ErrorStatus.FORBIDDEN);
}
// 4. FastAPI 서버로 비교 요청
FastLibraryRequestDTO.LibraryCompare fastApiRequest = FastLibraryRequestDTO.LibraryCompare.builder()
.libraryId1(library1.getId())
.libraryId2(library2.getId())
.panelIds1(library1.getPanelIds())
.panelIds2(library2.getPanelIds())
.build();
FastLibraryCompareResponseDTO.CompareResult fastApiResponse = fastApiService
.compareLibraries(fastApiRequest);
// 5. 응답 데이터 구성
return LibraryCompareResponseDTO.CompareResult.builder()
.group1(LibraryCompareResponseDTO.GroupInfo.builder()
.libraryId(library1.getId())
.libraryName(library1.getLibraryName())
// .summary()
.totalCount(library1.getPanelIds().size())
.filters(convertFilters(library1))
.color("#4169E1")
.build())
.group2(LibraryCompareResponseDTO.GroupInfo.builder()
.libraryId(library2.getId())
.libraryName(library2.getLibraryName())
// .summary()
.totalCount(library2.getPanelIds().size())
.filters(convertFilters(library2))
.color("#32CD32")
.build())
.keyCharacteristics(convertKeyCharacteristics(fastApiResponse.getKeyCharacteristics()))
.comparisons(convertComparisons(fastApiResponse.getBasicComparison(), library1, library2))
.insights(convertInsights(fastApiResponse.getAiInsights()))
.build();
}
private LibraryCompareResponseDTO.Comparisons convertComparisons(List<FastLibraryCompareResponseDTO.BasicComparison> comparisons, Library library1, Library library2) {
return LibraryCompareResponseDTO.Comparisons.builder()
.group1(getGroupMetrics(library1))
.group2(getGroupMetrics(library2))
.build();
}
private LibraryCompareResponseDTO.GroupMetrics getGroupMetrics(Library library) {
List<Panel> panels = panelRepository.findByIdList(library.getPanelIds());
int total = panels.size();
if (total == 0) {
return LibraryCompareResponseDTO.GroupMetrics.builder()
.male(0).female(0)
.seoul(0).gyeonggi(0).busan(0).regionEtc(0)
.ratePossessingCar(0)
.avgAge(0.0)
.avgFamily(0.0)
.avgChildren(0.0)
.avgPersonalIncome(0)
.avgFamilyIncome(0)
.build();
}
long maleCount = panels.stream().filter(p -> p.getGender() != null && p.getGender().toString().equals(Gender.MALE)).count();
long femaleCount = panels.stream().filter(p -> p.getGender() != null && p.getGender().toString().equals(Gender.FEMALE)).count();
long seoul = panels.stream().filter(p -> p.getRegion() != null && p.getRegion().contains("서울")).count();
long gyeonggi = panels.stream().filter(p -> p.getRegion() != null && p.getRegion().contains("경기")).count();
long busan = panels.stream().filter(p -> p.getRegion() != null && p.getRegion().contains("부산")).count();
long regionEtc = total - seoul - gyeonggi - busan;
long carOwners = panels.stream().filter(p -> p.getCarOwnership() != null && p.getCarOwnership().contains("있음")).count();
double avgAge = panels.stream()
.filter(p -> p.getAge() != null)
.mapToInt(Panel::getAge)
.average()
.orElse(0);
double avgFamily = panels.stream()
.filter(p -> p.getFamilySize() != null)
.mapToInt(p -> {
try {
return Integer.parseInt(p.getFamilySize());
} catch (NumberFormatException e) {
return 0;
}
}).average().orElse(0);
double avgChildren = panels.stream()
.filter(p -> p.getChildrenCount() != null)
.mapToInt(Panel::getChildrenCount)
.average()
.orElse(0);
double avgPersonalIncome = panels.stream()
.filter(p -> p.getPersonalIncome() != null)
.mapToInt(p -> parseIncome(p.getPersonalIncome()))
.average()
.orElse(0);
double avgFamilyIncome = panels.stream()
.filter(p -> p.getHouseholdIncome() != null)
.mapToInt(p -> parseIncome(p.getHouseholdIncome()))
.average()
.orElse(0);
return LibraryCompareResponseDTO.GroupMetrics.builder()
.male((int) Math.round((double) maleCount / total * 100))
.female((int) Math.round((double) femaleCount / total * 100))
.seoul((int) Math.round((double) seoul / total * 100))
.gyeonggi((int) Math.round((double) gyeonggi / total * 100))
.busan((int) Math.round((double) busan / total * 100))
.regionEtc((int) Math.round((double) regionEtc / total * 100))
.ratePossessingCar((int) Math.round((double) carOwners / total * 100))
.avgAge(avgAge)
.avgFamily(avgFamily)
.avgChildren(avgChildren)
.avgPersonalIncome((int) avgPersonalIncome)
.avgFamilyIncome((int) avgFamilyIncome)
.build();
}
// 문자열 -> 숫자
private int parseIncome(String incomeStr) {
if (incomeStr == null) return 0;
String clean = incomeStr.replaceAll("[^0-9]", "");
if (clean.isEmpty()) return 0;
try {
return Integer.parseInt(clean);
} catch (NumberFormatException e) {
return 0;
}
}
private List<LibraryCompareResponseDTO.KeyCharacteristic> convertKeyCharacteristics(
List<FastLibraryCompareResponseDTO.KeyCharacteristic> fastApiCharacteristics) {
int lastIndex = Math.min(fastApiCharacteristics.size(), 3);
return fastApiCharacteristics.subList(0, lastIndex-1).stream()
.map(fast -> LibraryCompareResponseDTO.KeyCharacteristic.builder()
.characteristic(fast.getCharacteristic())
.description(fast.getDescription())
.group1Percentage(fast.getGroup1Percentage())
.group2Percentage(fast.getGroup2Percentage())
.difference(fast.getDifference())
.build())
.toList();
}
private List<LibraryCompareResponseDTO.Filter> convertFilters(Library library) {
List<SearchHistoryLibrary> searchHistoryLibraries =
searchHistoryLibraryRepository.findByLibraryId(library.getId());
List<SearchHistory> histories = searchHistoryLibraries.stream()
.map(SearchHistoryLibrary::getHistory)
.toList();
List<SearchFilter> searchFilters = searchFilterRepository.findBySearchHistory(histories);
// Set<Long> filterIds = searchFilters.stream()
// .map(SearchFilter::getId)
// .collect(Collectors.toSet());
Set<Long> filterIds = new HashSet<>();
searchFilters.forEach(searchFilter -> filterIds.addAll(searchFilter.getFilters()));
List<Filter> filters = filterRepository.findByIds(filterIds);
Map<String, List<String>> grouped = filters.stream()
.collect(Collectors.groupingBy(
Filter::getType,
Collectors.mapping(Filter::getDisplayValue, Collectors.toList())
));
return grouped.entrySet().stream()
.map(entry -> LibraryCompareResponseDTO.Filter.builder()
.key(entry.getKey())
.values(entry.getValue())
.build())
.toList();
}
private void createLibraryPanels(Library library, List<String> panelIds) {
List<Panel> panels = panelRepository.findByIdList(panelIds);
if (panels.size() != panelIds.size()) {
throw new ErrorHandler(ErrorStatus.BAD_REQUEST);
// TODO: 커스텀 에러 메시지 추가 시 활용 - "존재하지 않는 패널 ID가 있습니다"
}
List<LibraryPanel> libraryPanels = panels.stream()
.map(panel -> LibraryPanel.builder()
.id(new LibraryPanelKey(panel.getId(), library.getId()))
.library(library)
.panel(panel)
.build())
.toList();
libraryPanelRepository.saveAll(libraryPanels);
}
private LibraryCompareResponseDTO.Insights convertInsights(FastLibraryCompareResponseDTO.Insights insights) {
return LibraryCompareResponseDTO.Insights.builder()
.difference(insights.getDifference())
.common(insights.getCommon())
.implication(insights.getImplication())
.build();
}
// 라이브러리 생성 결과를 담는 내부 클래스
@lombok.Getter
@lombok.AllArgsConstructor
public static class LibraryCreateResult {
private final Library library;
private final int panelCount;
}
}