Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…ucks_backend into feature/user
  • Loading branch information
hejin8307 committed May 8, 2024
2 parents edff54e + 3647b38 commit 706c005
Show file tree
Hide file tree
Showing 15 changed files with 136 additions and 26 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package com.hanaro.starbucks.controller;

import com.hanaro.starbucks.config.JwtUtil;
import com.hanaro.starbucks.dto.member.LoginReqDto;
import com.hanaro.starbucks.dto.member.MemberResDto;
import com.hanaro.starbucks.dto.member.SignupReqDto;
import com.hanaro.starbucks.dto.member.MemberUpdateReqDto;
import com.hanaro.starbucks.dto.member.*;
import com.hanaro.starbucks.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -71,4 +68,8 @@ public void deleteUser(@PathVariable int userIdx){
memberService.deleteUser(userIdx);
}

@GetMapping("/{userIdx}/points")
public PointResDto getUserPoint(@PathVariable int userIdx){
return memberService.getUserPoint(userIdx);
}
}
14 changes: 14 additions & 0 deletions src/main/java/com/hanaro/starbucks/controller/MenuController.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.hanaro.starbucks.controller;

import com.hanaro.starbucks.dto.category.CategoryResDto;
import com.hanaro.starbucks.dto.menu.MenuReqDto;
import com.hanaro.starbucks.dto.menu.MenuResDto;
import com.hanaro.starbucks.service.CategoryService;
import com.hanaro.starbucks.service.MenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
Expand All @@ -13,11 +16,13 @@
import static com.hanaro.starbucks.util.APIConstant.API_VERSION;

