Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: product tag 생성 #72

Open
wants to merge 3 commits into
base: week7
Choose a base branch
from
Open
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 @@ -3,6 +3,7 @@
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import poomasi.domain.farm.dto.FarmRegisterRequest;
import poomasi.domain.farm.dto.FarmUpdateRequest;
Expand All @@ -17,8 +18,11 @@ public class FarmFarmerController {
private final FarmScheduleService farmScheduleService;

// TODO: 판매자만 접근가능하도록 인증/인가 annotation 추가
@Secured("ROLE_FARMER")
@PostMapping("")
public ResponseEntity<?> registerFarm(@RequestBody FarmRegisterRequest request) {
public ResponseEntity<?> registerFarm(

@RequestBody FarmRegisterRequest request) {
return ResponseEntity.ok(farmFarmerService.registerFarm(request));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package poomasi.domain.product.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import poomasi.domain.product.dto.ProductTagRequest;
import poomasi.domain.product.service.ProductTagService;

@Controller
@RequiredArgsConstructor
public class ProductTagController {

private final ProductTagService productTagService;

@Secured("ROLE_ADMIN")
@PostMapping("/api/products/tag")
public ResponseEntity<?> addTag(@RequestBody ProductTagRequest productTagRequest) {
productTagService.addTag(productTagRequest);
return new ResponseEntity<>(HttpStatus.CREATED);
}

@Secured("ROLE_ADMIN")
@DeleteMapping("/api/products/tag")
public ResponseEntity<?> deleteTag(@RequestBody ProductTagRequest productTagRequest) {
productTagService.deleteTag(productTagRequest);
return ResponseEntity.ok().build();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package poomasi.domain.product.dto;

import java.util.List;
import lombok.Builder;
import poomasi.domain.product.entity.Product;
import poomasi.domain.product.entity.ProductTagEnum;

@Builder
public record ProductResponse(
Expand All @@ -11,10 +13,13 @@ public record ProductResponse(
Integer stock,
String description,
String imageUrl,
Long categoryId
Long categoryId,
List<String> tags
) {

public static ProductResponse fromEntity(Product product) {
List<String> tags = product.getTags().stream().map(ProductTagEnum::getKoreanName).toList();

return ProductResponse.builder()
.id(product.getId())
.name(product.getName())
Expand All @@ -23,6 +28,7 @@ public static ProductResponse fromEntity(Product product) {
.description(product.getDescription())
.imageUrl(product.getImageUrl())
.categoryId(product.getCategoryId())
.tags(tags)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package poomasi.domain.product.dto;

public record ProductTagRequest(
Long productId,
String tagEnum
) {

}
12 changes: 12 additions & 0 deletions src/main/java/poomasi/domain/product/entity/Product.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package poomasi.domain.product.entity;

import jakarta.persistence.CascadeType;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
Expand Down Expand Up @@ -64,6 +70,12 @@ public class Product {
@JoinColumn(name = "entityId")
List<Review> reviewList = new ArrayList<>();

@ElementCollection(fetch = FetchType.EAGER)
Copy link
Contributor

Choose a reason for hiding this comment

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

혹시 Lazy대신 Eager로 설정하신 이유가 궁금합니다!!!

@CollectionTable(name = "product_tag", joinColumns = @JoinColumn(name = "product_id"))
@Column(name = "enum_value")
@Enumerated(EnumType.STRING)
List<ProductTagEnum> tags = new ArrayList<>();

@Comment("평균 평점")
private double averageRating = 0.0;

Expand Down
16 changes: 16 additions & 0 deletions src/main/java/poomasi/domain/product/entity/ProductTagEnum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package poomasi.domain.product.entity;

public enum ProductTagEnum {
ORGANIC("유기농"),
NonPesticide("무농약");
Copy link
Contributor

Choose a reason for hiding this comment

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

enum이니깐
NON_PESTICIDE("무농약"); 으로 쓰는 것은 어떨까요?


private final String value;

private ProductTagEnum(String value) {
this.value = value;
}

public String getKoreanName() {
return value;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package poomasi.domain.product.service;

import java.util.List;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import poomasi.domain.product.dto.ProductResponse;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package poomasi.domain.product.service;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import poomasi.domain.product.dto.ProductTagRequest;
import poomasi.domain.product.entity.Product;
import poomasi.domain.product.entity.ProductTagEnum;
import poomasi.domain.product.repository.ProductRepository;
import poomasi.global.error.BusinessError;
import poomasi.global.error.BusinessException;

@Service
@RequiredArgsConstructor
public class ProductTagService {

private final ProductRepository productRepository;

@Transactional
public void addTag(ProductTagRequest productTagRequest) {
Product product = CheckProduct(productTagRequest);

ProductTagEnum productTagEnum = null;
try {
productTagEnum = ProductTagEnum.valueOf(productTagRequest.tagEnum());
} catch (IllegalArgumentException e) {
throw new BusinessException(BusinessError.INVALID_TAG_NAME);
}

product.getTags().add(productTagEnum);
}

private Product CheckProduct(ProductTagRequest productTagRequest) {
return productRepository.findById(productTagRequest.productId())
Copy link
Contributor

Choose a reason for hiding this comment

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

findByIdAndDeletedAtIsNull로 바꾸는 것은 어떨까요?
혹시 제가 틀린 거라면 바로 피드백 주시면 감사하겠습니당

.orElseThrow(() -> new BusinessException(BusinessError.PRODUCT_NOT_FOUND));
}

@Transactional
public void deleteTag(ProductTagRequest productTagRequest) {
Product product = CheckProduct(productTagRequest);

ProductTagEnum productTagEnum = null;
try {
Copy link
Contributor

Choose a reason for hiding this comment

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

이 부분은 addTag에 있는 로직과 동일해서 공통화시키면 좋을 것 같다는 생각이 듭니당

productTagEnum = ProductTagEnum.valueOf(productTagRequest.tagEnum());
} catch (IllegalArgumentException e) {
throw new BusinessException(BusinessError.INVALID_TAG_NAME);
}

product.getTags().remove(productTagEnum);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

public record ReviewResponse
(Long id,
Long productId,
Long entityId,
Copy link
Contributor

Choose a reason for hiding this comment

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

product, farm 둘다 쓸 ㅇ예정이라 Entity로 네이밍을 수정하신건지 궁금합니다!

Copy link
Contributor

@jjt4515 jjt4515 Oct 31, 2024

Choose a reason for hiding this comment

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

저는 product랑 farm이랑 id값이 중복될 수 있으니 따로 type을 받아야겠다 생각했는데
ReviewRepository에서
@query("select r from Review r where r.entityId = :productId and r.entityType = 'PRODUCT'")
와 같은 쿼리문 써서 type 받을 필요도 없도록 잘 구현해주셨네요 하나 배웠습니다~!

다만 리뷰를 가지는 엔티티가 많을 경우에는 type을 받으면 하나의 로직으로 공통화하기 좋을 것 같기는 하네여

//Long reviewerId,
Float rating,
String content
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/poomasi/global/error/BusinessError.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package poomasi.global.error;

import org.springframework.boot.actuate.autoconfigure.observation.ObservationProperties.Http;
import org.springframework.http.HttpStatus;

import lombok.AllArgsConstructor;
Expand Down Expand Up @@ -48,6 +49,10 @@ public enum BusinessError {
RESERVATION_ALREADY_CANCELED(HttpStatus.BAD_REQUEST, "이미 취소된 예약입니다."),
RESERVATION_CANCELLATION_PERIOD_EXPIRED(HttpStatus.BAD_REQUEST, "예약 취소 기간이 지났습니다."),

//ProductTag
INVALID_TAG_NAME(HttpStatus.BAD_REQUEST, "존재하지 않는 태그명입니다."),
TAG_NOT_FOUND(HttpStatus.NOT_FOUND, "태그가 존재하지 않습니다."),

// ETC
START_DATE_SHOULD_BE_BEFORE_END_DATE(HttpStatus.BAD_REQUEST, "시작 날짜는 종료 날짜보다 이전이어야 합니다.");

Expand Down