Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@
public interface BrandDescribeTagRepository extends JpaRepository<BrandDescribeTag, Long> {

List<BrandDescribeTag> findAllByBrandId(Long brandId);

List<BrandDescribeTag> findAllByBrandIdIn(List<Long> brandIds);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.example.RealMatch.user.application.service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.RealMatch.brand.domain.entity.BrandDescribeTag;
import com.example.RealMatch.brand.domain.repository.BrandDescribeTagRepository;
import com.example.RealMatch.match.domain.entity.enums.BrandSortType;
import com.example.RealMatch.match.domain.entity.enums.CampaignSortType;
import com.example.RealMatch.user.domain.repository.UserFavoriteBrandQueryRepository;
import com.example.RealMatch.user.domain.repository.UserFavoriteCampaignQueryRepository;
import com.example.RealMatch.user.presentation.dto.response.FavoriteBrandDto;
import com.example.RealMatch.user.presentation.dto.response.FavoriteBrandListResponseDto;
import com.example.RealMatch.user.presentation.dto.response.FavoriteCampaignDto;
import com.example.RealMatch.user.presentation.dto.response.FavoriteCampaignListResponseDto;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class UserFavoriteService {

private final UserFavoriteCampaignQueryRepository userFavoriteCampaignQueryRepository;
private final UserFavoriteBrandQueryRepository userFavoriteBrandQueryRepository;
private final BrandDescribeTagRepository brandDescribeTagRepository;

/* ===== 찜한 브랜드 ===== */
public FavoriteBrandListResponseDto getMyFavoriteBrands(
Long userId,
BrandSortType sortType
) {
List<FavoriteBrandDto> brands =
userFavoriteBrandQueryRepository.findFavoriteBrands(userId, sortType);

if (brands.isEmpty()) {
return FavoriteBrandListResponseDto.empty();
}

List<Long> brandIds = brands.stream()
.map(FavoriteBrandDto::getBrandId)
.toList();

List<BrandDescribeTag> tags =
brandDescribeTagRepository.findAllByBrandIdIn(brandIds);

Map<Long, List<String>> tagMap = tags.stream()
.collect(Collectors.groupingBy(
tag -> tag.getBrand().getId(),
Collectors.mapping(
BrandDescribeTag::getBrandDescribeTag,
Collectors.toList()
)
));

brands.forEach(dto ->
dto.setTags(tagMap.getOrDefault(dto.getBrandId(), List.of()))
);

return FavoriteBrandListResponseDto.builder()
.count(brands.size())
.brands(brands)
.build();
Comment on lines +60 to +67
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

FavoriteBrandDto를 불변으로 변경하는 것과 연관하여, forEach를 사용해 DTO 리스트를 직접 수정하는 대신, stream().map()을 사용하여 태그 정보가 포함된 새로운 DTO 객체를 생성하는 것이 좋습니다. 이는 코드의 불변성을 유지하고 가독성을 높이는 데 도움이 됩니다.

Suggested change
brands.forEach(dto ->
dto.setTags(tagMap.getOrDefault(dto.getBrandId(), List.of()))
);
return FavoriteBrandListResponseDto.builder()
.count(brands.size())
.brands(brands)
.build();
final List<FavoriteBrandDto> brandsWithTags = brands.stream()
.map(dto -> new FavoriteBrandDto(
dto.getBrandId(),
dto.getBrandName(),
dto.getBrandLogoUrl(),
dto.getMatchingRatio(),
dto.getLikeCount(),
tagMap.getOrDefault(dto.getBrandId(), List.of())
))
.toList();
return FavoriteBrandListResponseDto.builder()
.count(brandsWithTags.size())
.brands(brandsWithTags)
.build();
References
  1. Avoid using @Setter on domain or DTO objects to prevent uncontrolled external modifications. If mutation is needed, provide specific methods for it.

}

/* ===== 찜한 캠페인 ===== */
public FavoriteCampaignListResponseDto getMyFavoriteCampaigns(
Long userId,
CampaignSortType sortType
) {
List<FavoriteCampaignDto> campaigns =
userFavoriteCampaignQueryRepository.findFavoriteCampaigns(userId, sortType);

if (campaigns.isEmpty()) {
return FavoriteCampaignListResponseDto.empty();
}

return FavoriteCampaignListResponseDto.builder()
.count(campaigns.size())
.campaigns(campaigns)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.example.RealMatch.user.domain.entity.enums;

public enum FavoriteType {
BRAND, CAMPAIGN
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.RealMatch.user.domain.repository;

import java.util.List;

import com.example.RealMatch.match.domain.entity.enums.BrandSortType;
import com.example.RealMatch.user.presentation.dto.response.FavoriteBrandDto;

public interface UserFavoriteBrandQueryRepository {

List<FavoriteBrandDto> findFavoriteBrands(
Long userId,
BrandSortType sortType
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.example.RealMatch.user.domain.repository;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.example.RealMatch.brand.domain.entity.QBrand;
import com.example.RealMatch.brand.domain.entity.QBrandLike;
import com.example.RealMatch.match.domain.entity.QMatchBrandHistory;
import com.example.RealMatch.match.domain.entity.enums.BrandSortType;
import com.example.RealMatch.user.presentation.dto.response.FavoriteBrandDto;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
public class UserFavoriteBrandRepositoryImpl
implements UserFavoriteBrandQueryRepository {

private final JPAQueryFactory queryFactory;

// ✅ Checkstyle 대응: static final → 대문자 상수
private static final QBrandLike BRAND_LIKE = QBrandLike.brandLike;
private static final QBrand BRAND = QBrand.brand;
private static final QMatchBrandHistory MATCH_BRAND_HISTORY =
QMatchBrandHistory.matchBrandHistory;

@Override
public List<FavoriteBrandDto> findFavoriteBrands(
Long userId,
BrandSortType sortType
) {
List<OrderSpecifier<?>> orderSpecifiers =
buildBrandOrderSpecifiers(sortType);

return queryFactory
.select(Projections.constructor(
FavoriteBrandDto.class,
BRAND.id,
BRAND.brandName,
BRAND.logoUrl,
brandMatchingRatioExpression(),
brandLikeCountExpression(),
Expressions.nullExpression(List.class) // tags는 나중에 채움
))
.from(BRAND_LIKE)
.join(BRAND_LIKE.brand, BRAND)
.leftJoin(MATCH_BRAND_HISTORY).on(
MATCH_BRAND_HISTORY.brand.id.eq(BRAND.id),
MATCH_BRAND_HISTORY.user.id.eq(userId),
MATCH_BRAND_HISTORY.isDeprecated.eq(false)
)
.where(BRAND_LIKE.user.id.eq(userId))
.orderBy(orderSpecifiers.toArray(new OrderSpecifier[0]))
.fetch();
}

private List<OrderSpecifier<?>> buildBrandOrderSpecifiers(
BrandSortType sortType
) {
if (sortType == null) {
sortType = BrandSortType.MATCH_SCORE;
}

return switch (sortType) {
case MATCH_SCORE -> List.of(
MATCH_BRAND_HISTORY.matchingRatio.desc().nullsLast(),
BRAND.id.asc()
);

case POPULARITY -> List.of(
popularityDesc(),
MATCH_BRAND_HISTORY.matchingRatio.desc().nullsLast(),
BRAND.id.asc()
);

case NEWEST -> List.of(
BRAND.createdAt.desc(),
BRAND.id.asc()
);
};
}

private OrderSpecifier<?> popularityDesc() {
return new OrderSpecifier<>(
com.querydsl.core.types.Order.DESC,
brandLikeCountExpression(),
OrderSpecifier.NullHandling.NullsLast
);
}

private Expression<Long> brandLikeCountExpression() {
QBrandLike bl = QBrandLike.brandLike;

return JPAExpressions
.select(bl.id.count())
.from(bl)
.where(bl.brand.id.eq(BRAND.id));
}

private Expression<Long> brandMatchingRatioExpression() {
return Expressions.numberTemplate(
Long.class,
"COALESCE({0}, 0)",
MATCH_BRAND_HISTORY.matchingRatio
);
}
Comment on lines +107 to +113
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Expressions.numberTemplate를 사용하여 COALESCE 함수를 문자열로 직접 사용하고 있습니다. QueryDSL이 제공하는 타입-세이프한 coalesce() 메소드를 사용하면 코드의 가독성과 데이터베이스 이식성을 높일 수 있습니다.

    private Expression<Long> brandMatchingRatioExpression() {
        return MATCH_BRAND_HISTORY.matchingRatio.coalesce(0L);
    }

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.RealMatch.user.domain.repository;

import java.util.List;

import com.example.RealMatch.match.domain.entity.enums.CampaignSortType;
import com.example.RealMatch.user.presentation.dto.response.FavoriteCampaignDto;

public interface UserFavoriteCampaignQueryRepository {

List<FavoriteCampaignDto> findFavoriteCampaigns(
Long userId,
CampaignSortType sortType
);
}
Loading
Loading