-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryService.java
More file actions
830 lines (725 loc) · 46.6 KB
/
LibraryService.java
File metadata and controls
830 lines (725 loc) · 46.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
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
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.domain.panel.repository.projection.PanelWithRawDataDTO;
import DiffLens.back_end.domain.search.service.interfaces.SearchPanelService;
import DiffLens.back_end.global.dto.ResponsePageDTO;
import DiffLens.back_end.global.fastapi.FastApiService;
import DiffLens.back_end.global.fastapi.dto.request.FastLibraryChartRequestDTO;
import DiffLens.back_end.global.fastapi.dto.response.FastChartResponseDTO;
import DiffLens.back_end.global.fastapi.dto.response.FastLibraryChartResponseDTO;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
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;
private final SearchPanelService searchPanelService;
@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 서버로 비교 요청
FastLibraryCompareResponseDTO.CompareResult fastApiResponse = fastApiService
.compareLibraries(library1.getId(), library2.getId());
// 5. 응답 데이터 구성
return LibraryCompareResponseDTO.CompareResult.builder()
.group1(convertGroupInfo(fastApiResponse.getCohort1(), library1))
.group2(convertGroupInfo(fastApiResponse.getCohort2(), library2))
.keyCharacteristics(convertCharacteristics(fastApiResponse.getCharacteristics()))
.comparisons(convertBasicInfoComparisons(
fastApiResponse.getBasicInfo(),
fastApiResponse.getRegionDistribution(),
fastApiResponse.getGenderDistribution()))
.insights(convertKeyInsights(fastApiResponse.getKeyInsights()))
.build();
}
/**
* CohortBasicInfo를 GroupInfo로 변환
*/
private LibraryCompareResponseDTO.GroupInfo convertGroupInfo(
FastLibraryCompareResponseDTO.CohortBasicInfo cohortInfo,
Library library) {
return LibraryCompareResponseDTO.GroupInfo.builder()
.libraryId(Long.parseLong(cohortInfo.getCohortId()))
.libraryName(cohortInfo.getCohortName())
.totalCount(cohortInfo.getPanelCount())
.filters(convertFilters(library))
.build();
}
/**
* CharacteristicComparison 리스트를 KeyCharacteristic 리스트로 변환
*/
private List<LibraryCompareResponseDTO.KeyCharacteristic> convertCharacteristics(
List<FastLibraryCompareResponseDTO.CharacteristicComparison> characteristics) {
if (characteristics == null || characteristics.isEmpty()) {
return List.of();
}
return characteristics.stream()
.map(fast -> LibraryCompareResponseDTO.KeyCharacteristic.builder()
.characteristic(fast.getCharacteristic())
.description(null) // 새 스키마에는 description이 없음
.group1Percentage(fast.getCohort1Percentage() != null
? fast.getCohort1Percentage().intValue()
: 0)
.group2Percentage(fast.getCohort2Percentage() != null
? fast.getCohort2Percentage().intValue()
: 0)
.difference(fast.getDifferencePercentage() != null
? fast.getDifferencePercentage().intValue()
: 0)
.build())
.toList();
}
/**
* BasicInfoComparison 리스트를 Comparisons로 변환
* basic_info에서 메트릭별로 값을 추출하여 GroupMetrics 구성
* region_distribution 데이터를 group1, group2의 지역 필드에 매핑
* gender_distribution 데이터를 group1, group2의 성별 필드에 매핑
*/
private LibraryCompareResponseDTO.Comparisons convertBasicInfoComparisons(
List<FastLibraryCompareResponseDTO.BasicInfoComparison> basicInfo,
FastLibraryCompareResponseDTO.RegionDistribution regionDistribution,
FastLibraryCompareResponseDTO.GenderDistribution genderDistribution) {
if (basicInfo == null || basicInfo.isEmpty()) {
return LibraryCompareResponseDTO.Comparisons.builder()
.group1(LibraryCompareResponseDTO.GroupMetrics.builder().build())
.group2(LibraryCompareResponseDTO.GroupMetrics.builder().build())
.build();
}
// basic_info에서 메트릭별로 값 추출
LibraryCompareResponseDTO.GroupMetrics.GroupMetricsBuilder group1Builder = LibraryCompareResponseDTO.GroupMetrics
.builder();
LibraryCompareResponseDTO.GroupMetrics.GroupMetricsBuilder group2Builder = LibraryCompareResponseDTO.GroupMetrics
.builder();
for (FastLibraryCompareResponseDTO.BasicInfoComparison info : basicInfo) {
String metricName = info.getMetricName();
Double cohort1Value = info.getCohort1Value();
Double cohort2Value = info.getCohort2Value();
switch (metricName) {
case "age":
if (cohort1Value != null)
group1Builder.avgAge(cohort1Value);
if (cohort2Value != null)
group2Builder.avgAge(cohort2Value);
break;
case "family_size":
if (cohort1Value != null)
group1Builder.avgFamily(cohort1Value);
if (cohort2Value != null)
group2Builder.avgFamily(cohort2Value);
break;
case "children_count":
if (cohort1Value != null)
group1Builder.avgChildren(cohort1Value);
if (cohort2Value != null)
group2Builder.avgChildren(cohort2Value);
break;
case "personal_income":
if (cohort1Value != null)
group1Builder.avgPersonalIncome(cohort1Value.intValue());
if (cohort2Value != null)
group2Builder.avgPersonalIncome(cohort2Value.intValue());
break;
case "household_income":
if (cohort1Value != null)
group1Builder.avgFamilyIncome(cohort1Value.intValue());
if (cohort2Value != null)
group2Builder.avgFamilyIncome(cohort2Value.intValue());
break;
case "car_ownership":
if (cohort1Value != null)
group1Builder.ratePossessingCar(cohort1Value.intValue());
if (cohort2Value != null)
group2Builder.ratePossessingCar(cohort2Value.intValue());
break;
}
}
// region_distribution 데이터를 group1, group2의 지역 필드에 매핑
if (regionDistribution != null) {
// cohort_1 (group1) 지역 데이터 매핑
if (regionDistribution.getCohort1() != null) {
java.util.Map<String, Double> cohort1Region = regionDistribution.getCohort1();
group1Builder.seoul(cohort1Region.getOrDefault("서울", 0.0).intValue());
group1Builder.gyeonggi(cohort1Region.getOrDefault("경기", 0.0).intValue());
group1Builder.busan(cohort1Region.getOrDefault("부산", 0.0).intValue());
group1Builder.regionEtc(cohort1Region.getOrDefault("기타", 0.0).intValue());
}
// cohort_2 (group2) 지역 데이터 매핑
if (regionDistribution.getCohort2() != null) {
java.util.Map<String, Double> cohort2Region = regionDistribution.getCohort2();
group2Builder.seoul(cohort2Region.getOrDefault("서울", 0.0).intValue());
group2Builder.gyeonggi(cohort2Region.getOrDefault("경기", 0.0).intValue());
group2Builder.busan(cohort2Region.getOrDefault("부산", 0.0).intValue());
group2Builder.regionEtc(cohort2Region.getOrDefault("기타", 0.0).intValue());
}
}
// gender_distribution 데이터를 group1, group2의 성별 필드에 매핑
if (genderDistribution != null) {
// cohort_1 (group1) 성별 데이터 매핑
if (genderDistribution.getCohort1() != null) {
java.util.Map<String, Double> cohort1Gender = genderDistribution.getCohort1();
group1Builder.male(cohort1Gender.getOrDefault("남성", 0.0).intValue());
group1Builder.female(cohort1Gender.getOrDefault("여성", 0.0).intValue());
}
// cohort_2 (group2) 성별 데이터 매핑
if (genderDistribution.getCohort2() != null) {
java.util.Map<String, Double> cohort2Gender = genderDistribution.getCohort2();
group2Builder.male(cohort2Gender.getOrDefault("남성", 0.0).intValue());
group2Builder.female(cohort2Gender.getOrDefault("여성", 0.0).intValue());
}
}
return LibraryCompareResponseDTO.Comparisons.builder()
.group1(group1Builder.build())
.group2(group2Builder.build())
.build();
}
/**
* KeyInsights를 Insights로 변환 (nullable 처리)
*/
private LibraryCompareResponseDTO.Insights convertKeyInsights(
FastLibraryCompareResponseDTO.KeyInsights keyInsights) {
if (keyInsights == null) {
return null;
}
return LibraryCompareResponseDTO.Insights.builder()
.difference(keyInsights.getMainDifferences())
.common(keyInsights.getCommonalities())
.implication(keyInsights.getImplications())
.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.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);
}
/**
* 라이브러리 대시보드 조회 (차트 포함)
*/
@Transactional(readOnly = true)
public LibraryResponseDTO.LibraryDashboard getLibraryDashboard(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. 패널 ID 배열 조회
List<String> panelIds = library.getPanelIds();
if (panelIds == null || panelIds.isEmpty()) {
throw new ErrorHandler(ErrorStatus.BAD_REQUEST);
}
// 3. 서브서버 API 호출
FastLibraryChartRequestDTO request = FastLibraryChartRequestDTO.builder()
.panelIds(panelIds)
.libraryName(library.getLibraryName())
.build();
FastLibraryChartResponseDTO.LibraryChartResponse chartResponse = fastApiService
.getChartsFromLibrary(request);
// 4. 차트 데이터 변환
LibraryResponseDTO.LibraryDashboard.ChartData mainChart = convertToChartData(
chartResponse.getMainChart());
List<LibraryResponseDTO.LibraryDashboard.ChartData> subCharts = chartResponse.getSubCharts()
.stream()
.map(this::convertToChartData)
.toList();
// 5. 응답 구성
return LibraryResponseDTO.LibraryDashboard.builder()
.libraryId(library.getId())
.libraryName(library.getLibraryName())
.panelCount(panelIds.size())
.mainChart(mainChart)
.subCharts(subCharts)
.build();
}
/**
* 라이브러리 패널 목록 조회 (페이징, 일치율 없음)
*/
@Transactional(readOnly = true)
public LibraryResponseDTO.LibraryPanels getLibraryPanels(Long libraryId, Integer pageNum, Integer size,
Member member) {
// 1. 페이지 번호 예외처리
if (pageNum < 1) {
throw new ErrorHandler(ErrorStatus.PAGE_NO_INVALID);
}
// 2. 라이브러리 조회 및 권한 검증
Library library = libraryRepository.findById(libraryId)
.orElseThrow(() -> new ErrorHandler(ErrorStatus.BAD_REQUEST));
if (!library.getMember().getId().equals(member.getId())) {
throw new ErrorHandler(ErrorStatus.FORBIDDEN);
}
// 3. 패널 ID 배열 조회
List<String> panelIds = library.getPanelIds();
if (panelIds == null || panelIds.isEmpty()) {
return LibraryResponseDTO.LibraryPanels.builder()
.keys(List.of("respondent_id", "gender", "age", "residence",
"personal_income"))
.values(List.of())
.pageInfo(ResponsePageDTO.OffsetLimitPageInfo.builder()
.offset(0)
.currentPage(1)
.currentPageCount(0)
.totalPageCount(0)
.limit(size)
.totalCount(0L)
.hasNext(false)
.hasPrevious(false)
.build())
.build();
}
// 4. 페이징을 위한 Pageable 객체 생성
Pageable pageable = PageRequest.of(pageNum - 1, size);
// 5. PanelId 목록을 이용해서 Panel 조회
Page<PanelWithRawDataDTO> panelDtoList = searchPanelService.getPanelDtoList(panelIds, pageable);
// 6. 페이지 범위 초과 검사
if (pageNum > panelDtoList.getTotalPages() && panelDtoList.getTotalPages() > 0) {
throw new ErrorHandler(ErrorStatus.PAGE_NO_EXCEED);
}
// 7. Panel 목록을 응답 형식으로 변환 (일치율 없음)
List<LibraryResponseDTO.LibraryPanels.PanelResponseValues> values = panelDtoList.stream()
.map(panel -> LibraryResponseDTO.LibraryPanels.PanelResponseValues.builder()
.respondentId(panel.getId())
.gender(panel.getGender() != null ? panel.getGender().getDisplayValue()
: null)
.age(panel.getAge() != null ? panel.getAge().toString() : null)
.residence(panel.getResidence())
.personalIncome(panel.getPersonalIncome())
.build())
.toList();
// 8. 페이징 정보 생성
ResponsePageDTO.OffsetLimitPageInfo pageInfo = ResponsePageDTO.OffsetLimitPageInfo
.from(panelDtoList);
return LibraryResponseDTO.LibraryPanels.builder()
.keys(List.of("respondent_id", "gender", "age", "residence", "personal_income"))
.values(values)
.pageInfo(pageInfo)
.build();
}
/**
* FastAPI ChartData를 LibraryDashboard ChartData로 변환
*/
private LibraryResponseDTO.LibraryDashboard.ChartData convertToChartData(
FastChartResponseDTO.ChartData fastChartData) {
if (fastChartData == null) {
return null;
}
List<LibraryResponseDTO.LibraryDashboard.ChartDataPoint> dataPoints = fastChartData.getData()
.stream()
.map(this::convertToChartDataPoint)
.toList();
return LibraryResponseDTO.LibraryDashboard.ChartData.builder()
.chartType(fastChartData.getChartType())
.metric(fastChartData.getMetric())
.title(fastChartData.getTitle())
.reasoning(fastChartData.getReasoning())
.data(dataPoints)
.build();
}
/**
* FastAPI ChartDataPoint를 LibraryDashboard ChartDataPoint로 변환
*/
private LibraryResponseDTO.LibraryDashboard.ChartDataPoint convertToChartDataPoint(
FastChartResponseDTO.ChartDataPoint fastDataPoint) {
if (fastDataPoint == null) {
return null;
}
return LibraryResponseDTO.LibraryDashboard.ChartDataPoint.builder()
.category(fastDataPoint.getCategory())
.value(fastDataPoint.getValue())
.male(fastDataPoint.getMale())
.maleMax(fastDataPoint.getMaleMax())
.female(fastDataPoint.getFemale())
.femaleMax(fastDataPoint.getFemaleMax())
.id(fastDataPoint.getId())
.name(fastDataPoint.getName())
.build();
}
// 라이브러리 생성 결과를 담는 내부 클래스
@lombok.Getter
@lombok.AllArgsConstructor
public static class LibraryCreateResult {
private final Library library;
private final int panelCount;
}
}