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: 메뉴 판매량 및 재고 기록 CRUD 작성 #26

Open
wants to merge 6 commits into
base: main
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 @@ -84,7 +84,7 @@ public BaseResponse fileSizeLimitExceeded(final MaxUploadSizeExceededException e
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
protected BaseResponse handleException(final Exception e, final HttpServletRequest request) throws IOException {
log.error("Internal Server Error: {}", e.getMessage());
log.error("Internal Server Error: {}", e.getMessage(), e);
return BaseResponse.error(ErrorCode.INTERNAL_SERVER_ERROR);
}

Expand Down
54 changes: 27 additions & 27 deletions src/main/java/net/skhu/tastyinventory_be/config/MvcConfigurer.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
//package net.skhu.tastyinventory_be.config;
//
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.HttpMethod;
//import org.springframework.web.servlet.config.annotation.CorsRegistry;
//import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//
//@Configuration
//public class MvcConfigurer implements WebMvcConfigurer {
// @Value("${client.origins}")
// private String[] allowedOrigins;
//
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOrigins(allowedOrigins)
// .allowedMethods(
// HttpMethod.GET.name(),
// HttpMethod.HEAD.name(),
// HttpMethod.POST.name(),
// HttpMethod.PUT.name(),
// HttpMethod.DELETE.name())
// .maxAge(3600)
// .allowCredentials(true);
// }
//}
package net.skhu.tastyinventory_be.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfigurer implements WebMvcConfigurer {
@Value("${client.origins}")
private String[] allowedOrigins;

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(allowedOrigins)
.allowedMethods(
HttpMethod.GET.name(),
HttpMethod.HEAD.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name())
.maxAge(3600)
.allowCredentials(true);
}
}
Comment on lines +1 to +27
Copy link
Contributor

Choose a reason for hiding this comment

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

이 부분 다시 주석 처리! cors 에러는 요청에 헤더를 추가하는 과정이라서 nginx랑 spring에서 cors 처리 이중으로 하면 충돌 남..ㅇㅇ 이거는 로컬에서 리액트랑 스프링 같이 테스트할 때만 써주세여

Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.skhu.tastyinventory_be.common.dto.BaseResponse;
import net.skhu.tastyinventory_be.controller.inventoryRecord.dto.request.InventoryRecordDto;
import net.skhu.tastyinventory_be.controller.inventoryRecord.dto.request.InventoryRecordRequestDto;
import net.skhu.tastyinventory_be.controller.inventoryRecord.dto.request.InventoryRecordUpdateRequestDto;
import net.skhu.tastyinventory_be.controller.inventoryRecord.dto.response.InventoryRecordResponseDto;
import net.skhu.tastyinventory_be.domain.inventoryRecord.InventoryRecord;
import net.skhu.tastyinventory_be.exception.SuccessCode;
import net.skhu.tastyinventory_be.service.InventoryRecordService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@RequestMapping("/inventory-records")
Expand All @@ -23,4 +29,21 @@ public BaseResponse<?> createRecord(@RequestBody @Valid InventoryRecordRequestDt
inventoryRecordService.createInventoryRecord(requestDto);
return BaseResponse.success(SuccessCode.INVENTORY_RECORD_CREATE_SUCCESS);
}
@GetMapping
public BaseResponse<List<InventoryRecordResponseDto>> getAllRecords() {
return BaseResponse.success(SuccessCode.INVENTORY_RECORD_GET_SUCCESS, inventoryRecordService.getAllInventoryRecords());
}
@PatchMapping("/{id}")
public BaseResponse<?> updateRecord(@PathVariable Long id, @RequestBody @Valid InventoryRecordUpdateRequestDto requestDto) {
inventoryRecordService.updateInventoryRecord(id, requestDto);
return BaseResponse.success(SuccessCode.INVENTORY_RECORD_PATCH_SUCCESS);
}

