Skip to content

Commit

Permalink
Merge branch 'feature/#29' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeongh00 committed Nov 24, 2024
2 parents d25dc17 + 06758e8 commit 4b315b5
Show file tree
Hide file tree
Showing 12 changed files with 329 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Backend CD # actions 이름

on:
push:
branches: [ fix/#28 ]
branches: [ feature/#29 ]

jobs:
deploy:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,20 @@ public ChallengeList findChallengeList(User user, Long challengeId) {
}

private double calculateRate(List<Report> reports, Challenge challenge) {
int totalSum = 0;
double totalSum = 0;

switch (challenge.getType()) {
case CALORIE:
totalSum = reports.stream().mapToInt(Report::getTotal).sum();
totalSum = reports.stream().mapToDouble(Report::getTotal).sum();
break;
case CARB:
totalSum = reports.stream().mapToInt(Report::getCarb).sum();
totalSum = reports.stream().mapToDouble(Report::getCarb).sum();
break;
case PROTEIN:
totalSum = reports.stream().mapToInt(Report::getProtein).sum();
totalSum = reports.stream().mapToDouble(Report::getProtein).sum();
break;
case FAT:
totalSum = reports.stream().mapToInt(Report::getFat).sum();
totalSum = reports.stream().mapToDouble(Report::getFat).sum();
break;
case FREQUENCY:
totalSum = reports.size();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.foodgo.apimodule.ingredient.application;

import com.foodgo.apimodule.report.mapper.ReportMapper;
import com.foodgo.coremodule.ingredient.dto.request.IngredientGetRequest;
import com.foodgo.coremodule.ingredient.dto.response.IngredientGetResponse;
import com.foodgo.coremodule.report.domain.Report;
import com.foodgo.coremodule.report.service.ReportQueryService;
import com.foodgo.coremodule.user.domain.User;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -19,6 +22,8 @@ public class IngredientFindUseCase {
@Value("${spring.openapi.key.ingredient}")
private String apiKey;

private final ReportQueryService reportQueryService;

public IngredientGetResponse.Row getIngredient(User user, IngredientGetRequest request) throws URISyntaxException {

String apiUrl = "http://openapi.foodsafetykorea.go.kr/api/" + apiKey + "/I2790/json/1/100/DESC_KOR=" + request.descKor();
Expand All @@ -39,6 +44,13 @@ public IngredientGetResponse.Row getIngredient(User user, IngredientGetRequest r
.filter(row -> groupNameMatches(row, request.groupName()))
.toList();

// 리포트 저장 후 결과 반환
if (!filteredRows.isEmpty()) {
IngredientGetResponse.Row selectedRow = filteredRows.get(0);
Report report = ReportMapper.mapToReport(user, selectedRow);
reportQueryService.saveReport(report); // 리포트 저장
}

return filteredRows.isEmpty() ? null : filteredRows.get(0);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,49 @@
package com.foodgo.apimodule.ingredient.presentation;

import java.net.URISyntaxException;

import com.foodgo.apimodule.ingredient.application.IngredientFindUseCase;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.foodgo.commonmodule.common.ApplicationResponse;
import com.foodgo.coremodule.ingredient.dto.request.IngredientGetRequest;
import com.foodgo.coremodule.ingredient.dto.response.IngredientGetResponse;
import com.foodgo.coremodule.security.annotation.UserResolver;
import com.foodgo.coremodule.user.domain.User;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URISyntaxException;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/ingredients")
@Tag(name = "ingredient", description = "식재료 관련 API")
public class IngredientController {

private final IngredientFindUseCase ingredientFindUseCase;
private final IngredientFindUseCase ingredientFindUseCase;

@PostMapping("")
public ApplicationResponse<IngredientGetResponse.Row> getIngredientInfo(
@UserResolver User user,
@RequestBody @Valid IngredientGetRequest request
) throws URISyntaxException {
return ApplicationResponse.onSuccess(ingredientFindUseCase.getIngredient(user, request));
}
@PostMapping("")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "식재료 정보 확인 성공",
useReturnTypeSchema = true
)
}
)
@Operation(summary = "식재료 정보 확인 API", description = "식재료 정보 확인 + 리포트 DB 저장 API 입니다.")
public ApplicationResponse<IngredientGetResponse.Row> getIngredientInfo(
@UserResolver User user,
@RequestBody @Valid IngredientGetRequest request
) throws URISyntaxException {
return ApplicationResponse.onSuccess(ingredientFindUseCase.getIngredient(user, request));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.foodgo.apimodule.report.application;

import com.foodgo.coremodule.report.dto.ReportComparisonDTO;
import com.foodgo.coremodule.report.service.ReportQueryService;
import com.foodgo.coremodule.user.domain.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ReportFindUseCase {

private final ReportQueryService reportQueryService;

// 통게 dto list 만들기
public ReportComparisonDTO getStatistics(User user) {
return reportQueryService.getWeeklyReportComparison(user.getId());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.foodgo.apimodule.report.dto;

public record ReportStatistics(
String name,
Double lastweek,
Double thisweek
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.foodgo.apimodule.report.mapper;

import com.foodgo.coremodule.ingredient.dto.response.IngredientGetResponse;
import com.foodgo.coremodule.report.domain.MealType;
import com.foodgo.coremodule.report.domain.Report;
import com.foodgo.coremodule.user.domain.User;

import java.time.LocalTime;

public class ReportMapper {

public static Report mapToReport(User user, IngredientGetResponse.Row row) {
MealType mealType = determineMealType(); // MealType을 결정하는 메서드 호출

return Report.builder()
.user(user)
.type(mealType) // MealType 저장
.total(Double.parseDouble(row.getNutrCont1())) // 총 칼로리
.carb(Double.parseDouble(row.getNutrCont2())) // 탄수화물
.protein(Double.parseDouble(row.getNutrCont3())) // 단백질
.fat(Double.parseDouble(row.getNutrCont4())) // 지방
.sugar(Double.parseDouble(row.getNutrCont5())) // 당류
.sodium(Double.parseDouble(row.getNutrCont6())) // 나트륨
.cholesterol(Double.parseDouble(row.getNutrCont7())) // 콜레스테롤
.saturatedFat(Double.parseDouble(row.getNutrCont8())) // 포화지방산
.transFat(Double.parseDouble(row.getNutrCont9())) // 트랜스지방
.build();
}

private static MealType determineMealType() {
LocalTime now = LocalTime.now();

if (now.isBefore(LocalTime.NOON)) {
return MealType.BREAKFAST; // 정오 이전이면 아침
} else if (now.isBefore(LocalTime.of(15, 0))) {
return MealType.LUNCH; // 오후 3시 이전이면 점심
} else {
return MealType.DINNER; // 그 이후는 저녁
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.foodgo.apimodule.report.presentation;

import com.foodgo.apimodule.report.application.ReportFindUseCase;
import com.foodgo.commonmodule.common.ApplicationResponse;
import com.foodgo.coremodule.report.dto.ReportComparisonDTO;
import com.foodgo.coremodule.security.annotation.UserResolver;
import com.foodgo.coremodule.user.domain.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/report")
@Tag(name = "report", description = "리포트 관련 API")
public class ReportController {

private final ReportFindUseCase reportFindUseCase;

@GetMapping()
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "리포트 통계 확인 성공",
useReturnTypeSchema = true
)
}
)
@Operation(summary = "리포트 통계 확인 API", description = "리포트 통계 확인 API 입니다.")
public ApplicationResponse<ReportComparisonDTO> findReportStatistics(
@UserResolver User user) {

ReportComparisonDTO comparisonDTO = reportFindUseCase.getStatistics(user);
return ApplicationResponse.onSuccess(comparisonDTO);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@

import com.foodgo.coremodule.report.domain.Report;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.time.LocalDateTime;
import java.util.List;

public interface ReportRepository extends JpaRepository<Report, Long> {

List<Report> findAllByUserIdAndCreatedAtBetween(Long userId, LocalDateTime start, LocalDateTime end);

// 이번 주 총 레포트 조회
@Query("SELECT r FROM Report r WHERE r.user.id = :userId AND r.createdAt >= :startOfWeek AND r.createdAt < :endOfWeek")
List<Report> findReportsByUserAndCreatedAtBetween(Long userId, LocalDateTime startOfWeek, LocalDateTime endOfWeek);

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,29 @@ public class Report extends BaseEntity {
private MealType type;

@Column(name = "report_total", nullable = false)
private Integer total;
private Double total;

@Column(name = "report_carb", nullable = false)
private Integer carb;
private Double carb;

@Column(name = "report_protein", nullable = false)
private Integer protein;
private Double protein;

@Column(name = "report_fat", nullable = false)
private Integer fat;
private Double fat;

@Column(name = "report_sugar", nullable = false)
private Double sugar; // 당류

@Column(name = "report_sodium", nullable = false)
private Double sodium; // 나트륨

@Column(name = "report_cholesterol", nullable = false)
private Double cholesterol; // 콜레스테롤

@Column(name = "report_saturated_fat", nullable = false)
private Double saturatedFat; // 포화지방산

@Column(name = "report_trans_fat", nullable = false)
private Double transFat; // 트랜스지방
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.foodgo.coremodule.report.dto;

public record ReportComparisonDTO(
Double lastWeekTotal,
Double thisWeekTotal,
Double lastWeekCarbs,
Double thisWeekCarbs,
Double lastWeekProteins,
Double thisWeekProteins,
Double lastWeekFats,
Double thisWeekFats,
Double lastWeekSugar,
Double thisWeekSugar,
Double lastWeekSodium,
Double thisWeekSodium,
Double lastWeekCholesterol,
Double thisWeekCholesterol,
Double lastWeekSaturatedFat,
Double thisWeekSaturatedFat,
Double lastWeekTransFat,
Double thisWeekTransFat
) {
}
Loading

0 comments on commit 4b315b5

Please sign in to comment.