Skip to content

Commit

Permalink
Merge pull request #130 from Team-HMH/modify/#120-send-finished-chall…
Browse files Browse the repository at this point in the history
…enge-info-list

modify - 완료된 챌린지 정보를 리스트로 보내도록 수정
  • Loading branch information
kseysh authored May 8, 2024
2 parents d1dbb30 + 08e1423 commit 640fc8f
Show file tree
Hide file tree
Showing 16 changed files with 165 additions and 125 deletions.

This file was deleted.

46 changes: 46 additions & 0 deletions src/main/java/sopt/org/hmh/domain/app/service/AppService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package sopt.org.hmh.domain.app.service;

import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sopt.org.hmh.domain.app.domain.AppWithGoalTime;
import sopt.org.hmh.domain.app.domain.AppWithUsageGoalTime;
import sopt.org.hmh.domain.app.domain.exception.AppError;
import sopt.org.hmh.domain.app.domain.exception.AppException;
import sopt.org.hmh.domain.app.dto.request.AppUsageTimeRequest;
import sopt.org.hmh.domain.app.repository.AppWithUsageGoalTimeRepository;
import sopt.org.hmh.domain.dailychallenge.domain.DailyChallenge;

@Service
@RequiredArgsConstructor
@Transactional
public class AppService {

private final AppWithUsageGoalTimeRepository appWithUsageGoalTimeRepository;

public void addAppForHistory(List<AppWithGoalTime> currentChallengeApps, List<AppUsageTimeRequest> apps,
DailyChallenge dailyChallenge, String os) {
appWithUsageGoalTimeRepository.saveAll(supplementAdditionalInfo(currentChallengeApps, apps, dailyChallenge, os));
}

private List<AppWithUsageGoalTime> supplementAdditionalInfo(List<AppWithGoalTime> currentChallengeApps,
List<AppUsageTimeRequest> apps, DailyChallenge dailyChallenge, String os) {
return apps.stream().map(app -> AppWithUsageGoalTime.builder()
.goalTime(this.getGoalTime(currentChallengeApps, app.appCode()))
.appCode(app.appCode())
.dailyChallenge(dailyChallenge)
.os(os)
.usageTime(app.usageTime())
.build()
).toList();
}

private Long getGoalTime(List<AppWithGoalTime> currentChallengeApps, String appCode) {
return currentChallengeApps.stream()
.filter(currentChallengeApp -> currentChallengeApp.getAppCode().equals(appCode))
.findFirst()
.map(AppWithGoalTime::getGoalTime)
.orElseThrow(() -> new AppException(AppError.APP_NOT_FOUND));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import sopt.org.hmh.domain.app.domain.AppWithGoalTime;
import sopt.org.hmh.domain.challenge.domain.exception.ChallengeError;
import sopt.org.hmh.domain.challenge.domain.exception.ChallengeException;
import sopt.org.hmh.global.common.domain.BaseTimeEntity;
import sopt.org.hmh.domain.dailychallenge.domain.DailyChallenge;
import java.util.ArrayList;
Expand Down Expand Up @@ -44,11 +42,4 @@ private Challenge(Integer period, Long userId, Long goalTime, List<AppWithGoalTi
this.isChallengeFailedToday = false;
this.apps = apps;
}

public void setChallengeFailedToday(boolean challengeFailedToday) {
if (challengeFailedToday && this.isChallengeFailedToday) {
throw new ChallengeException(ChallengeError.CHALLENGE_ALREADY_FAILED_TODAY);
}
this.isChallengeFailedToday = challengeFailedToday;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

public interface ChallengeRepository extends JpaRepository<Challenge, Long> {

Optional<Challenge> findById(Long id);

Optional<Challenge> findFirstByUserIdOrderByCreatedAtDesc(Long userId);

void deleteByUserIdIn(List<Long> userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,18 @@ private void validateAppTime(Long appTime) {
throw new AppException(AppError.INVALID_TIME_RANGE);
}

@Deprecated
public Challenge findFirstByUserIdOrderByCreatedAtDescOrElseThrow(Long userId) {
return challengeRepository.findFirstByUserIdOrderByCreatedAtDesc(userId).orElseThrow(
() -> new ChallengeException(ChallengeError.CHALLENGE_NOT_FOUND));
}

public Challenge findByIdOrElseThrow(Long challengeId) {
return challengeRepository.findById(challengeId).orElseThrow(
() -> new ChallengeException(ChallengeError.CHALLENGE_NOT_FOUND));
}

public List<AppWithGoalTime> getCurrentChallengeAppWithGoalTimeByChallengeId(Long challengeId) {
return this.findByIdOrElseThrow(challengeId).getApps();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import sopt.org.hmh.domain.app.dto.request.AppArrayUsageTimeRequest;
import sopt.org.hmh.global.auth.UserId;
import sopt.org.hmh.domain.dailychallenge.dto.request.FinishedDailyChallengeListRequest;
import sopt.org.hmh.global.auth.jwt.JwtConstants;
import sopt.org.hmh.global.common.response.BaseResponse;
import sopt.org.hmh.global.common.response.EmptyJsonResponse;

@Tag(name = "일별챌린지 관련 API")
@SecurityRequirement(name = JwtConstants.AUTHORIZATION)
Expand All @@ -32,9 +30,9 @@ public interface DailyChallengeApi {
responseCode = "500",
description = "서버 내부 오류입니다.",
content = @Content)})
ResponseEntity<BaseResponse<?>> orderAddHistoryDailyChallenge(
@UserId @Parameter(hidden = true) final Long userId,
@RequestHeader("OS") final String os,
@RequestBody final AppArrayUsageTimeRequest request);
ResponseEntity<BaseResponse<EmptyJsonResponse>> orderAddHistoryDailyChallenge(
@Parameter(hidden = true) final Long userId,
final String os,
final FinishedDailyChallengeListRequest request);
}

Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sopt.org.hmh.domain.app.dto.request.AppArrayUsageTimeRequest;
import sopt.org.hmh.domain.dailychallenge.domain.exception.DailyChallengeSuccess;
import sopt.org.hmh.domain.dailychallenge.service.DailyChallengeService;
import sopt.org.hmh.domain.dailychallenge.dto.request.FinishedDailyChallengeListRequest;
import sopt.org.hmh.domain.dailychallenge.service.DailyChallengeFacade;
import sopt.org.hmh.global.auth.UserId;
import sopt.org.hmh.global.common.response.BaseResponse;
import sopt.org.hmh.global.common.response.EmptyJsonResponse;
Expand All @@ -15,18 +15,18 @@
@RequestMapping("/api/v1/challenge/daily")
public class DailyChallengeController implements DailyChallengeApi {

private final DailyChallengeService dailyChallengeService;
private final DailyChallengeFacade dailyChallengeFacade;

@PostMapping
@Override
public ResponseEntity<BaseResponse<?>> orderAddHistoryDailyChallenge(
@PostMapping("/finish")
public ResponseEntity<BaseResponse<EmptyJsonResponse>> orderAddHistoryDailyChallenge(
@UserId final Long userId,
@RequestHeader("OS") final String os,
@RequestBody final AppArrayUsageTimeRequest request
@RequestBody final FinishedDailyChallengeListRequest request
) {
dailyChallengeService.addHistoryDailyChallenge(userId, request.apps(), os);
dailyChallengeFacade.addFinishedDailyChallengeHistory(userId, request, os);
return ResponseEntity
.status(DailyChallengeSuccess.ADD_HISTORY_DAILY_CHALLENGE_SUCCESS.getHttpStatus())
.body(BaseResponse.success(DailyChallengeSuccess.ADD_HISTORY_DAILY_CHALLENGE_SUCCESS, new EmptyJsonResponse()));
.status(DailyChallengeSuccess.SEND_FINISHED_DAILY_CHALLENGE_SUCCESS.getHttpStatus())
.body(BaseResponse.success(DailyChallengeSuccess.SEND_FINISHED_DAILY_CHALLENGE_SUCCESS, new EmptyJsonResponse()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@

import jakarta.persistence.*;
import java.time.LocalDate;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;
import sopt.org.hmh.domain.app.domain.AppWithUsageGoalTime;
import sopt.org.hmh.global.common.domain.BaseTimeEntity;
import sopt.org.hmh.domain.challenge.domain.Challenge;

import java.util.ArrayList;
import java.util.List;

@Entity
@Getter
@NoArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class DailyChallenge extends BaseTimeEntity {

@Id
Expand All @@ -27,23 +27,30 @@ public class DailyChallenge extends BaseTimeEntity {
@JoinColumn(name = "challenge_id")
private Challenge challenge;

private Long goalTime;
@OneToMany(mappedBy = "dailyChallenge", cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<AppWithUsageGoalTime> apps;

@Enumerated(EnumType.STRING)
private Status status;

@OneToMany(mappedBy = "dailyChallenge", cascade = CascadeType.REMOVE, orphanRemoval = true)
private final List<AppWithUsageGoalTime> apps = new ArrayList<>();
private Long userId;

private LocalDate challengeDate;
private Long goalTime;

private Long userId;
private LocalDate challengeDate;

@Builder
public DailyChallenge(Challenge challenge, Long goalTime, Status status) {
DailyChallenge(Challenge challenge, Long userId, Long goalTime, LocalDate challengeDate) {
Assert.notNull(challenge, "Challenge must not be null");
Assert.notNull(userId, "UserId must not be null");
Assert.notNull(goalTime, "GoalTime must not be null");
Assert.notNull(challengeDate, "ChallengeDate must not be null");

this.challenge = challenge;
this.userId = userId;
this.goalTime = goalTime;
this.status = status;
this.challengeDate = challengeDate;
this.status = Status.NONE;
}

public void changeStatus(Status status) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public enum DailyChallengeError implements ErrorBase {

DAILY_CHALLENGE_NOT_FOUND(HttpStatus.NOT_FOUND, "일별 챌린지를 찾을 수 없습니다."),
DAILY_CHALLENGE_YESTERDAY_NOT_FOUND(HttpStatus.NOT_FOUND, "어제의 일별 챌린지를 찾을 수 없습니다."),
DAILY_CHALLENGE_ALREADY_HANDLED(HttpStatus.BAD_REQUEST, "이미 처리된 일별 챌린지입니다.")
DAILY_CHALLENGE_ALREADY_PROCESSED(HttpStatus.BAD_REQUEST, "이미 처리된 일별 챌린지입니다.")
;

private final HttpStatus status;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
@AllArgsConstructor
public enum DailyChallengeSuccess implements SuccessBase {

ADD_HISTORY_DAILY_CHALLENGE_SUCCESS(HttpStatus.OK, "어제의 일별 챌린지 업데이트를 성공하였습니다"),
SEND_FINISHED_DAILY_CHALLENGE_SUCCESS(HttpStatus.OK, "완료된 일별 챌린지 정보 전송을 성공하였습니다"),
MODIFY_DAILY_CHALLENGE_STATUS_FAILURE_SUCCESS(HttpStatus.OK, "오늘의 일별 챌린지 STATUS 실패 처리를 성공하였습니다"),
;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package sopt.org.hmh.domain.dailychallenge.dto.request;

import java.util.List;

public record FinishedDailyChallengeListRequest(
List<FinishedDailyChallengeRequest> finishedDailyChallenges
) {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package sopt.org.hmh.domain.dailychallenge.dto.request;

import java.time.LocalDate;
import java.util.List;
import sopt.org.hmh.domain.app.dto.request.AppUsageTimeRequest;

public record FinishedDailyChallengeRequest(
LocalDate challengeDate,
List<AppUsageTimeRequest> apps
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package sopt.org.hmh.domain.dailychallenge.service;

import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sopt.org.hmh.domain.app.domain.AppWithGoalTime;
import sopt.org.hmh.domain.app.service.AppService;
import sopt.org.hmh.domain.challenge.service.ChallengeService;
import sopt.org.hmh.domain.dailychallenge.domain.DailyChallenge;
import sopt.org.hmh.domain.dailychallenge.dto.request.FinishedDailyChallengeListRequest;
import sopt.org.hmh.domain.user.service.UserService;

@Service
@RequiredArgsConstructor
@Transactional
public class DailyChallengeFacade {

private final DailyChallengeService dailyChallengeService;
private final AppService appService;
private final ChallengeService challengeService;
private final UserService userService;

public void addFinishedDailyChallengeHistory(Long userId, FinishedDailyChallengeListRequest requests, String os) {
requests.finishedDailyChallenges().forEach(request -> {
DailyChallenge dailyChallenge = dailyChallengeService.findByChallengeDateAndUserIdOrThrowException(request.challengeDate(), userId);
dailyChallengeService.changeStatusByCurrentStatus(dailyChallenge);
Long currentChallengeId = userService.getCurrentChallengeIdByUserId(userId);
List<AppWithGoalTime> currentChallengeApps = challengeService.getCurrentChallengeAppWithGoalTimeByChallengeId(currentChallengeId);
appService.addAppForHistory(currentChallengeApps, request.apps(), dailyChallenge, os);
});
}
}
Loading

0 comments on commit 640fc8f

Please sign in to comment.