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

소셜 기능 (찜하기, 조회수) 구현 #20

Closed
wants to merge 3 commits into from
Closed
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
@@ -0,0 +1,30 @@
package com.trade_ham.domain.auth.controller;

import com.trade_ham.domain.auth.dto.CustomOAuth2User;
import com.trade_ham.domain.auth.dto.UserUpdateDTO;
import com.trade_ham.domain.auth.service.UserService;
import com.trade_ham.global.common.response.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/v1")
public class UserController {

private final UserService userService;

@PostMapping("/user")
public ApiResponse<UserUpdateDTO> updateUser(@RequestBody UserUpdateDTO userUpdateDTO, @AuthenticationPrincipal CustomOAuth2User oAuth2User) {
Long sellerId = oAuth2User.getId();
// ID가 제대로 나오는지 확인
log.info("OAuth2 User ID: {}", oAuth2User.getId());

UserUpdateDTO userResponse = userService.updateUser(sellerId, userUpdateDTO);

return ApiResponse.success(userResponse);
}
}
11 changes: 11 additions & 0 deletions src/main/java/com/trade_ham/domain/auth/dto/UserUpdateDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.trade_ham.domain.auth.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserUpdateDTO {
private String account; // 계좌번호
private String realname;
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public class UserEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long user_id;
@Column(name = "user_id")
private Long id;

private String email; // 이메일
private String username; // OAuth2 유일 식별자
Expand All @@ -36,10 +37,11 @@ public class UserEntity {
private List<ProductEntity> purchasedProductEntities = new ArrayList<>();

// 추후 따로 받는다.
private String acount; // 계좌번호
private String account; // 계좌번호
private String realname; // 실제이름

public void updateNickname(String nickname) {
public void updateAccountAndNickname(String account, String nickname) {
this.account = account;
this.nickname = nickname;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic

UserDTO userDTO = new UserDTO();

userDTO.setId(userRepository.findByProviderAndEmail(oAuth2Response.getProvider(), oAuth2Response.getEmail()).getUser_id());
userDTO.setId(userRepository.findByProviderAndEmail(oAuth2Response.getProvider(), oAuth2Response.getEmail()).getId());
userDTO.setEmail(oAuth2Response.getEmail());
userDTO.setNickname(oAuth2Response.getNickName());
userDTO.setRole(Role.USER);
Expand All @@ -62,7 +62,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
}
else{ // 이미 존재한다면
UserDTO userDTO = new UserDTO();
userDTO.setId(existData.getUser_id());
userDTO.setId(existData.getId());
userDTO.setNickname(existData.getNickname());
userDTO.setEmail(existData.getEmail());
userDTO.setRole(existData.getRole());
Expand Down
30 changes: 30 additions & 0 deletions src/main/java/com/trade_ham/domain/auth/service/UserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.trade_ham.domain.auth.service;

import com.trade_ham.domain.auth.dto.UserUpdateDTO;
import com.trade_ham.domain.auth.entity.UserEntity;
import com.trade_ham.domain.auth.repository.UserRepository;
import com.trade_ham.global.common.exception.ErrorCode;
import com.trade_ham.global.common.exception.ResourceNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;

public UserUpdateDTO updateUser(Long sellerId, UserUpdateDTO userUpdateDTO) {
UserEntity userEntity = userRepository.findById(sellerId)
.orElseThrow(() -> new ResourceNotFoundException(ErrorCode.USER_NOT_FOUND));

userEntity.setAccount(userUpdateDTO.getAccount());
userEntity.setNickname(userUpdateDTO.getRealname());

userRepository.save(userEntity);

return userUpdateDTO;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.trade_ham.domain.locker.controller;

import com.trade_ham.domain.auth.dto.CustomOAuth2User;
import com.trade_ham.domain.locker.entity.NotificationEntity;
import com.trade_ham.domain.locker.service.NotificationService;
import com.trade_ham.global.common.response.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/notification")
public class NotificationController {

private final NotificationService notificationService;

@GetMapping()
public ApiResponse<List<NotificationEntity>> getAllNotifications(@AuthenticationPrincipal CustomOAuth2User oAuth2User) {
Long userId = oAuth2User.getId();

List<NotificationEntity> notifications = notificationService.allNotification(userId);
return ApiResponse.success(notifications);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.trade_ham.domain.locker.dto;

import com.trade_ham.domain.auth.entity.UserEntity;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class NotificationBuyerDTO {
private String message;
private boolean isRead;
private UserEntity userId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.trade_ham.domain.locker.dto;

import com.trade_ham.domain.auth.entity.UserEntity;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class NotificationLockerDTO {
private String message;
private Long lockerId;
private String lockerPassword;
private boolean isRead;
private UserEntity userId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.trade_ham.domain.locker.entity;

import com.trade_ham.domain.auth.entity.UserEntity;
import com.trade_ham.domain.locker.dto.NotificationBuyerDTO;
import com.trade_ham.domain.locker.dto.NotificationLockerDTO;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
public class NotificationEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "notification_id")
private Long id;

//seller
@Column(name = "locker_id")
private Long lockerId;

@Column(name = "locker_password")
private String lockerPassword;

// common
private String message;

@Setter
private boolean isRead;

@ManyToOne
@JoinColumn(name = "user_id")
private UserEntity user;

// 판매자 전용 알림
public NotificationEntity(NotificationLockerDTO notificationLockerDTO) {
this.message = notificationLockerDTO.getMessage();
this.lockerId = notificationLockerDTO.getLockerId();
this.lockerPassword = notificationLockerDTO.getLockerPassword();
this.isRead = notificationLockerDTO.isRead();
this.user = notificationLockerDTO.getUserId();
}

// 구매자 전용 알림
public NotificationEntity(NotificationBuyerDTO NotificationBuyerDTO) {
this.message = NotificationBuyerDTO.getMessage();
this.isRead = NotificationBuyerDTO.isRead();
this.user = NotificationBuyerDTO.getUserId();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.trade_ham.domain.locker.repository;

import com.trade_ham.domain.auth.entity.UserEntity;
import com.trade_ham.domain.locker.entity.NotificationEntity;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;

public interface NotificationRepository extends JpaRepository<NotificationEntity, Long> {
List<NotificationEntity> findByUser_IdAndIsReadFalse(Long Id);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.trade_ham.domain.locker.service;

import com.trade_ham.domain.locker.entity.NotificationEntity;
import com.trade_ham.domain.locker.repository.NotificationRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class NotificationService {

private final NotificationRepository notificationRepository;

@Transactional
public List<NotificationEntity> allNotification(Long userId) {
List<NotificationEntity> notifications = notificationRepository.findByUser_IdAndIsReadFalse(userId);

for(NotificationEntity notificationEntity : notifications) {
notificationEntity.setRead(true);
}

return notificationRepository.saveAll(notifications);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.trade_ham.domain.product.controller;

import com.trade_ham.domain.auth.dto.CustomOAuth2User;
import com.trade_ham.domain.product.entity.LikeEntity;
import com.trade_ham.domain.product.service.LikeService;
import com.trade_ham.global.common.response.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Controller
@RequiredArgsConstructor
@RequestMapping("/api/v1")
public class LikeController {

private final LikeService likeService;

// 상품 좋아요 클릭
@PostMapping("/likes/{productId}")
public ApiResponse<String> toggleLike(@PathVariable Long productId, @AuthenticationPrincipal CustomOAuth2User oAuth2User) {
boolean isLiked = likeService.toggleLike(productId, oAuth2User.getId());

if (isLiked) {
return ApiResponse.success("좋아요 추가");
} else {
return ApiResponse.success("좋아요 취소");
}
}


// 상품별 좋아요 cnt 조회
@GetMapping("/products/{productId}/likes")
public ApiResponse<Long> getLikeCount(@PathVariable Long productId) {
Long likeCount = likeService.getLikeCount(productId);

return ApiResponse.success(likeCount);
}

// 특정 유저가 좋아요한 상품 조회
@GetMapping("/products/likes/{userId}")
public ApiResponse<List<LikeEntity>> getLikedProductsByUser(@PathVariable Long userId) {
List<LikeEntity> likeEntities = likeService.getLikedProductsByUser(userId);
return ApiResponse.success(likeEntities);
}
Comment on lines +44 to +48
Copy link
Collaborator

Choose a reason for hiding this comment

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

본인이 아닌 다른 사람의 좋아요를 조회할 경우가 있을까요..?
저는 자신의 좋아요만 조회해도 될 것 같아서 myPage 안의 기능과 통합했습니다!

}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package com.trade_ham.domain.product.controller;

import com.trade_ham.domain.product.entity.ProductEntity;
import com.trade_ham.domain.product.entity.ProductStatus;
import com.trade_ham.domain.auth.dto.CustomOAuth2User;
import com.trade_ham.domain.product.service.PurchaseProductService;
import com.trade_ham.global.common.exception.AccessDeniedException;
import com.trade_ham.global.common.exception.ErrorCode;
import com.trade_ham.global.common.response.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;


Expand All @@ -17,15 +15,10 @@ public class PurchaseProductController {
private final PurchaseProductService productService;

@GetMapping("/product/purchase-page/{productId}")
public ApiResponse<String> accessPurchasePage(@PathVariable Long productId) {
ProductEntity productEntity = productService.findProductById(productId);
public ApiResponse<String> accessPurchasePage(@PathVariable Long productId, @AuthenticationPrincipal CustomOAuth2User oAuth2User) {
Long buyerId = oAuth2User.getId();

// 상태가 SELL이 아니라면 예외 발생
if (!productEntity.getStatus().equals(ProductStatus.SELL)) {
throw new AccessDeniedException(ErrorCode.ACCESS_DENIED);
}

productService.purchaseProduct(productId);
productService.purchaseProduct(productId, buyerId);

// 상태가 SELL이면 구매 페이지에 접근 가능
return ApiResponse.success("구매 페이지에 접근 가능합니다.");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.trade_ham.domain.product.controller;

import com.trade_ham.domain.product.entity.ProductEntity;
import com.trade_ham.domain.product.service.SearchProductService;
import com.trade_ham.global.common.response.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1")
public class SearchProductController {

private final SearchProductService searchProductService;

@GetMapping("/search")
public ApiResponse<List<ProductEntity>> searchSellProduct(@RequestParam String keyword) {
List<ProductEntity> productEntities = searchProductService.searchSellProduct(keyword);

return ApiResponse.success(productEntities);
}

// 상품 클릭
@GetMapping("/products/{productId}")
public ApiResponse<ProductEntity> getProductDetail(@PathVariable Long productId, HttpServletRequest request, HttpServletResponse response) {
ProductEntity productEntity = searchProductService.getProductDetail(productId, request, response);

return ApiResponse.success(productEntity);
}
}
Loading