@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public BaseResponse<?> deleteRecord(@PathVariable Long id) {
inventoryRecordService.deleteInventoryRecord(id);
return BaseResponse.success(SuccessCode.INVENTORY_RECORD_DELETE_SUCCESS);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package net.skhu.tastyinventory_be.controller.inventoryRecord.dto.request;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class InventoryRecordUpdateRequestDto {
@NotBlank(message = "날짜를 입력하세요")
@Pattern(
regexp="^\\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$",
message = "YYYY-MM-DD 형식으로 입력하세요"
)
private String date;

@NotNull(message = "현 재고량을 입력하세요")
private Long currentVolume;

@NotNull(message = "발주량을 입력하세요")
private Long orderVolume;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package net.skhu.tastyinventory_be.controller.inventoryRecord.dto.response;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import net.skhu.tastyinventory_be.domain.inventoryRecord.InventoryRecord;

@Getter
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class InventoryRecordResponseDto {
private Long id;
private String date;
private Long inventoryId;
private Long currentVolume;
private Long orderVolume;

public InventoryRecordResponseDto(InventoryRecord inventoryRecord) {
this.id = inventoryRecord.getId();
this.date = inventoryRecord.getDate().toString();
this.inventoryId = inventoryRecord.getInventory().getId();
this.currentVolume = inventoryRecord.getCurrentVolume();
this.orderVolume = inventoryRecord.getOrderVolume();
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package net.skhu.tastyinventory_be.controller.sold;

import com.fasterxml.jackson.databind.ser.Serializers;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.skhu.tastyinventory_be.common.dto.BaseResponse;
import net.skhu.tastyinventory_be.controller.sold.dto.request.SoldRequestDto;
import net.skhu.tastyinventory_be.controller.sold.dto.response.SoldResponseDto;
import net.skhu.tastyinventory_be.exception.SuccessCode;
import net.skhu.tastyinventory_be.service.SoldService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@RequestMapping("/sold")
Expand All @@ -23,4 +27,20 @@ public BaseResponse<?> registerSold(@RequestBody @Valid SoldRequestDto requestDt
soldService.registerSold(requestDto);
return BaseResponse.success(SuccessCode.SOLD_CREATE_SUCCESS);
}
@GetMapping
public BaseResponse<List<SoldResponseDto>> findAllSold() {
List<SoldResponseDto> soldResponseDtoList = soldService.findAllSold();
return BaseResponse.success(SuccessCode.GET_SUCCESS, soldResponseDtoList);
}
@PatchMapping("/{id}")
public BaseResponse<?> updateSold(@PathVariable("id") Long id, @RequestBody @Valid SoldRequestDto requestDto) {
soldService.updateSold(id, requestDto);
return BaseResponse.success(SuccessCode.SOLD_PATCH_SUCCESSCODE);
}

@DeleteMapping("/{id}")
public BaseResponse<?> deleteSold(@PathVariable("id") Long id) {
soldService.deleteSold(id);
return BaseResponse.success(SuccessCode.SOLD_DELETE_SUCCESSCODE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package net.skhu.tastyinventory_be.controller.sold.dto.response;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class SoldResponseDto {
private Long id;
private String menuName;
private Long count;

public static SoldResponseDto of(Long id, String menuName, Long count) {
return new SoldResponseDto(id, menuName, count);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@ public abstract class BaseEntity {
@Column(name = "UPDATE_AT", nullable = false)
@LastModifiedDate
private LocalDateTime updateAt;

protected void setId(Long id) {
this.id = id;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

이 부분 어쩌다가 들어갔지요? id 값은 보통 한 번 생성되면 불변인데..?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

아 id를 받아야했어서 생성했었긴 한데 수정해볼게여

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,9 @@ public InventoryRecord(LocalDate date, Inventory inventory, Long currentVolume,
this.currentVolume = currentVolume;
this.orderVolume = orderVolume;
}
public void update(LocalDate date, Long currentVolume, Long orderVolume) {
this.date = date;
this.currentVolume = currentVolume;
this.orderVolume = orderVolume;
}
}
10 changes: 9 additions & 1 deletion src/main/java/net/skhu/tastyinventory_be/domain/sold/Sold.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import net.skhu.tastyinventory_be.controller.sold.dto.request.SoldMenuDto;
import net.skhu.tastyinventory_be.controller.sold.dto.request.SoldRequestDto;
import net.skhu.tastyinventory_be.domain.BaseEntity;
import net.skhu.tastyinventory_be.domain.menu.Menu;
import org.springframework.cglib.core.Local;

import java.time.LocalDate;
import java.util.List;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand All @@ -26,9 +30,13 @@ public class Sold extends BaseEntity {
private Long count;

@Builder
public Sold(LocalDate date, Menu menu, Long count) {
public Sold(Long id, LocalDate date, Menu menu, Long count) {
this.setId(id);
Copy link
Contributor

Choose a reason for hiding this comment

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

여기가 원인인듯? 생성자에 id 없어도 됩니당

this.date = date;
this.menu = menu;
this.count = count;
}
public void update(Long count) {
this.count = count; // 판매량을 업데이트
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package net.skhu.tastyinventory_be.domain.sold;

import net.skhu.tastyinventory_be.domain.menu.Menu;
import org.springframework.data.jpa.repository.JpaRepository;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

public interface SoldRepository extends JpaRepository<Sold, Long> {
List<Sold> findByDate(LocalDate date);
Optional<Sold> findByDateAndMenu(LocalDate date, Menu menu);
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ public enum ErrorCode {
NOT_FOUND_INVENTORY_EXCEPTION(HttpStatus.NOT_FOUND, "존재하지 않는 재고입니다"),
NOT_FOUND_MENU_EXCEPTION(HttpStatus.NOT_FOUND, "존재하지 않는 메뉴입니다"),
NOT_FOUND_EMPLOYEE_EXCEPTION(HttpStatus.NOT_FOUND, "존재하지 않는 직원입니다"),
NOT_FOUND_SOLD_EXCEPTION(HttpStatus.NOT_FOUND, "재고량이 존재하지 않습니다"),
NOT_FOUND_INVENTORY_RECORD_EXCEPTION(HttpStatus.NOT_FOUND, "재고기록이 존재하지 않습니다"),
NOT_FOUND_SCHEDULE_EXCEPTION(HttpStatus.NOT_FOUND, "존재하지 않는 스케줄입니다"),

/**
* 500 INTERNAL SERVER ERROR
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ public enum SuccessCode {
INVENTORY_PATCH_SUCCESS(HttpStatus.OK, "재고 수정이 완료되었습니다"),
MENU_PATCH_SUCCESS(HttpStatus.OK, "메뉴 수정이 완료되었습니다"),
MENU_DELETE_SUCCESS(HttpStatus.OK, "메뉴 삭제에 성공했습니다"),
SOLD_DELETE_SUCCESSCODE(HttpStatus.OK, "메뉴 판매량 삭제에 성공했습니다"),
SOLD_PATCH_SUCCESSCODE(HttpStatus.NO_CONTENT, "재고량 정보 수정이 완료되었습니다"),
INVENTORY_RECORD_GET_SUCCESS(HttpStatus.OK, "재고량 정보 조회에 성공했습니다"),
INVENTORY_RECORD_PATCH_SUCCESS(HttpStatus.OK, "재고량 정보 수정이 완료되었습니다"),
INVENTORY_RECORD_DELETE_SUCCESS(HttpStatus.OK, "재고량 정보 삭제에 성공했습니다"),


/**
* 201 CREATED
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import lombok.RequiredArgsConstructor;
import net.skhu.tastyinventory_be.controller.inventoryRecord.dto.request.InventoryRecordRequestDto;
import net.skhu.tastyinventory_be.controller.inventoryRecord.dto.request.InventoryRecordUpdateRequestDto;
import net.skhu.tastyinventory_be.controller.inventoryRecord.dto.response.InventoryRecordResponseDto;
import net.skhu.tastyinventory_be.domain.inventory.Inventory;
import net.skhu.tastyinventory_be.domain.inventory.InventoryRepository;
import net.skhu.tastyinventory_be.domain.inventoryRecord.InventoryRecord;
Expand All @@ -12,6 +14,8 @@
import org.springframework.transaction.annotation.Transactional;

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

@RequiredArgsConstructor
@Transactional(readOnly = true)
Expand Down Expand Up @@ -43,4 +47,36 @@ public void createInventoryRecord(InventoryRecordRequestDto requestDto) {
inventoryRecordRepository.save(inventoryRecord);
}
}
public List<InventoryRecordResponseDto> getAllInventoryRecords() {
return inventoryRecordRepository.findAll().stream()
.map(InventoryRecordResponseDto::new)
.collect(Collectors.toList());
}

@Transactional
public void updateInventoryRecord(Long id, InventoryRecordUpdateRequestDto requestDto) {
InventoryRecord inventoryRecord = inventoryRecordRepository.findById(id).orElseThrow(
() -> new NotFoundException(
ErrorCode.NOT_FOUND_INVENTORY_RECORD_EXCEPTION,
ErrorCode.NOT_FOUND_INVENTORY_RECORD_EXCEPTION.getMessage() + id
));

inventoryRecord.update(
LocalDate.parse(requestDto.getDate()),
requestDto.getCurrentVolume(),
requestDto.getOrderVolume()
);

inventoryRecordRepository.save(inventoryRecord);
}

@Transactional
public void deleteInventoryRecord(Long id) {
InventoryRecord inventoryRecord = inventoryRecordRepository.findById(id).orElseThrow(
() -> new NotFoundException(
ErrorCode.NOT_FOUND_INVENTORY_RECORD_EXCEPTION,
ErrorCode.NOT_FOUND_INVENTORY_RECORD_EXCEPTION.getMessage() + id
));
inventoryRecordRepository.delete(inventoryRecord);
}
}
Loading