Skip to content
Merged

San #11

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
23 changes: 23 additions & 0 deletions src/main/java/com/example/helper/constant/Types.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.helper.constant;

public enum Types {
LANG_KOR(0),
LANG_ENG(1),
BLDG1_1ST(0),
BLDG1_2ND(1),
BLDG2_1ST(2),
KIND_BREAKFAST(0),
KIND_LUNCH(1),
KIND_DINNER(2),
KIND_LUNCH_CORNER(3);

private Integer type;

Types(Integer type) {
this.type = type;
}

public Integer getType() {
return type;
}
}
59 changes: 48 additions & 11 deletions src/main/java/com/example/helper/controller/MealController.java
Original file line number Diff line number Diff line change
@@ -1,39 +1,48 @@
package com.example.helper.controller;
import com.example.helper.dto.DateMealDto;
import com.example.helper.dto.DateReqDto;
import com.example.helper.dto.Mealdto;
import com.example.helper.entity.Meal;
import com.example.helper.service.DateMealService;
import com.example.helper.service.MealService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.server.ResponseStatusException;


@RestController
@RestController // @Controller + @ResponseBody. return이 view가 아닌, http body에 직접 쓰여짐.
@RequestMapping(path = "/meals", produces = "application/json;charset=UTF-8")
@Slf4j
public class MealController {

@Autowired
private MealService mealService;

@Autowired
private DateMealService dateMealService;

@GetMapping("/all")
public String hello() {
return "Hello HELPERs. 초기 세팅 완료.";
}

@PostMapping("/test")
public @ResponseBody void test(String testStr) {
public void test(String testStr) {
log.info(testStr);
}

@PostMapping("/create")
public @ResponseBody String createMeal(@RequestBody Mealdto mealDto) {
public String createMeal(@RequestBody Mealdto mealDto) {
// input : 식단 json
// output : None

Expand All @@ -48,7 +57,7 @@ public String hello() {
}

@PostMapping("/kor")
public @ResponseBody String readKorMeal() throws JsonProcessingException {
public String readKorMeal() throws JsonProcessingException {
// input : None (먼저 서버에서 현재 시간 측정)
// output : 한국어 식단이 포함된 JSON (단, JSON은 카톡 서버가 받을 수 있는 형식이여야 함.)

Expand All @@ -70,7 +79,7 @@ public String hello() {
// }
// };

Map<String, Object> simpleText = new HashMap<>();
Map<String, Object> simpleText = new HashMap<>();
simpleText.put("text", nowMeal);

Map<String, Object> simpleTextWrapper = new HashMap<>();
Expand All @@ -93,7 +102,7 @@ public String hello() {
}

@PostMapping("/eng")
public @ResponseBody String readEngMeal() throws JsonProcessingException {
public String readEngMeal() throws JsonProcessingException {
// input : None (먼저 서버에서 현재 시간 측정)
// output : 영어 식단이 포함된 JSON (단, JSON은 카톡 서버가 받을 수 있는 형식이여야 함.)

Expand All @@ -115,7 +124,7 @@ public String hello() {
// }
// };

Map<String, Object> simpleText = new HashMap<>();
Map<String, Object> simpleText = new HashMap<>();
simpleText.put("text", nowMeal);

Map<String, Object> simpleTextWrapper = new HashMap<>();
Expand All @@ -138,7 +147,7 @@ public String hello() {
}

@PostMapping("/speckor")
public @ResponseBody String readSpecKorMeal() throws JsonProcessingException {
public String readSpecKorMeal() throws JsonProcessingException {
// input : 날짜요일내일 + 아점저 + 1/2학
// output : 한국어 식단이 포함된 JSON (단, JSON은 카톡 서버가 받을 수 있는 형식이여야 함.)

Expand All @@ -160,7 +169,7 @@ public String hello() {
// }
// };

Map<String, Object> simpleText = new HashMap<>();
Map<String, Object> simpleText = new HashMap<>();
simpleText.put("text", specMeal);

Map<String, Object> simpleTextWrapper = new HashMap<>();
Expand All @@ -183,7 +192,7 @@ public String hello() {
}

@PostMapping("/speceng")
public @ResponseBody String readSpecEngMeal() throws JsonProcessingException {
public String readSpecEngMeal() throws JsonProcessingException {
// input : 날짜요일내일 + 아점저 + 1/2학
// output : 영어 식단이 포함된 JSON (단, JSON은 카톡 서버가 받을 수 있는 형식이여야 함.)

Expand All @@ -205,7 +214,7 @@ public String hello() {
// }
// };

Map<String, Object> simpleText = new HashMap<>();
Map<String, Object> simpleText = new HashMap<>();
simpleText.put("text", specMeal);

Map<String, Object> simpleTextWrapper = new HashMap<>();
Expand All @@ -226,4 +235,32 @@ public String hello() {

return result;
}

// FE쪽에서 query에 담아주면 아래처럼 dto 객체 하나만 req로 받으면 되서 코드 깔끔함.
// DateMealDto dateMealDtoList = dateMealService.getDateMeal(dateReqDto);
// 근데 FE에서 보낼때 parameter 일일이 적기 귀찮으니 pathvariable로 받아서 처리
@GetMapping("/date/{year}/{month}/{day}/{bldgType}/{langType}")
public DateMealDto DateMealRead(
@PathVariable("langType") Integer langType,
@PathVariable("bldgType") Integer bldgType,
@PathVariable("year") Integer year,
@PathVariable("month") Integer month,
@PathVariable("day") Integer day) {

DateReqDto dateReqDto = DateReqDto.builder()
.langType(langType)
.bldgType(bldgType)
.year(year.toString())
.month(month.toString())
.date(day.toString())
.build();

try {
DateMealDto dateMealDto = dateMealService.getDateMenus(dateReqDto);
return dateMealDto;
} catch (IllegalStateException e) {
throw new ResponseStatusException(
HttpStatus.NOT_ACCEPTABLE, e.getMessage());
}
}
}
24 changes: 24 additions & 0 deletions src/main/java/com/example/helper/dto/DateMealDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.example.helper.dto;

import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

// https://dev-jhl.tistory.com/entry/Lombok-올바른-Lombok-사용법-Builder
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class DateMealDto {
private String breakfast;
private String lunch;
private String lunch_corner;
private String dinner;

@Builder
public DateMealDto(String breakfast, String lunch, String lunch_corner, String dinner) {
this.breakfast = breakfast;
this.lunch = lunch;
this.lunch_corner = lunch_corner;
this.dinner = dinner;
}
}
27 changes: 27 additions & 0 deletions src/main/java/com/example/helper/dto/DateReqDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.example.helper.dto;

import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Getter
@ToString
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class DateReqDto {
private Integer langType;
private Integer bldgType;
private String year;
private String month;
private String date;

@Builder
public DateReqDto(Integer langType, Integer bldgType, String year, String month, String date) {
this.langType = langType;
this.bldgType = bldgType;
this.year = year;
this.month = month;
this.date = date;
}
}
12 changes: 12 additions & 0 deletions src/main/java/com/example/helper/repository/SqlMealRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ public Optional<Meal> findByPk(Integer bldgType, Integer langType, Integer dateT
return result.stream().findAny();
}

public Optional<Meal> findByDate(Integer bldgType, Integer langType, Integer kindType, String date) {
List<Meal> result = em.createQuery("select m from Meal m where " +
"m.bldgType = :bldgType and m.langType = :langType and m.kindType = :kindType " +
"and m.date = :date", Meal.class)
.setParameter("bldgType", bldgType)
.setParameter("langType", langType)
.setParameter("kindType", kindType)
.setParameter("date", date)
.getResultList();
return result.stream().findAny();
}

@Override
public Optional<Meal> findById(Long mealId) {
Meal meal = em.find(Meal.class, mealId);
Expand Down
83 changes: 83 additions & 0 deletions src/main/java/com/example/helper/service/DateMealService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.example.helper.service;

import com.example.helper.constant.Types;
import com.example.helper.dto.DateMealDto;
import com.example.helper.dto.DateReqDto;
import com.example.helper.entity.Meal;
import com.example.helper.repository.SqlMealRepository;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@Slf4j
public class DateMealService {

@Autowired
private SqlMealRepository sqlMealRepository;

public DateMealDto getDateMenus(DateReqDto dateReqDto) {
DateMealDto result = DateMealDto.builder()
.breakfast(getMenuFromMeal(dateReqDto, Types.KIND_BREAKFAST.getType()))
.lunch(getMenuFromMeal(dateReqDto, Types.KIND_LUNCH.getType()))
.dinner(getMenuFromMeal(dateReqDto, Types.KIND_DINNER.getType()))
.lunch_corner((getMenuFromMeal(dateReqDto, Types.KIND_LUNCH_CORNER.getType())))
.build();

// TODO: exception handling(target data is not in DB)
if (checkMenusEmpty(result)) {
throw new IllegalStateException("해당 날짜의 식단이 존재하지 않습니다.");
}
return result;
}

public String getMenuFromMeal(DateReqDto dateReqDto, Integer kindType) {
String result = "";

// DB에는 KIND_TYPE이 0,1,2만 존재. 따라서 KIND_LUNCH_CORNER는 KIND_LUNCH로 찾아서 getSpecial해야함.
Integer temp = kindType; // Integer는 immutable이므로 '='로 복사가능
if (kindType.equals(Types.KIND_LUNCH_CORNER.getType())) {
temp = Types.KIND_LUNCH.getType();
}

Optional<Meal> meal = sqlMealRepository.findByDate(
dateReqDto.getBldgType(),
dateReqDto.getLangType(),
temp,
conv2DateStr(dateReqDto.getYear(), dateReqDto.getMonth(), dateReqDto.getDate()));

if (meal.isPresent()) {
result = meal.get().getMenu();
if (kindType.equals(Types.KIND_LUNCH_CORNER.getType())) {
result = meal.get().getSpecial();
}
}
return result;
}

public String conv2DateStr(String year, String month, String date) {
String result = "";
result = year + "-" + padZero(month) + "-" + padZero(date);
return result;
}

public String padZero(String str) {
String result = "";
if (str.length() == 1) {
result = "0" + str;
} else {
result = str;
}
return result;
}

public boolean checkMenusEmpty(DateMealDto dateMealDto) {
return dateMealDto.getBreakfast().isEmpty() &&
dateMealDto.getLunch().isEmpty() &&
dateMealDto.getDinner().isEmpty() &&
dateMealDto.getLunch_corner().isEmpty();
}
}
4 changes: 3 additions & 1 deletion src/main/java/com/example/helper/service/MealService.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.example.helper.service;

import com.example.helper.dto.DateMealDto;
import com.example.helper.dto.DateReqDto;
import com.example.helper.entity.Meal;
import com.example.helper.repository.MealRepository;
import com.example.helper.repository.SqlMealRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand Down Expand Up @@ -51,5 +54,4 @@ public String getSpecEngMeal() {
//TODO sqlMealRepository.findSpecEngMeal
return "2023-01-27 Breakfast\n\nStudent Union Bldg.2 1st floor\n\nWhite rice*Seasoned rice with seaweed\n";
}

}
2 changes: 1 addition & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/helper_db
spring.datasource.username=helper
spring.datasource.password=12345678
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto=validate

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Expand Down