Skip to content

Commit 0ef4352

Browse files
authored
[Refactor]DietServiceV2 서비스 로직 클래스 분리 (#30)
* [Fix]Test 코드 수정 * [Refactor]CafeteriaServiceV2 단일 책임 원칙 적용하여 클래스 분리 * Update Java CI-CD.yml dependency submission code removed * [Refactor]CampusServiceV2 클래스 분리 * [Refactor]DietServiceV2 서비스 클래스 분리
1 parent b411e53 commit 0ef4352

File tree

4 files changed

+244
-199
lines changed

4 files changed

+244
-199
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package com.example.Jinus.service.v2.cafeteria;
2+
3+
import com.example.Jinus.dto.data.HandleRequestDto;
4+
import com.example.Jinus.dto.request.DetailParamsItemFieldDto;
5+
import com.example.Jinus.dto.request.RequestDto;
6+
import com.example.Jinus.service.v2.userInfo.UserServiceV2;
7+
import lombok.RequiredArgsConstructor;
8+
import org.springframework.stereotype.Service;
9+
10+
import java.sql.Date;
11+
import java.time.LocalDate;
12+
import java.time.LocalTime;
13+
import java.util.Optional;
14+
15+
@Service
16+
@RequiredArgsConstructor
17+
public class DietParameterServiceV2 {
18+
19+
private final UserServiceV2 userServiceV2;
20+
private final CampusServiceV2 campusServiceV2;
21+
22+
// 요청 파라미터 객체 생성
23+
public HandleRequestDto setParameters(String kakaoId, LocalTime time, RequestDto requestDto) {
24+
// 요청 필수 파라미터 추출
25+
String cafeteriaName = requestDto.getAction().getParams().getSys_cafeteria_name();
26+
27+
// DetailParams에서 일반 파라미터 추출 및 초기화(null 체크 포함)
28+
String campusNameValue = extractValue(requestDto.getAction().getDetailParams().getSys_campus_name())
29+
.orElseGet(() -> getCampusName(kakaoId));
30+
String dayValue = extractValue(requestDto.getAction().getDetailParams().getSys_date())
31+
.orElseGet(() -> getDay(time));
32+
String periodValue = extractValue(requestDto.getAction().getDetailParams().getSys_time_period())
33+
.orElseGet(() -> getPeriodOfDay(time));
34+
35+
// 오늘, 내일 문자열로 날짜 생성
36+
Date dietDate = getCurrentDate(dayValue);
37+
// 요청 파라미터 객체 생성
38+
return new HandleRequestDto(kakaoId, campusNameValue, dayValue, periodValue, cafeteriaName, dietDate);
39+
}
40+
41+
// 일반 파라미터가 null인 경우 기본값 설정
42+
private Optional<String> extractValue(DetailParamsItemFieldDto fieldDto) {
43+
return Optional.ofNullable(fieldDto).map(DetailParamsItemFieldDto::getValue);
44+
}
45+
46+
// 일반 파라미터 값 채우기
47+
// sys_campus_name 파라미터 초기화
48+
private String getCampusName(String kakaoId) {
49+
// 학과 등록 여부 확인
50+
int campusId = userServiceV2.getUserCampusId(kakaoId);
51+
// 학과 등록한 경우 campusId가 존재함
52+
if (campusId != -1) {
53+
return campusServiceV2.getUserCampusName(campusId);
54+
} else { // 학과 등록 안한 경우
55+
return "가좌캠퍼스";
56+
}
57+
}
58+
59+
// sys_date 파라미터 초기화 - 시간 범위에 따라 오늘, 내일 판별
60+
private String getDay(LocalTime time) {
61+
if (time.isAfter(LocalTime.parse("00:00:00")) && time.isBefore(LocalTime.parse("19:00:00"))) {
62+
return "오늘";
63+
} else {
64+
return "내일";
65+
}
66+
}
67+
68+
// sys_period 파라미터 초기화 - 시간 범위에 따라 아침, 점심, 저녁을 판별
69+
private String getPeriodOfDay(LocalTime time) {
70+
if (time.isAfter(LocalTime.parse("19:00:00")) || time.isBefore(LocalTime.parse("09:30:00"))) {
71+
return "아침";
72+
} else if (!time.isBefore(LocalTime.parse("09:30:00")) && time.isBefore(LocalTime.parse("13:30:00"))) {
73+
return "점심";
74+
} else {
75+
return "저녁";
76+
}
77+
}
78+
79+
// sysDay 파라미터 값으로 조회할 날짜 찾는 함수
80+
private Date getCurrentDate(String sysDate) {
81+
// 현재 날짜
82+
LocalDate today = LocalDate.now();
83+
LocalDate tomorrow = today.plusDays(1); // 하루 뒤 날짜 계산
84+
85+
if (sysDate.equals("오늘")) {
86+
return Date.valueOf(today);
87+
} else { // 내일
88+
return Date.valueOf(tomorrow);
89+
}
90+
}
91+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package com.example.Jinus.service.v2.cafeteria;
2+
3+
import com.example.Jinus.dto.data.DietDto;
4+
import com.example.Jinus.dto.data.HandleRequestDto;
5+
import com.example.Jinus.repository.v2.cafeteria.DietRepositoryV2;
6+
import lombok.RequiredArgsConstructor;
7+
import org.springframework.stereotype.Service;
8+
import org.springframework.util.LinkedMultiValueMap;
9+
import org.springframework.util.MultiValueMap;
10+
11+
import java.sql.Date;
12+
import java.util.List;
13+
import java.util.Set;
14+
import java.util.TreeSet;
15+
16+
@Service
17+
@RequiredArgsConstructor
18+
public class DietQueryServiceV2 {
19+
20+
private final CacheServiceV2 cacheServiceV2;
21+
private final DietRepositoryV2 dietRepositoryV2;
22+
23+
// 메뉴 존재 여부에 따른 반환값 처리 로직
24+
public String getDietResponse(HandleRequestDto parameters, int cafeteriaId) {
25+
// 메뉴 존재하는 경우
26+
if (checkThereIsDiet(parameters, cafeteriaId) != -1) {
27+
// 메뉴 찾기
28+
MultiValueMap<String, String> dietList = getDiets(parameters, cafeteriaId);
29+
return processDietList(dietList).toString();
30+
}
31+
return "\n메뉴가 존재하지 않습니다."; // 메뉴가 없는 경우
32+
}
33+
34+
35+
// 식당 메뉴 존재여부 확인
36+
private int checkThereIsDiet(HandleRequestDto parameters, int cafeteriaId) {
37+
// 오늘, 내일 문자열로 날짜 설정하기
38+
Date dietDate = parameters.getDietDate();
39+
List<DietDto> dietDtos =
40+
dietRepositoryV2.findDietList(dietDate, parameters.getPeriod(), cafeteriaId);
41+
return (!dietDtos.isEmpty()) ? 1 : -1;
42+
}
43+
44+
45+
// 카테고리별 메뉴 리스트 생성하기
46+
private MultiValueMap<String, String> getDiets(HandleRequestDto parameters, int cafeteriaId) {
47+
List<DietDto> dietDtos = cacheServiceV2.getDietList(parameters, cafeteriaId);
48+
MultiValueMap<String, String> dietList = new LinkedMultiValueMap<>(); // 중복 키 허용(값을 리스트로 반환)
49+
50+
for (DietDto o : dietDtos) {
51+
String key = (o.getDishCategory() != null) ? o.getDishCategory()
52+
: (o.getDishType() != null) ? o.getDishType()
53+
: "메뉴";
54+
55+
dietList.add(key, o.getDishName());
56+
}
57+
return dietList;
58+
}
59+
60+
// 카테고리별 메뉴 문자열로 나열하기
61+
private StringBuilder processDietList(MultiValueMap<String, String> dietList) {
62+
// 키 추출
63+
Set<String> keys = new TreeSet<>(dietList.keySet()); // 순서 보장 - 오름차순
64+
StringBuilder description = new StringBuilder();
65+
66+
for (String key : keys) {
67+
description.append("\n[").append(key).append("]").append("\n");
68+
dietList.get(key).forEach(diet -> description.append(diet).append("\n"));
69+
}
70+
return description;
71+
}
72+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.example.Jinus.service.v2.cafeteria;
2+
3+
import com.example.Jinus.dto.data.HandleRequestDto;
4+
import com.example.Jinus.dto.response.*;
5+
import com.example.Jinus.utility.JsonUtils;
6+
import com.example.Jinus.utility.SimpleTextResponse;
7+
import lombok.RequiredArgsConstructor;
8+
import org.springframework.stereotype.Service;
9+
10+
import java.util.List;
11+
import java.util.stream.Collectors;
12+
13+
@Service
14+
@RequiredArgsConstructor
15+
public class DietResponseServiceV2 {
16+
17+
// 응답 객체 매핑
18+
public String mappingResponse(HandleRequestDto parameters, String imgUrl, String title, String description) {
19+
// imgUrl 객체 생성
20+
ThumbnailDto thumbnail = new ThumbnailDto(imgUrl);
21+
22+
// 버튼 리스트 객체 생성
23+
List<ButtonDto> buttonList = List.of(new ButtonDto("공유하기", "share"));
24+
25+
// 아이템 객체 생성
26+
BasicCardDto basicCardDto = new BasicCardDto(title, description, thumbnail, buttonList);
27+
List<ComponentDto> outputs = List.of(new ComponentDto(basicCardDto));
28+
29+
List<QuickReplyDto> quickReplies = mappingQuickReply(parameters);
30+
31+
TemplateDto templateDto = new TemplateDto(outputs, quickReplies);
32+
ResponseDto responseDto = new ResponseDto("2.0", templateDto);
33+
34+
return JsonUtils.toJsonResponse(responseDto);
35+
}
36+
37+
private List<QuickReplyDto> mappingQuickReply(HandleRequestDto parameters) {
38+
List<String> periods = getNextMealPeriods(parameters.getPeriod());
39+
return periods.stream()
40+
.map(period -> createQuickReply(period, parameters))
41+
.collect(Collectors.toList());
42+
}
43+
44+
// 현재 시간대(period)에 따라 다음 선택할 식사 시간대를 반환
45+
private List<String> getNextMealPeriods(String currentPeriod) {
46+
return switch (currentPeriod) {
47+
case "아침" -> List.of("점심", "저녁");
48+
case "점심" -> List.of("아침", "저녁");
49+
default -> List.of("아침", "점심");
50+
};
51+
}
52+
53+
// QuickReplyDto 객체를 생성하는 메서드
54+
private QuickReplyDto createQuickReply(String period, HandleRequestDto parameters) {
55+
String message = String.format("%s %s %s %s 메뉴",
56+
parameters.getCampusName(),
57+
parameters.getCafeteriaName(),
58+
parameters.getDay(),
59+
period);
60+
return new QuickReplyDto(period, "message", message);
61+
}
62+
63+
// 캠퍼스에 식당이 존재하지 않는 경우 메시지 출력
64+
public String errorMsgThereIsNoCafeteria() {
65+
return SimpleTextResponse
66+
.simpleTextResponse("식당을 찾지 못했어!\n어떤 캠퍼스에 있는 식당인지 정확히 알려줘!");
67+
}
68+
}

0 commit comments

Comments
 (0)