@RestController
@Slf4j
@RequestMapping(API_VERSION + "/products")
@RequiredArgsConstructor
@CrossOrigin("http://localhost:5173")
public class MenuController {
private final MenuService menuService;
private final CategoryService categoryService;

@GetMapping("")
public List<MenuResDto> getMenuList() {
Expand All @@ -41,6 +46,15 @@ public void deleteMenuByMenuIdx(@PathVariable int menuIdx) throws Exception{

@PutMapping(value = "/admin/{menuIdx}", consumes = {MediaType.APPLICATION_JSON_VALUE, "multipart/form-data"})
public void updateMenu(@PathVariable int menuIdx, @RequestPart(value = "dto") MenuReqDto menuReqDto, @RequestPart(value = "menuImg", required = false) MultipartFile img) throws Exception{
log.info("~~~~~~menuReqDto = {}", menuReqDto.getCategoryIdx());
menuService.updateMenu(menuIdx, menuReqDto, img);
}

@GetMapping("/category")
public List<CategoryResDto> getCategoryList() {
return categoryService.getCategoryList();
}

@GetMapping("/recommendations")
public List<MenuResDto> getRecommendationList() { return menuService.getRecommendationList(); }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.hanaro.starbucks.dto.category;

import com.hanaro.starbucks.entity.Category;
import lombok.Getter;
import lombok.NoArgsConstructor;


@Getter
@NoArgsConstructor
public class CategoryResDto {
private int categoryIdx;

private String categoryName;

public CategoryResDto(Category category) {
this.categoryIdx = category.getCategoryIdx();
this.categoryName = category.getCategoryName();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public class MemberResDto {

@Builder
public MemberResDto(Member user){
this.userIdx = user.getUserIdx();
this.userId = user.getUserId();
this.userPw = user.getUserPw();
this.userNickname = user.getUserNickname();
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/hanaro/starbucks/dto/member/PointResDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.hanaro.starbucks.dto.member;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class PointResDto {
private int point;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
@Builder
@Getter
public class OrderResDto {
private int userIdx;
private Integer userIdx;
private String userNickname;
private int orderIdx;
private String orderId;
private Integer totalPrice;
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/hanaro/starbucks/entity/Menu.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ public class Menu {
private Category category;


public void update(MenuReqDto dto, String img) {
public void update(MenuReqDto dto, Category category, String img) {
this.menuName = dto.getMenuName();
this.menuPrice = dto.getMenuPrice();
this.menuImage = img;
this.category = category;
this.menuDate = LocalDate.now();
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/hanaro/starbucks/entity/Orders.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class Orders {
private LocalDateTime orderDate;

@ManyToOne
@JoinColumn(name = "user_idx")
@JoinColumn(name = "user_idx", nullable = true)
private Member user;

@OneToMany(mappedBy = "orders", cascade = CascadeType.ALL)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.hanaro.starbucks.repository;

import com.hanaro.starbucks.dto.member.PointResDto;
import com.hanaro.starbucks.entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
Expand All @@ -11,4 +13,7 @@
public interface MemberRepository extends JpaRepository<Member, Integer> {
Optional<Member> findByUserId(String userId);
boolean existsByUserId(String userId);

@Query("Select new com.hanaro.starbucks.dto.member.PointResDto(m.userPoint) from Member m where m.userIdx = :userIdx")
PointResDto findPointByUserIdx(int userIdx);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface OrderRepository extends JpaRepository<Orders, Integer> {
List<Orders> findAllByOrderByOrderIdxDesc();
}
21 changes: 21 additions & 0 deletions src/main/java/com/hanaro/starbucks/service/CategoryService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.hanaro.starbucks.service;

import com.hanaro.starbucks.dto.category.CategoryResDto;
import com.hanaro.starbucks.entity.Category;
import com.hanaro.starbucks.repository.CategoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
public class CategoryService {
private final CategoryRepository categoryRepository;

public List<CategoryResDto> getCategoryList() {
List<Category> categories = categoryRepository.findAll();
return categories.stream().map(CategoryResDto::new).collect(Collectors.toList());
}
}
8 changes: 8 additions & 0 deletions src/main/java/com/hanaro/starbucks/service/MemberService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.hanaro.starbucks.service;

import com.hanaro.starbucks.dto.member.MemberResDto;
import com.hanaro.starbucks.dto.member.PointResDto;
import com.hanaro.starbucks.dto.member.SignupReqDto;
import com.hanaro.starbucks.dto.member.MemberUpdateReqDto;
import com.hanaro.starbucks.entity.Member;
Expand Down Expand Up @@ -81,4 +82,11 @@ public void updateUser(int userIdx, MemberUpdateReqDto user){
public void deleteUser(int userIdx){
memberRepository.deleteById(userIdx);
}
public PointResDto getUserPoint(int userIdx){
PointResDto dto = memberRepository.findPointByUserIdx(userIdx);
if(dto==null){
throw new IllegalArgumentException("존재하지 않는 회원입니다.");
}
return dto;
}
}
22 changes: 19 additions & 3 deletions src/main/java/com/hanaro/starbucks/service/MenuService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;

@Service
Expand Down Expand Up @@ -50,6 +49,7 @@ public void deleteMenuByMenuIdx(int menuIdx) throws Exception {
if (optionalMenu.isEmpty()) {
throw new Exception("존재하지 않는 메뉴입니다.");
}
s3Uploader.deleteFile(optionalMenu.get().getMenuImage());
menuRepository.deleteById(menuIdx);
}

Expand All @@ -69,7 +69,23 @@ public void updateMenu(int menuIdx, MenuReqDto menuReqDto, MultipartFile img) th
if(img==null || img.isEmpty()) url=menu.getMenuImage();
else url = s3Uploader.updateFile(img, menu.getMenuImage(), optionalCategory.get().getCategoryName());

menu.update(menuReqDto, url);
menu.update(menuReqDto, optionalCategory.get(), url);
menuRepository.save(menu);
}

public List<MenuResDto> getRecommendationList(){
List<Menu> menus = menuRepository.findAll();

Set<Integer> idxSet = new HashSet<>(9);
List<Menu> menuList = new ArrayList<>(9);

Random random = new Random();

while (idxSet.size() < 9) {
int idx = random.nextInt(menus.size());
idxSet.add(idx);
menuList.add(menus.get(idx));
}
return menuList.stream().map(MenuResDto::new).collect(Collectors.toList());
}
}
15 changes: 10 additions & 5 deletions src/main/java/com/hanaro/starbucks/service/OrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@ public class OrderService {
private final OrderDetailRepository orderDetailRepository;

public List<OrderResDto> getOrders() {
List<Orders> orders = orderRepository.findAll();
List<OrderResDto> orderResDtos = orders.stream()
List<Orders> orders = orderRepository.findAllByOrderByOrderIdxDesc();
return orders.stream()
.map(order -> {
List<OrderDetail> orderDetails = order.getOrderDetails();
int totalPrice = calculateTotalPrice(orderDetails);
Integer userIdx = order.getUser() != null ? order.getUser().getUserIdx() : null;
String userNickname = order.getUser()!=null? order.getUser().getUserNickname() : null ;
return OrderResDto.builder()
.userIdx(order.getUser().getUserIdx())
.userIdx(userIdx)
.userNickname(userNickname)
.orderIdx(order.getOrderIdx())
.orderId(order.getOrderId())
.totalPrice(totalPrice)
Expand All @@ -36,13 +39,15 @@ public List<OrderResDto> getOrders() {
.build();
})
.collect(Collectors.toList());
return orderResDtos;
}

public OrderResDto getOrder(int orderIdx) {
Orders order = findOrderById(orderIdx);
Integer userIdx = order.getUser() != null ? order.getUser().getUserIdx() : null;
String userNickname = order.getUser()!=null? order.getUser().getUserNickname() : null ;
return OrderResDto.builder()
.userIdx(order.getUser().getUserIdx())
.userIdx(userIdx)
.userNickname(userNickname)
.orderIdx(order.getOrderIdx())
.orderId(order.getOrderId())
.totalPrice(calculateTotalPrice(order.getOrderDetails()))
Expand Down
27 changes: 16 additions & 11 deletions src/main/java/com/hanaro/starbucks/service/S3Uploader.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.hanaro.starbucks.service;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -12,7 +12,7 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.UUID;

Expand All @@ -26,13 +26,12 @@ public class S3Uploader {

// MultipartFile을 전달받아 File로 전환한 후 S3에 업로드
public String upload(MultipartFile multipartFile, String dirName) throws IOException {

File uploadFile = convert(multipartFile); // 파일 변환할 수 없으면 에러
String fileName = dirName + "/" + uploadFile.getName();
String safeDirName = dirName.replace("/", "_");
String fileName = safeDirName + "/" + uploadFile.getName();

String uploadImageUrl = putS3(uploadFile, fileName);
removeNewFile(uploadFile); // 로컬에 생성된 File 삭제 (MultipartFile -> File 전환 하며 로컬에 파일 생성됨)

return uploadImageUrl; // 업로드된 파일의 S3 URL 주소 반환
}

Expand Down Expand Up @@ -68,17 +67,23 @@ private File convert(MultipartFile file) throws IOException {
}

// 파일 삭제
public void deleteFile(String fileName) {
public void deleteFile(String url) {
try {
String decodedFileName = URLDecoder.decode(fileName, "UTF-8");
// URL 객체 생성
URL s3URL = new URL(url);
String path = s3URL.getPath();

if (path.startsWith("/")) {
path = path.substring(1);
}
String decodedFileName = URLDecoder.decode(path, "UTF-8");
log.info("Deleting file from S3: " + decodedFileName);
amazonS3Client.deleteObject(bucket, decodedFileName);
} catch (UnsupportedEncodingException e) {
log.error("Error while decoding the file name: {}", e.getMessage());
amazonS3Client.deleteObject(new DeleteObjectRequest(bucket, decodedFileName));
} catch (Exception e) {
log.error("Error deleting file from S3: " + e.getMessage());
}
}


// 파일 확장자 추출
private String extractExt(String originalFilename) {
int pos = originalFilename.lastIndexOf(".");
Expand Down

0 comments on commit 706c005

Please sign in to comment.