From cb6dbf51517d1bb0491a63cd772ab98b8e14f40a Mon Sep 17 00:00:00 2001 From: Sejin Park <95167215+sejineer@users.noreply.github.com> Date: Fri, 5 Jan 2024 14:57:18 +0900 Subject: [PATCH 1/5] =?UTF-8?q?[FIX]:=20=EC=98=88/=EC=A0=81=EA=B8=88=20?= =?UTF-8?q?=EC=83=81=ED=92=88=20=EC=A1=B0=ED=9A=8C=20Bookmark=20=EC=97=AC?= =?UTF-8?q?=EB=B6=80=20Response=20=EC=B6=94=EA=B0=80=20(#47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: 예금 조회 API (조건 별 조회 가능) 구현 * [FEAT]: 적금 조회(조건별 조회) API 구현 * [FEAT]: 예금 상세 조회 API 구현 * [FEAT]: 적금 상세 조회 API 구현 * [FIX]: 총 페이지 수 + 1 현상 수정 * [FEAT]: 은행 리스트 조건 별 조회 API 구현 * [FEAT]: 상품 조회에 유저가 좋아요 눌렀는지 여부 response 추가 --- .../FinancialProductServiceImpl.java | 16 +++-- .../finfellows/domain/product/domain/CMA.java | 65 +++++++++++++++++++ .../FinancialProductQueryDslRepository.java | 2 +- ...inancialProductQueryDslRepositoryImpl.java | 8 ++- .../response/SearchFinancialProductRes.java | 4 +- 5 files changed, 85 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/finfellows/domain/product/domain/CMA.java diff --git a/src/main/java/com/finfellows/domain/product/application/FinancialProductServiceImpl.java b/src/main/java/com/finfellows/domain/product/application/FinancialProductServiceImpl.java index a414114..3df5461 100644 --- a/src/main/java/com/finfellows/domain/product/application/FinancialProductServiceImpl.java +++ b/src/main/java/com/finfellows/domain/product/application/FinancialProductServiceImpl.java @@ -1,5 +1,6 @@ package com.finfellows.domain.product.application; +import com.finfellows.domain.bookmark.domain.repository.FinancialProductBookmarkRepository; import com.finfellows.domain.product.domain.FinancialProduct; import com.finfellows.domain.product.domain.FinancialProductOption; import com.finfellows.domain.product.domain.FinancialProductType; @@ -29,23 +30,24 @@ public class FinancialProductServiceImpl implements FinancialProductService { private final FinancialProductRepository financialProductRepository; private final FinancialProductOptionRepository financialProductOptionRepository; + private final FinancialProductBookmarkRepository financialProductBookmarkRepository; @Override - public PagedResponse findDepositProducts(UserPrincipal userPrincipal, FinancialProductSearchCondition financialProductSearchCondition, Pageable pageable) { - Page financialProducts = financialProductRepository.findFinancialProducts(financialProductSearchCondition, pageable, FinancialProductType.DEPOSIT); + public PagedResponse findDepositProducts(final UserPrincipal userPrincipal, final FinancialProductSearchCondition financialProductSearchCondition, final Pageable pageable) { + Page financialProducts = financialProductRepository.findFinancialProducts(financialProductSearchCondition, pageable, FinancialProductType.DEPOSIT, userPrincipal.getId()); return new PagedResponse<>(financialProducts); } @Override - public PagedResponse findSavingProducts(UserPrincipal userPrincipal, FinancialProductSearchCondition financialProductSearchCondition, Pageable pageable) { - Page financialProducts = financialProductRepository.findFinancialProducts(financialProductSearchCondition, pageable, FinancialProductType.SAVING); + public PagedResponse findSavingProducts(final UserPrincipal userPrincipal, final FinancialProductSearchCondition financialProductSearchCondition, final Pageable pageable) { + Page financialProducts = financialProductRepository.findFinancialProducts(financialProductSearchCondition, pageable, FinancialProductType.SAVING, userPrincipal.getId()); return new PagedResponse<>(financialProducts); } @Override - public DepositDetailRes getDepositDetail(UserPrincipal userPrincipal, Long depositId) { + public DepositDetailRes getDepositDetail(final UserPrincipal userPrincipal, final Long depositId) { FinancialProduct deposit = financialProductRepository.findById(depositId) .orElseThrow(InvalidFinancialProductException::new); @@ -67,7 +69,7 @@ public DepositDetailRes getDepositDetail(UserPrincipal userPrincipal, Long depos } @Override - public SavingDetailRes getSavingDetail(UserPrincipal userPrincipal, Long savingId) { + public SavingDetailRes getSavingDetail(final UserPrincipal userPrincipal, final Long savingId) { FinancialProduct saving = financialProductRepository.findById(savingId) .orElseThrow(InvalidFinancialProductException::new); @@ -89,7 +91,7 @@ public SavingDetailRes getSavingDetail(UserPrincipal userPrincipal, Long savingI } @Override - public List findBanks(String bankGroupNo) { + public List findBanks(final String bankGroupNo) { return financialProductRepository.findBanks(bankGroupNo); } diff --git a/src/main/java/com/finfellows/domain/product/domain/CMA.java b/src/main/java/com/finfellows/domain/product/domain/CMA.java new file mode 100644 index 0000000..e722093 --- /dev/null +++ b/src/main/java/com/finfellows/domain/product/domain/CMA.java @@ -0,0 +1,65 @@ +package com.finfellows.domain.product.domain; + +import com.finfellows.domain.common.BaseEntity; +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "CMA") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Getter +public class CMA extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", updatable = false) + private Long id; + + @Column(name="company_name") + private String companyName; + + @Column(name="product_name") + private String productName; + + @Column(name="cma_type") + private String cmaType; + + @Column(name = "disclosure_month") + private String disclosureMonth; + + @Column(name="maturity_interest_rate") + private String maturityInterestRate; + + @Column(name="special_condition") + private String specialCondition; + + @Column(name="join_way") + private String joinWay; + + @Column(name="etc_note") + private String etcNote; + + @Column(name="product_url") + private String productUrl; + + @Column(name="deposit_protection") + private String depositProtection; + + @Builder + public CMA(String companyName, String productName, String cmaType, String disclosureMonth, String maturityInterestRate, String specialCondition, String joinWay, String etcNote, String productUrl, String depositProtection) { + this.companyName = companyName; + this.productName = productName; + this.cmaType = cmaType; + this.disclosureMonth = disclosureMonth; + this.maturityInterestRate = maturityInterestRate; + this.specialCondition = specialCondition; + this.joinWay = joinWay; + this.etcNote = etcNote; + this.productUrl = productUrl; + this.depositProtection = depositProtection; + } + +} \ No newline at end of file diff --git a/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepository.java b/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepository.java index 2260c1e..01ed551 100644 --- a/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepository.java +++ b/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepository.java @@ -10,7 +10,7 @@ public interface FinancialProductQueryDslRepository { - Page findFinancialProducts(FinancialProductSearchCondition financialProductSearchCondition, Pageable pageable, FinancialProductType financialProductType); + Page findFinancialProducts(FinancialProductSearchCondition financialProductSearchCondition, Pageable pageable, FinancialProductType financialProductType, Long userId); List findBanks(String bankGroupNo); } diff --git a/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepositoryImpl.java b/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepositoryImpl.java index 1ab49e5..f697912 100644 --- a/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepositoryImpl.java +++ b/src/main/java/com/finfellows/domain/product/domain/repository/FinancialProductQueryDslRepositoryImpl.java @@ -1,5 +1,6 @@ package com.finfellows.domain.product.domain.repository; +import com.finfellows.domain.bookmark.domain.QFinancialProductBookmark; import com.finfellows.domain.product.domain.FinancialProductType; import com.finfellows.domain.product.dto.condition.FinancialProductSearchCondition; import com.finfellows.domain.product.dto.response.QSearchFinancialProductRes; @@ -26,10 +27,13 @@ public class FinancialProductQueryDslRepositoryImpl implements FinancialProductQ private final JPAQueryFactory queryFactory; @Override - public Page findFinancialProducts(FinancialProductSearchCondition financialProductSearchCondition, Pageable pageable, FinancialProductType financialProductType) { + public Page findFinancialProducts(FinancialProductSearchCondition financialProductSearchCondition, Pageable pageable, FinancialProductType financialProductType, Long userId) { + QFinancialProductBookmark financialProductBookmark = QFinancialProductBookmark.financialProductBookmark; + List results = queryFactory .select(new QSearchFinancialProductRes( financialProduct.id, + financialProductBookmark.id.isNotNull(), financialProduct.productName, financialProduct.companyName, financialProductOption.maximumPreferredInterestRate, @@ -37,6 +41,8 @@ public Page findFinancialProducts(FinancialProductSea )) .from(financialProductOption) .leftJoin(financialProductOption.financialProduct, financialProduct) + .leftJoin(financialProductBookmark) + .on(financialProductBookmark.financialProduct.eq(financialProduct).and(financialProductBookmark.user.id.eq(userId))) .where( financialProduct.financialProductType.eq(financialProductType), typeEq(financialProductSearchCondition.getType()), diff --git a/src/main/java/com/finfellows/domain/product/dto/response/SearchFinancialProductRes.java b/src/main/java/com/finfellows/domain/product/dto/response/SearchFinancialProductRes.java index f4df387..259d734 100644 --- a/src/main/java/com/finfellows/domain/product/dto/response/SearchFinancialProductRes.java +++ b/src/main/java/com/finfellows/domain/product/dto/response/SearchFinancialProductRes.java @@ -7,14 +7,16 @@ public class SearchFinancialProductRes { private Long id; + private Boolean isLiked; private String productName; private String bankName; private String maxInterestRate; private String interestRate; @QueryProjection - public SearchFinancialProductRes(Long id, String productName, String bankName, String maxInterestRate, String interestRate) { + public SearchFinancialProductRes(Long id, Boolean isLiked, String productName, String bankName, String maxInterestRate, String interestRate) { this.id = id; + this.isLiked = isLiked; this.productName = productName; this.bankName = bankName; this.maxInterestRate = maxInterestRate; From 806c6790720d9b2df0b00f63e66c3b40ee26c2e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=EC=9E=AC=ED=98=81?= <67510260+LEEJaeHyeok97@users.noreply.github.com> Date: Sat, 6 Jan 2024 21:22:37 +0900 Subject: [PATCH 2/5] [FEAT]: #44 edit entity (#45) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [FEAT]#9 즐겨찾기 API 구현 * [FIX]#9 ApiResponse 수정 * [FEAT]#10 마이페이지 즐겨찾기 내역 조회 API 구현 * [FEAT]#44 policyInfo 엔티티 수정, toDto 수정 --- .../bookmark/dto/PolicyInfoBookmarkRes.java | 15 +++++++++------ .../domain/policyinfo/domain/PolicyInfo.java | 13 ++++++++----- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/finfellows/domain/bookmark/dto/PolicyInfoBookmarkRes.java b/src/main/java/com/finfellows/domain/bookmark/dto/PolicyInfoBookmarkRes.java index 2cf7064..c525ebe 100644 --- a/src/main/java/com/finfellows/domain/bookmark/dto/PolicyInfoBookmarkRes.java +++ b/src/main/java/com/finfellows/domain/bookmark/dto/PolicyInfoBookmarkRes.java @@ -10,20 +10,23 @@ @Data public class PolicyInfoBookmarkRes { private Long id; - private String url; + private String contentName; + private String content; @Builder - public PolicyInfoBookmarkRes(Long id, String url) { - this.id = id; - this.url = url; + public PolicyInfoBookmarkRes(String contentName, String content) { + this.contentName = contentName; + this.content = content; } + + public static List toDto(List bookmarks) { return bookmarks.stream() .map(bookmark -> PolicyInfoBookmarkRes.builder() - .id(bookmark.getPolicyInfo().getId()) - .url(bookmark.getPolicyInfo().getUrl()) + .contentName(bookmark.getPolicyInfo().getContentName()) + .content(bookmark.getPolicyInfo().getContent()) .build()) .collect(Collectors.toList()); } diff --git a/src/main/java/com/finfellows/domain/policyinfo/domain/PolicyInfo.java b/src/main/java/com/finfellows/domain/policyinfo/domain/PolicyInfo.java index c12d9c5..9786189 100644 --- a/src/main/java/com/finfellows/domain/policyinfo/domain/PolicyInfo.java +++ b/src/main/java/com/finfellows/domain/policyinfo/domain/PolicyInfo.java @@ -20,12 +20,15 @@ public class PolicyInfo extends BaseEntity { @Column(name = "id", updatable = false) private Long id; - @Column(name="url", nullable = false, unique = true) - private String url; + @Column(name = "content_name", nullable = false, unique = true) + private String contentName; + + @Column(name="content", nullable = false, unique = true) + private String content; @Builder - public PolicyInfo(String url){ - this.url=url; + public PolicyInfo(String contentName, String content) { + this.contentName = contentName; + this.content = content; } - } From cae15c3dcc62f123b5afbcb76ca90fe95fc8d9b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=EC=9E=AC=ED=98=81?= <67510260+LEEJaeHyeok97@users.noreply.github.com> Date: Sat, 6 Jan 2024 21:23:40 +0900 Subject: [PATCH 3/5] [FEAT]: #1 kakao login (#49) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [FEAT]#9 즐겨찾기 API 구현 * [FIX]#9 ApiResponse 수정 * [FEAT]#10 마이페이지 즐겨찾기 내역 조회 API 구현 * [FEAT]#48 사용자 정보 조회 API 구현, 로그인 시 출력정보에 역할 추가, 안쓰는 코드 수정 --- .../CustomTokenProviderService.java | 1 + .../domain/auth/application/KakaoService.java | 14 +++++++++- .../finfellows/domain/auth/dto/AuthRes.java | 7 ++++- .../auth/presentation/AuthController.java | 28 ++++++++++++++----- .../config/security/token/UserPrincipal.java | 8 ++++-- 5 files changed, 47 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/finfellows/domain/auth/application/CustomTokenProviderService.java b/src/main/java/com/finfellows/domain/auth/application/CustomTokenProviderService.java index e624052..2dd1a91 100644 --- a/src/main/java/com/finfellows/domain/auth/application/CustomTokenProviderService.java +++ b/src/main/java/com/finfellows/domain/auth/application/CustomTokenProviderService.java @@ -84,6 +84,7 @@ public TokenMapping createToken(Authentication authentication) { .setSubject(Long.toString(userPrincipal.getId())) .setIssuedAt(new Date()) .setExpiration(accessTokenExpiresIn) + .claim("role", userPrincipal.getRole()) .signWith(key, SignatureAlgorithm.HS512) .compact(); diff --git a/src/main/java/com/finfellows/domain/auth/application/KakaoService.java b/src/main/java/com/finfellows/domain/auth/application/KakaoService.java index dc64a43..0a4902a 100644 --- a/src/main/java/com/finfellows/domain/auth/application/KakaoService.java +++ b/src/main/java/com/finfellows/domain/auth/application/KakaoService.java @@ -15,6 +15,7 @@ import com.finfellows.global.error.DefaultAuthenticationException; import com.finfellows.global.payload.ErrorCode; import com.finfellows.global.payload.Message; +import com.finfellows.global.payload.ResponseCustom; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -211,6 +212,7 @@ public AuthRes kakaoLogin(KakaoProfile kakaoProfile) { return AuthRes.builder() .accessToken(tokenMapping.getAccessToken()) .refreshToken(token.getRefreshToken()) + .role(Role.USER) .build(); } @@ -310,7 +312,11 @@ public ResponseEntity refresh(RefreshTokenReq refreshTokenReq) { Token updateToken = token.get().updateRefreshToken(tokenMapping.getRefreshToken()); tokenRepository.save(updateToken); - AuthRes authResponse = AuthRes.builder().accessToken(tokenMapping.getAccessToken()).refreshToken(updateToken.getRefreshToken()).build(); + AuthRes authResponse = AuthRes.builder() + .accessToken(tokenMapping.getAccessToken()) + .refreshToken(updateToken.getRefreshToken()) + .role(Role.ADMIN) + .build(); return ResponseEntity.ok(authResponse); } @@ -331,4 +337,10 @@ private boolean valid(String refreshToken) { return true; } + + public ResponseCustom whoAmI(UserPrincipal userPrincipal) { + Optional user = userRepository.findById(userPrincipal.getId()); + DefaultAssert.isOptionalPresent(user); + return ResponseCustom.OK(user); + } } diff --git a/src/main/java/com/finfellows/domain/auth/dto/AuthRes.java b/src/main/java/com/finfellows/domain/auth/dto/AuthRes.java index 30e1df7..a47d1b3 100644 --- a/src/main/java/com/finfellows/domain/auth/dto/AuthRes.java +++ b/src/main/java/com/finfellows/domain/auth/dto/AuthRes.java @@ -1,5 +1,6 @@ package com.finfellows.domain.auth.dto; +import com.finfellows.domain.user.domain.Role; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; import lombok.Data; @@ -16,10 +17,14 @@ public class AuthRes { @Schema( type = "string", example ="Bearer", description="권한(Authorization) 값 해더의 명칭을 지정합니다.") private String tokenType = "Bearer"; + @Schema( type = "Role", example = "USER", description = "Role을 출력합니다.") + private Role role; + @Builder - public AuthRes(String accessToken, String refreshToken) { + public AuthRes(String accessToken, String refreshToken, Role role) { this.accessToken = accessToken; this.refreshToken = refreshToken; + this.role = role; } } diff --git a/src/main/java/com/finfellows/domain/auth/presentation/AuthController.java b/src/main/java/com/finfellows/domain/auth/presentation/AuthController.java index c518d84..3e2f61a 100644 --- a/src/main/java/com/finfellows/domain/auth/presentation/AuthController.java +++ b/src/main/java/com/finfellows/domain/auth/presentation/AuthController.java @@ -5,6 +5,7 @@ import com.finfellows.domain.auth.dto.KakaoProfile; import com.finfellows.domain.auth.dto.RefreshTokenReq; import com.finfellows.domain.auth.dto.TokenMapping; +import com.finfellows.domain.user.domain.User; import com.finfellows.global.config.security.token.CurrentUser; import com.finfellows.global.config.security.token.UserPrincipal; import com.finfellows.global.payload.ErrorResponse; @@ -34,14 +35,27 @@ public class AuthController { private final KakaoService kakaoService; - @Operation(summary = "카카오 code 발급", description = "카카오 API 서버에 접근 권한을 인가하는 code를 발급받습니다.") + +// @Operation(summary = "카카오 code 발급", description = "카카오 API 서버에 접근 권한을 인가하는 code를 발급받습니다.") +// @ApiResponses(value = { +// @ApiResponse(responseCode = "200", description = "code 발급 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = AuthRes.class))}), +// @ApiResponse(responseCode = "400", description = "code 발급 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))}), +// }) +// @GetMapping(value = "/login") +// public void socialLoginRedirect() throws IOException { +// kakaoService.accessRequest(); +// } + + @Operation(summary = "유저 정보 확인", description = "현재 접속 중인 유저의 정보를 확인합니다.") @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "code 발급 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = AuthRes.class))}), - @ApiResponse(responseCode = "400", description = "code 발급 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))}), + @ApiResponse(responseCode = "200", description = "유저 확인 성공", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = User.class) ) } ), + @ApiResponse(responseCode = "400", description = "유저 확인 실패", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class) ) } ), }) - @GetMapping(value = "/login") - public void socialLoginRedirect() throws IOException { - kakaoService.accessRequest(); + @GetMapping + public ResponseCustom whoAmI( + @Parameter(description = "AccessToken을 입력해주세요.", required = true) @CurrentUser UserPrincipal userPrincipal + ) { + return kakaoService.whoAmI(userPrincipal); } @Operation(summary = "카카오 로그인", description = "카카오 로그인을 수행합니다.") @@ -62,7 +76,7 @@ public ResponseCustom kakaoCallback( } - @Operation(summary = "관리자 로그인", description = "관리자 권한으로 로그인을 수행합니다.") + @Operation(summary = "관리자 회원가입", description = "관리자 권한으로 로그인을 수행합니다.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "로그인 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = AuthRes.class))}), @ApiResponse(responseCode = "400", description = "로그인 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))}), diff --git a/src/main/java/com/finfellows/global/config/security/token/UserPrincipal.java b/src/main/java/com/finfellows/global/config/security/token/UserPrincipal.java index 7c132a1..2eaabc5 100644 --- a/src/main/java/com/finfellows/global/config/security/token/UserPrincipal.java +++ b/src/main/java/com/finfellows/global/config/security/token/UserPrincipal.java @@ -1,5 +1,6 @@ package com.finfellows.global.config.security.token; +import com.finfellows.domain.user.domain.Role; import com.finfellows.domain.user.domain.User; import lombok.Getter; import org.springframework.security.core.GrantedAuthority; @@ -17,13 +18,15 @@ public class UserPrincipal implements OAuth2User, UserDetails { private final Long id; private final String email; private final String name; + private final Role role; private Map attributes; - public UserPrincipal(User user, Long id, String email, String name) { + public UserPrincipal(User user, Long id, String email, String name, Role role) { this.user = user; this.id = id; this.email = email; this.name = name; + this.role = role; } public static UserPrincipal createUser(User user) { @@ -31,7 +34,8 @@ public static UserPrincipal createUser(User user) { user, user.getId(), user.getEmail(), - user.getName() + user.getName(), + user.getRole() ); } From a918f9853d7a0c31481ef6167ed9b4f5b96d6a9f Mon Sep 17 00:00:00 2001 From: Eunbeen Noh <101248968+EunbeenDev@users.noreply.github.com> Date: Sun, 7 Jan 2024 15:13:49 +0900 Subject: [PATCH 4/5] [FEAT]: chatbot reaponse (#51) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [FEAT] #3 ChatGPT 응답 단답 확인 과정 테스트 * [FIX] #3 SecurityConfig permitAll 추가 * [FEAT] #3 ChatgptRequest 추가 GPT Request DTO format * [FIX] #3 Chatgpt dependencies 추가 * [FEAT] #14 EduContent DTO 생성 * [FIX] #14 Post AccessLevel 수정 * [FEAT] #14 educontent 저장 api 구현 * [FEAT] #14 educontent 조회/상세조회/수정/삭제 api 구현 * [FEAT] #15 newscontent 저장/조회/상세조회/수정/삭제 api 구현 * [FEAT] #19 content 저장/조회/상세조회/수정/삭제 api 구현 * [FEAT] #19 swagger 설정 추가 * [FEAT] #19 readOnly를 위한 Transactional 어노테이션 추가 * [FEAT] #39 chatbot, comment 파일 추가 * fix: chat gpt 수정 * [FIX] #19 Transactional annotation readOnly default 수정 * Revert "[FIX] #19 Transactional annotation readOnly default 수정" This reverts commit 4a18b0ebce60ff41bdacac044fd6c365adf49ca4. * [FIX] #19 Transactional annotation readOnly default 수정 * [FEAT] #39 챗봇 질의응답 기능 개발 인사말 추가, 질의응답, 조회 기능 * [FEAT] educontent created_at 요청/응답 필드 추가 * [FIX] #39 챗봇 요청/응답값 UserId 부분 수정 * [FIX] #39 챗봇 요청/응답값 UserId 부분 수정 * [FIX] #39 swagger 코드 추가 --------- Co-authored-by: 박세진 --- .../chatgpt/application/ChatGptService.java | 51 ++++--------- .../presentation/ChatGptController.java | 30 ++++---- .../comment/application/CommentService.java | 71 +++++++++++++++++++ .../domain/comment/domain/Comment.java | 23 +++--- .../domain/repository/CommentRepository.java | 6 ++ .../comment/dto/request/CommentRequest.java | 22 ++++++ .../comment/dto/response/CommentResponse.java | 22 ++++++ .../presentation/CommentController.java | 54 +++++++++++++- .../dto/request/EduContentRequest.java | 4 ++ .../dto/response/EduContentResponse.java | 4 ++ .../config/security/SecurityConfig.java | 3 + 11 files changed, 230 insertions(+), 60 deletions(-) create mode 100644 src/main/java/com/finfellows/domain/comment/dto/request/CommentRequest.java create mode 100644 src/main/java/com/finfellows/domain/comment/dto/response/CommentResponse.java diff --git a/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java b/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java index 8704c09..0fa7e4f 100644 --- a/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java +++ b/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java @@ -14,46 +14,23 @@ public class ChatGptService { @Value("${chatgpt.api-key}") private String apiKey; -// private final ObjectMapper objectMapper = new ObjectMapper() -// .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) -// .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE ); -// public Flux ask(ChatgptQuestionRequest chatGptQuestionRequest) throws JsonProcessingException { -// WebClient client = WebClient.builder() -// .baseUrl(ChatgptConfig.CHAT_URL) -// .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) -// .defaultHeader(ChatgptConfig.AUTHORIZATION, ChatgptConfig.BEARER + apiKey) -// .build(); -// -// List messages = new ArrayList<>(); -// messages.add(ChatGptMessage.builder() -// .role(ChatgptConfig.ROLE) -// .content(chatGptQuestionRequest.getQuestion()) -// .build()); -// -// ChatgptRequest chatGptRequest = new ChatgptRequest( -// ChatgptConfig.CHAT_MODEL, -// ChatgptConfig.MAX_TOKEN, -// ChatgptConfig.TEMPERATURE, -// ChatgptConfig.STREAM_TRUE, -// messages -// ); -// -// String requestValue = objectMapper.writeValueAsString(chatGptRequest); -// -// Flux eventStream = client.post() -// .bodyValue(requestValue) -// .accept(MediaType.TEXT_EVENT_STREAM) -// .retrieve() -// .bodyToFlux(String.class); -// -// return eventStream; -// } // 단답 답변 public String getChatResponse(String prompt) { - System.out.print(apiKey); - // ChatGPT에 질문 전송 - return chatgptService.sendMessage(prompt); + try{ + String prompt_guide= + "너는 지금 청년들의 금융 지식을 향상시켜주기 위한 챗봇이야. 너의 이름은 '금토리'야. 너는 캐릭터의 역할이기 때문에 텍스트 형식으로 답변을 해야 해. 언어는 한국어로 말해야 하고, 말투는 친구한테 말하는 것처럼 반발로 해." + + "그리고 금융에 관련된 답변만 해야 하고, 만약 금융과 관련이 없는 질문이면 '미안해. 금융과 관련되지 않은 질문은 답변해줄 수 없어.'라고 말하면 돼. " + + "질문은 다음과 같아. 실제로 사용자와 대화하듯이 말해야 하고, 바로 질문에 대한 답을 해. 상식적으로 알 수도 있다는 말은 하지 마." + + "'네'라는 대답은 하지마. 인사말도 하지 마. 그리고 최대한 자세하게 답변해. 다시 한 번 말하지만, 반말로 말해. 그리고 문장은 끝까지 완전한 형태로 말 해"; + prompt=prompt_guide.concat(prompt); + String response=chatgptService.sendMessage(prompt); + return response; + } + catch (Exception e){ + e.printStackTrace(); + return "request error"; + } } } diff --git a/src/main/java/com/finfellows/domain/chatgpt/presentation/ChatGptController.java b/src/main/java/com/finfellows/domain/chatgpt/presentation/ChatGptController.java index b10657b..7df13d9 100644 --- a/src/main/java/com/finfellows/domain/chatgpt/presentation/ChatGptController.java +++ b/src/main/java/com/finfellows/domain/chatgpt/presentation/ChatGptController.java @@ -1,6 +1,11 @@ package com.finfellows.domain.chatgpt.presentation; import com.finfellows.domain.chatgpt.application.ChatGptService; +import com.finfellows.domain.comment.application.CommentService; +import com.finfellows.domain.comment.domain.QComment; +import com.finfellows.global.config.security.token.CurrentUser; +import com.finfellows.global.config.security.token.UserPrincipal; + import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; @@ -14,24 +19,21 @@ @Slf4j public class ChatGptController { private final ChatGptService chatgptService; - -// @PostMapping(value="/ask-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) -// public Flux ask(Locale locale, -// HttpServletRequest request, -// HttpServletResponse response, -// @RequestBody ChatgptQuestionRequest chatGptQuestionRequest){ -// try { -// return chatgptService.ask(chatGptQuestionRequest); -// }catch (JsonProcessingException je){ -// log.error(je.getMessage()); -// return Flux.empty(); -// } -// } + private final CommentService commentService; // 단답 테스트 // https://yjkim-dev.tistory.com/56 - @PostMapping("") + @PostMapping("/test") public String test(@RequestBody String question) { return chatgptService.getChatResponse(question); } + + // 답변 저장 테스트 + @PostMapping("") + public String getChatResponse(@CurrentUser UserPrincipal userPrincipal, @RequestBody String question){ + String answer= commentService.getChatResponse(question); + commentService.saveComment(userPrincipal.getId(), question, answer); + return answer; + } + } \ No newline at end of file diff --git a/src/main/java/com/finfellows/domain/comment/application/CommentService.java b/src/main/java/com/finfellows/domain/comment/application/CommentService.java index da5d479..6bf2e86 100644 --- a/src/main/java/com/finfellows/domain/comment/application/CommentService.java +++ b/src/main/java/com/finfellows/domain/comment/application/CommentService.java @@ -1,6 +1,9 @@ package com.finfellows.domain.comment.application; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; + import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.finfellows.domain.chatgpt.domain.ChatGptMessage; @@ -9,7 +12,11 @@ import com.finfellows.domain.chatgpt.dto.request.ChatgptQuestionRequest; import com.finfellows.domain.chatgpt.dto.request.ChatgptRequest; import com.finfellows.domain.chatgpt.dto.response.ChatgptResponse; +import com.finfellows.domain.comment.domain.Comment; import com.finfellows.domain.comment.domain.repository.CommentRepository; +import com.finfellows.domain.comment.dto.response.CommentResponse; +import com.finfellows.domain.user.domain.User; + import com.finfellows.domain.user.domain.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; @@ -20,6 +27,8 @@ import org.springframework.web.client.RestTemplate; import java.util.*; +import java.util.stream.Collectors; + @Service @RequiredArgsConstructor @@ -81,4 +90,66 @@ public ChatgptResponse askQuestion(ChatgptQuestionRequest questionRequest) { ) ); } + + + public String getChatResponse(String question){ + String responseFromGPT=chatGptService.getChatResponse(question); + return responseFromGPT; + } + + public void saveComment(Long userId, String question, String answer) { + Optional optionalUser = userRepository.findById(userId); + User user = optionalUser.orElseThrow(() -> new RuntimeException("User not found")); + + question = extractPromptFromJson(question); + answer = answer.replaceAll("\\n", ""); + answer = answer.replaceAll("금토리: ", ""); + answer = answer.replaceAll("네. ", ""); + + Comment comment = Comment.builder() + .question(question) + .answer(answer) + .user(user) + .build(); + commentRepository.save(comment); + } + + // JSON에서 "prompt" 부분 추출하는 메소드 + private String extractPromptFromJson(String json) { + try { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(json); + if (jsonNode.has("prompt")) { + return jsonNode.get("prompt").asText(); + } + } catch (JsonProcessingException e) { + System.out.print("텍스트 변환 실패"); + } + return json; + } + + public List getAllComments(Long userId) { + Optional optionalUser = userRepository.findById(userId); + User user = optionalUser.orElseThrow(() -> new RuntimeException("User not found")); + + List comments = commentRepository.findAllByUserId(userId); + + Comment greet = Comment.builder() + .greeting("안녕! 나는 금토리야. 도움이 필요하다면 편하게 말해줘.") + .user(user) + .build(); + commentRepository.save(greet); + + return comments.stream() + .map(comment -> CommentResponse.builder() + .commentId(comment.getCommentId()) + .created_at(comment.getCreatedAt()) + .greeting(comment.getGreeting()) + .question(comment.getQuestion()) + .answer(comment.getAnswer()) + .userId(comment.getUser().getId()) + .build() + ) + .collect(Collectors.toList()); + } } diff --git a/src/main/java/com/finfellows/domain/comment/domain/Comment.java b/src/main/java/com/finfellows/domain/comment/domain/Comment.java index 00c31c2..a32a7b8 100644 --- a/src/main/java/com/finfellows/domain/comment/domain/Comment.java +++ b/src/main/java/com/finfellows/domain/comment/domain/Comment.java @@ -11,23 +11,30 @@ @Getter public class Comment extends BaseEntity { - //질문 내용 저장 칼럼 필요함. @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="comment_id", updatable = false, nullable = false, unique = true) private Long commentId; - @Column(name="comment_content") - private String commentContent; + @Column(name = "greeting") + private String greeting; + + @Column(name = "question") + private String question; + + @Column(name="answer") + private String answer; @ManyToOne @JoinColumn(name="user_id") - private User userId; + private User user; @Builder - public Comment(Long commentId, String commentContent, User userId){ - this.commentId=commentId; - this.commentContent=commentContent; - this.userId=userId; + public Comment(String question, String greeting, String answer, User user){ + this.greeting=greeting; + this.question=question; + this.answer=answer; + this.user=user; + } } diff --git a/src/main/java/com/finfellows/domain/comment/domain/repository/CommentRepository.java b/src/main/java/com/finfellows/domain/comment/domain/repository/CommentRepository.java index ec86eae..00833ae 100644 --- a/src/main/java/com/finfellows/domain/comment/domain/repository/CommentRepository.java +++ b/src/main/java/com/finfellows/domain/comment/domain/repository/CommentRepository.java @@ -2,6 +2,12 @@ import com.finfellows.domain.comment.domain.Comment; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import java.util.List; + +@Repository public interface CommentRepository extends JpaRepository { + List findAllByUserId(Long userId); + } diff --git a/src/main/java/com/finfellows/domain/comment/dto/request/CommentRequest.java b/src/main/java/com/finfellows/domain/comment/dto/request/CommentRequest.java new file mode 100644 index 0000000..801ea38 --- /dev/null +++ b/src/main/java/com/finfellows/domain/comment/dto/request/CommentRequest.java @@ -0,0 +1,22 @@ +package com.finfellows.domain.comment.dto.request; + +import com.finfellows.domain.user.domain.User; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class CommentRequest { + private Long commentId; + private LocalDateTime created_at; + private String greeting; + private String question; + private String answer; + private Long userId; +} diff --git a/src/main/java/com/finfellows/domain/comment/dto/response/CommentResponse.java b/src/main/java/com/finfellows/domain/comment/dto/response/CommentResponse.java new file mode 100644 index 0000000..e110023 --- /dev/null +++ b/src/main/java/com/finfellows/domain/comment/dto/response/CommentResponse.java @@ -0,0 +1,22 @@ +package com.finfellows.domain.comment.dto.response; + +import com.finfellows.domain.user.domain.User; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Getter +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class CommentResponse { + private Long commentId; + private LocalDateTime created_at; + private String greeting; + private String question; + private String answer; + private Long userId; +} diff --git a/src/main/java/com/finfellows/domain/comment/presentation/CommentController.java b/src/main/java/com/finfellows/domain/comment/presentation/CommentController.java index 4bcc573..daacd2f 100644 --- a/src/main/java/com/finfellows/domain/comment/presentation/CommentController.java +++ b/src/main/java/com/finfellows/domain/comment/presentation/CommentController.java @@ -1,9 +1,61 @@ package com.finfellows.domain.comment.presentation; +import com.finfellows.domain.chatgpt.application.ChatGptService; +import com.finfellows.domain.comment.application.CommentService; +import com.finfellows.domain.comment.dto.response.CommentResponse; +import com.finfellows.domain.user.application.UserService; +import com.finfellows.global.config.security.token.CurrentUser; +import com.finfellows.global.config.security.token.UserPrincipal; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; @RestController @RequiredArgsConstructor +@RequestMapping("/api/chatbot") +@Tag(name="Chatbot",description = "Chatbot API") public class CommentController { + private CommentService commentService; + private ChatGptService chatGptService; + private UserService userService; + + + @Autowired + public CommentController(CommentService commentService, ChatGptService chatGptService, UserService userService) { + this.commentService = commentService; + this.chatGptService = chatGptService; + this.userService = userService; + } + + @Operation(summary = "챗봇 질의응답 저장", description = "챗봇 질문과 답변을 저장합니다.") + @ApiResponse(responseCode = "200", description = "챗봇 질문에 대한 답변 응답 성공", content = { + @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = CommentResponse.class))) + }) + @PostMapping("") + public String getChatResponse(@CurrentUser UserPrincipal userPrincipal, @RequestBody String question){ + String answer= commentService.getChatResponse(question); + commentService.saveComment(userPrincipal.getId(), question, answer); + return answer; + } + + @Operation(summary = "챗봇 대화 내용 조회", description = "챗봇 대화 전체 목록을 조회합니다.") + @ApiResponse(responseCode = "200", description = "챗봇 대화 목록 조회 성공", content = { + @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = CommentResponse.class))) + }) + @GetMapping("") + public ResponseEntity> getAllComments(@CurrentUser UserPrincipal userPrincipal){ + List responseList=commentService.getAllComments(userPrincipal.getId()); + return new ResponseEntity<>(responseList, HttpStatus.OK); + } + } diff --git a/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java b/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java index 130e9e0..e09677a 100644 --- a/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java +++ b/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java @@ -5,12 +5,16 @@ import lombok.Getter; import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + @Getter @Builder @AllArgsConstructor @NoArgsConstructor public class EduContentRequest { private Long id; + private LocalDateTime created_at; private String title; private String content; } diff --git a/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java b/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java index d711383..1422270 100644 --- a/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java +++ b/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java @@ -5,12 +5,16 @@ import lombok.Getter; import lombok.NoArgsConstructor; +import java.time.LocalDateTime; + + @Getter @Builder @AllArgsConstructor @NoArgsConstructor public class EduContentResponse { private Long id; + private LocalDateTime created_at; private String title; private String content; } diff --git a/src/main/java/com/finfellows/global/config/security/SecurityConfig.java b/src/main/java/com/finfellows/global/config/security/SecurityConfig.java index a4cce10..2752ab4 100644 --- a/src/main/java/com/finfellows/global/config/security/SecurityConfig.java +++ b/src/main/java/com/finfellows/global/config/security/SecurityConfig.java @@ -68,6 +68,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .requestMatchers("/api/v1/chat-gpt") .permitAll() + .requestMatchers("/api/chatbot") + .permitAll() + .anyRequest() .authenticated()); From 8f59b4dea3ce19304aeaba678d099acda81ada11 Mon Sep 17 00:00:00 2001 From: Eunbeen Noh <101248968+EunbeenDev@users.noreply.github.com> Date: Sun, 7 Jan 2024 15:15:28 +0900 Subject: [PATCH 5/5] [FIX]: edu/news/content to enum (#53) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [FEAT] #3 ChatGPT 응답 단답 확인 과정 테스트 * [FIX] #3 SecurityConfig permitAll 추가 * [FEAT] #3 ChatgptRequest 추가 GPT Request DTO format * [FIX] #3 Chatgpt dependencies 추가 * [FEAT] #14 EduContent DTO 생성 * [FIX] #14 Post AccessLevel 수정 * [FEAT] #14 educontent 저장 api 구현 * [FEAT] #14 educontent 조회/상세조회/수정/삭제 api 구현 * [FEAT] #15 newscontent 저장/조회/상세조회/수정/삭제 api 구현 * [FEAT] #19 content 저장/조회/상세조회/수정/삭제 api 구현 * [FEAT] #19 swagger 설정 추가 * [FEAT] #19 readOnly를 위한 Transactional 어노테이션 추가 * [FEAT] #39 chatbot, comment 파일 추가 * fix: chat gpt 수정 * [FIX] #19 Transactional annotation readOnly default 수정 * Revert "[FIX] #19 Transactional annotation readOnly default 수정" This reverts commit 4a18b0ebce60ff41bdacac044fd6c365adf49ca4. * [FIX] #19 Transactional annotation readOnly default 수정 * [FEAT] #39 챗봇 질의응답 기능 개발 인사말 추가, 질의응답, 조회 기능 * [FEAT] educontent created_at 요청/응답 필드 추가 * [FIX] #39 챗봇 요청/응답값 UserId 부분 수정 * [FIX] #39 챗봇 요청/응답값 UserId 부분 수정 * [FIX] #39 swagger 코드 추가 * [FIX] #52 Post Entity enum type 추가 --------- Co-authored-by: 박세진 Co-authored-by: Sejin Park <95167215+sejineer@users.noreply.github.com> --- .../domain/chatgpt/application/ChatGptService.java | 1 + .../domain/comment/application/CommentService.java | 3 +-- .../domain/educontent/domain/EduContent.java | 11 +++++++++++ .../educontent/dto/request/EduContentRequest.java | 1 - .../educontent/dto/response/EduContentResponse.java | 1 - .../domain/newscontent/domain/NewsContent.java | 9 +++++++++ .../com/finfellows/domain/post/domain/Content.java | 6 ++++++ .../finfellows/domain/post/domain/ContentType.java | 7 +++++++ .../java/com/finfellows/domain/post/domain/Post.java | 7 ++++++- 9 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/finfellows/domain/post/domain/ContentType.java diff --git a/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java b/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java index 0fa7e4f..da6ba38 100644 --- a/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java +++ b/src/main/java/com/finfellows/domain/chatgpt/application/ChatGptService.java @@ -32,5 +32,6 @@ public String getChatResponse(String prompt) { return "request error"; } } + } diff --git a/src/main/java/com/finfellows/domain/comment/application/CommentService.java b/src/main/java/com/finfellows/domain/comment/application/CommentService.java index 6bf2e86..2b741d8 100644 --- a/src/main/java/com/finfellows/domain/comment/application/CommentService.java +++ b/src/main/java/com/finfellows/domain/comment/application/CommentService.java @@ -40,6 +40,7 @@ public class CommentService { @Autowired private RestTemplate restTemplate; + @Value("${chatgpt.api-key}") private String apiKey; private final ObjectMapper objectMapper = new ObjectMapper() @@ -56,7 +57,6 @@ public HttpEntity buildHttpEntity(ChatgptRequest chatGptRequest) // gpt 단답 public ChatgptResponse getResponse(HttpEntity chatGptRequestHttpEntity) { - SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(60000); //답변이 길어질 경우 TimeOut Error가 발생하니 1분정도 설정해줍니다. @@ -91,7 +91,6 @@ public ChatgptResponse askQuestion(ChatgptQuestionRequest questionRequest) { ); } - public String getChatResponse(String question){ String responseFromGPT=chatGptService.getChatResponse(question); return responseFromGPT; diff --git a/src/main/java/com/finfellows/domain/educontent/domain/EduContent.java b/src/main/java/com/finfellows/domain/educontent/domain/EduContent.java index 420223b..37dc0f1 100644 --- a/src/main/java/com/finfellows/domain/educontent/domain/EduContent.java +++ b/src/main/java/com/finfellows/domain/educontent/domain/EduContent.java @@ -1,6 +1,7 @@ package com.finfellows.domain.educontent.domain; import com.finfellows.domain.common.BaseEntity; +import com.finfellows.domain.post.domain.ContentType; import com.finfellows.domain.post.domain.Post; import jakarta.persistence.*; import lombok.AccessLevel; @@ -25,6 +26,10 @@ public class EduContent extends BaseEntity { @JoinColumn(name="post_id") private Post post; + @Enumerated(EnumType.STRING) + @Column(name="contentType") + private ContentType contentType; + @Column(name="title") private String title; @@ -37,6 +42,12 @@ public EduContent(Post post, String title, String content){ this.post=post; this.title=title; this.content=content; + this.contentType = ContentType.EDU_CONTENT; + } + + public void updateContent(String title, String content) { + this.title = title; + this.content = content; } public void updateContent(String title, String content) { diff --git a/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java b/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java index e09677a..e8c2b3c 100644 --- a/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java +++ b/src/main/java/com/finfellows/domain/educontent/dto/request/EduContentRequest.java @@ -5,7 +5,6 @@ import lombok.Getter; import lombok.NoArgsConstructor; - import java.time.LocalDateTime; @Getter diff --git a/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java b/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java index 1422270..a2231c6 100644 --- a/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java +++ b/src/main/java/com/finfellows/domain/educontent/dto/response/EduContentResponse.java @@ -7,7 +7,6 @@ import java.time.LocalDateTime; - @Getter @Builder @AllArgsConstructor diff --git a/src/main/java/com/finfellows/domain/newscontent/domain/NewsContent.java b/src/main/java/com/finfellows/domain/newscontent/domain/NewsContent.java index 5d6006c..3a83299 100644 --- a/src/main/java/com/finfellows/domain/newscontent/domain/NewsContent.java +++ b/src/main/java/com/finfellows/domain/newscontent/domain/NewsContent.java @@ -1,6 +1,9 @@ package com.finfellows.domain.newscontent.domain; import com.finfellows.domain.common.BaseEntity; + +import com.finfellows.domain.post.domain.ContentType; + import com.finfellows.domain.post.domain.Post; import jakarta.persistence.*; import lombok.Builder; @@ -29,11 +32,17 @@ public class NewsContent extends BaseEntity { @Column(name="content") private String content; + @Enumerated(EnumType.STRING) + @Column(name="contentType") + private ContentType contentType; + @Builder public NewsContent(Post post, String title, String content){ this.post=post; this.title=title; this.content=content; + this.contentType = ContentType.NEWS_CONTENT; + } public void updateContent(String title, String content) { diff --git a/src/main/java/com/finfellows/domain/post/domain/Content.java b/src/main/java/com/finfellows/domain/post/domain/Content.java index c5f3db5..a865285 100644 --- a/src/main/java/com/finfellows/domain/post/domain/Content.java +++ b/src/main/java/com/finfellows/domain/post/domain/Content.java @@ -32,12 +32,18 @@ public class Content { @Column(name="content") private String content; + @Enumerated(EnumType.STRING) + @Column(name="contentType") + private ContentType contentType; + @Builder public Content(Post post_id, String title, String content){ this.post_id=post_id; this.title=title; this.content=content; + this.contentType = ContentType.CONTENT; + } public void updateContent(String title, String content) { diff --git a/src/main/java/com/finfellows/domain/post/domain/ContentType.java b/src/main/java/com/finfellows/domain/post/domain/ContentType.java new file mode 100644 index 0000000..a0f2316 --- /dev/null +++ b/src/main/java/com/finfellows/domain/post/domain/ContentType.java @@ -0,0 +1,7 @@ +package com.finfellows.domain.post.domain; + +public enum ContentType { + EDU_CONTENT, + NEWS_CONTENT, + CONTENT +} diff --git a/src/main/java/com/finfellows/domain/post/domain/Post.java b/src/main/java/com/finfellows/domain/post/domain/Post.java index 5231c18..f661ccf 100644 --- a/src/main/java/com/finfellows/domain/post/domain/Post.java +++ b/src/main/java/com/finfellows/domain/post/domain/Post.java @@ -26,9 +26,14 @@ public class Post extends BaseEntity { @JoinColumn(name="writer_id") private User writer; + @Enumerated(EnumType.STRING) + @Column(name="contentType") + private ContentType contentType; + @Builder - public Post(User writer){ + public Post(User writer, ContentType contentType){ this.writer=writer; + this.contentType=contentType; } }