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] #39 - Log 생성 API 구현 #43

Merged
merged 23 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2b12dd1
[Feat] #39 - OKR 생성 Principal 추가
0lynny Jan 9, 2024
a2f133c
[Feat] #39 - LogCreateRequestDto 추가
0lynny Jan 9, 2024
3114349
[Feat] #39 - LogRepository 추가
0lynny Jan 9, 2024
2a5faac
[Feat] #39 - Log 생성 API 구현
0lynny Jan 9, 2024
302ae6f
[Feat] #39 - Log 생성 SuccessType 추가
0lynny Jan 9, 2024
358bc0a
[Feat] #39 - KR 수정 시 Log 생성 기능 구현
0lynny Jan 9, 2024
849aae7
[Feat] #39 - Target 범위에 따른 Entity 수정
0lynny Jan 9, 2024
a3f84fa
[Chore] #39 - 타입 변경으로 인한 관련 코드 수정
0lynny Jan 9, 2024
71881c8
[Chore] #39 - 타입 변경에 따른 코드 수정
0lynny Jan 9, 2024
4299cf8
[Feat] #39 - Log prevNum Default 설정
0lynny Jan 9, 2024
680318c
[Chore] #39 - LogCreateRequestDto 변경
0lynny Jan 9, 2024
dce1bbe
[Feat] #39 - 메소드 분리
0lynny Jan 9, 2024
a575330
[Fix] #39 - merge 후 confilct 해결
0lynny Jan 9, 2024
dd338d4
[Feat] #28 - KR 삭제 시 Log 삭제 기능 구현
0lynny Jan 9, 2024
9895da1
[Feat] #39 - Log 진척정도 직전값 기능 구현
0lynny Jan 9, 2024
438dbce
[Feat] #39 - 예외처리 추가
0lynny Jan 9, 2024
9647200
[Del] #39 - 사용하지 않는 import문 삭제
0lynny Jan 9, 2024
e0a0cc8
Merge branch 'develop' into feature/#39
0lynny Jan 9, 2024
8cbfa38
Merge branch 'feature/#39' of https://github.com/MOONSHOT-Team/MOONSH…
0lynny Jan 9, 2024
af316b8
[Feat] #39 - 수치 Limit 관련 어노테이션 추가
0lynny Jan 9, 2024
0296c9f
[Feat] #39 - ValidLimitValue 어노테이션 적용
0lynny Jan 9, 2024
02e1f96
[Fix] #39 - 오탈자 수정
0lynny Jan 9, 2024
91bf6df
[Fix] #39 - 코드리뷰 반영
0lynny Jan 9, 2024
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 @@ -4,6 +4,7 @@
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import org.hibernate.validator.constraints.Range;
import org.moonshot.server.global.common.model.validator.ValidLimitValue;
import org.moonshot.server.global.common.model.validator.ValidTargetNumber;
import org.springframework.format.annotation.DateTimeFormat;

Expand All @@ -23,7 +24,8 @@ public record KeyResultCreateRequestDto(
Short idx,
@NotNull(message = "KR 목표 수치를 입력해주세요.")
@ValidTargetNumber
Integer target,
@ValidLimitValue
Long target,
@NotNull(message = "KR 목표 수치의 단위를 입력해주세요.")
String metric,
@NotNull(message = "KR 목표의 이전 수식을 입력해주세요.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.List;
import org.moonshot.server.domain.task.dto.request.TaskCreateRequestDto;
import org.hibernate.validator.constraints.Range;
import org.moonshot.server.global.common.model.validator.ValidLimitValue;
import org.moonshot.server.global.common.model.validator.ValidTargetNumber;
import org.springframework.format.annotation.DateTimeFormat;

Expand All @@ -24,7 +25,8 @@ public record KeyResultCreateRequestInfoDto(
Short idx,
@NotNull(message = "KR 목표 수치를 입력해주세요.")
@ValidTargetNumber
Integer target,
@ValidLimitValue
Long target,
@NotNull(message = "KR 목표 수치의 단위를 입력해주세요.")
String metric,
@NotNull(message = "KR 목표의 이전 수식을 입력해주세요.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import org.moonshot.server.domain.keyresult.model.KRState;
import org.moonshot.server.global.common.model.validator.ValidLimitValue;
import org.moonshot.server.global.common.model.validator.ValidTargetNumber;
import org.springframework.format.annotation.DateTimeFormat;

Expand All @@ -17,7 +18,10 @@ public record KeyResultModifyRequestDto(
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
LocalDateTime expireAt,
@ValidTargetNumber
Integer target,
KRState state
@ValidLimitValue
Long target,
KRState state,
@Size(min = 1, max = 100, message = "본문은 100자 이하여야 합니다.")
String logContent
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class KeyResult {
private Period period;

@Column(nullable = false)
private Integer target;
private Long target;

@Column(nullable = false)
private Short idx;
Expand Down Expand Up @@ -64,7 +64,7 @@ public void modifyIdx(Short idx) {
this.idx = idx;
}

public void modifyTarget(Integer target) {
public void modifyTarget(Long target) {
this.target = target;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@
import org.moonshot.server.domain.keyresult.exception.KeyResultNumberExceededException;
import org.moonshot.server.domain.keyresult.model.KeyResult;
import org.moonshot.server.domain.keyresult.repository.KeyResultRepository;
import org.moonshot.server.domain.log.repository.LogRepository;
import org.moonshot.server.domain.log.service.LogService;
import org.moonshot.server.domain.objective.exception.ObjectiveNotFoundException;
import org.moonshot.server.domain.objective.model.Objective;
import org.moonshot.server.domain.objective.repository.ObjectiveRepository;
import org.moonshot.server.domain.task.dto.request.TaskCreateRequestDto;
import org.moonshot.server.domain.task.model.Task;
import org.moonshot.server.domain.task.repository.TaskRepository;
import org.moonshot.server.domain.task.service.TaskService;
import org.moonshot.server.domain.user.service.UserService;
Expand All @@ -34,6 +37,8 @@ public class KeyResultService {
private final TaskRepository taskRepository;
private final TaskService taskService;
private final UserService userService;
private final LogService logService;
private final LogRepository logRepository;

//TODO
// 여기 모든 로직에 User 관련 기능이 추가된 이후
Expand All @@ -52,8 +57,16 @@ public void createInitKRWithObjective(Objective objective, List<KeyResultCreateR
.descriptionAfter(dto.descriptionAfter())
.objective(objective)
.build());
for (TaskCreateRequestDto taskDto: dto.taskList()) {
taskService.saveTask(keyResult, taskDto);
logService.createKRLog(dto, keyResult.getId());
if (dto.taskList() != null) {
taskRepository.saveAll(dto.taskList().stream().map((task) -> Task.builder()
.title(task.title())
.idx(task.idx())
.keyResult(keyResult)
.build()).toList());
for (TaskCreateRequestDto taskDto : dto.taskList()) {
taskService.saveTask(keyResult, taskDto);
}
}
Copy link
Member

Choose a reason for hiding this comment

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

p2;

for (TaskCreateRequestDto taskDto : dto.taskList()) {
    taskService.saveTask(keyResult, taskDto);
}

이거 남기고 if(dto.taskList() !=null) 내 로직 지워야할것 같습니다!

}
}
Expand All @@ -75,7 +88,7 @@ public void createKeyResult(KeyResultCreateRequestDto request, Long userId) {
for (short i = request.idx(); i < krList.size(); i++) {
krList.get(i).incrementIdx();
}
keyResultRepository.save(KeyResult.builder()
KeyResult keyResult = keyResultRepository.save(KeyResult.builder()
.objective(objective)
.title(request.title())
.period(Period.of(request.startAt(), request.expireAt()))
Expand All @@ -84,6 +97,7 @@ public void createKeyResult(KeyResultCreateRequestDto request, Long userId) {
.metric(request.metric())
.descriptionBefore(request.descriptionBefore())
.descriptionAfter(request.descriptionAfter()).build());
logService.createKRLog(request, keyResult.getId());
}

@Transactional
Expand All @@ -92,6 +106,7 @@ public void deleteKeyResult(Long keyResultId, Long userId) {
.orElseThrow(KeyResultNotFoundException::new);
userService.validateUserAuthorization(keyResult.getObjective().getUser(), userId);

logRepository.deleteAllInBatch(logRepository.findAllByKeyResult(keyResult));
taskRepository.deleteAllInBatch(taskRepository.findAllByKeyResult(keyResult));
keyResultRepository.delete(keyResult);
}
Expand Down Expand Up @@ -121,11 +136,15 @@ public void modifyKeyResult(KeyResultModifyRequestDto request, Long userId) {
keyResult.modifyPeriod(Period.of(newStartAt, newExpireAt));
}
if (request.target() != null) {
if (request.logContent() != null) {
logService.createUpdateLog(request, keyResult.getId());
}
keyResult.modifyTarget(request.target());
}
if (request.state() != null) {
keyResult.modifyState(request.state());
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package org.moonshot.server.domain.log.controller;

import lombok.RequiredArgsConstructor;
import org.moonshot.server.domain.log.dto.request.LogCreateRequestDto;
import org.moonshot.server.domain.log.service.LogService;
import org.moonshot.server.global.auth.jwt.JwtTokenProvider;
import org.moonshot.server.global.common.response.ApiResponse;
import org.moonshot.server.global.common.response.SuccessType;
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.security.Principal;

@RestController
@RequiredArgsConstructor
@RequestMapping("/v1/log")
public class LogController {

private final LogService logService;

@PostMapping
public ApiResponse<?> create(Principal principal, @RequestBody LogCreateRequestDto logCreateRequestDto) {
logService.createRecordLog(JwtTokenProvider.getUserIdFromPrincipal(principal), logCreateRequestDto);
return ApiResponse.success(SuccessType.POST_LOG_SUCCESS);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.moonshot.server.domain.log.dto.request;

import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.moonshot.server.global.common.model.validator.ValidLimitValue;

public record LogCreateRequestDto(
Long keyResultId,

@NotNull(message = "Log의 수치를 입력해주세요.")
@ValidLimitValue
long logNum,

@NotNull(message = "Log의 체크인 본문을 입력해주세요.")
@Size(min = 1, max = 100, message = "본문은 100자 이하여야 합니다.")
String logContent
) {
}
21 changes: 18 additions & 3 deletions src/main/java/org/moonshot/server/domain/log/model/Log.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.DynamicInsert;
import org.moonshot.server.domain.keyresult.model.KeyResult;
import org.moonshot.server.domain.user.model.SocialPlatform;
import org.moonshot.server.domain.user.model.User;

import java.time.LocalDateTime;

@Entity
@Getter
@Builder
@DynamicInsert
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class Log {
Expand All @@ -26,11 +30,12 @@ public class Log {
@Column(nullable = false)
private LogState state;

@ColumnDefault("-1")
private int prevNum;
@Builder.Default
@Column(columnDefinition = "bigint default -1")
private long prevNum = -1;

@Column(nullable = false)
private int currNum;
private long currNum;

@Column(nullable = false)
private String content;
Expand All @@ -39,4 +44,14 @@ public class Log {
@JoinColumn(name = "key_result_id")
private KeyResult keyResult;

public static Log of(LocalDateTime date, LogState state, int prevNum, int currNum, String content, KeyResult keyResult) {
return Log.builder()
.date(date)
.state(state)
.prevNum(prevNum)
.currNum(currNum)
.keyResult(keyResult)
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.moonshot.server.domain.log.repository;

import org.moonshot.server.domain.keyresult.model.KeyResult;
import org.moonshot.server.domain.log.model.Log;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface LogRepository extends JpaRepository<Log, Long> {

List<Log> findAllByKeyResult(KeyResult keyResult);

@Query("select l FROM Log l JOIN FETCH l.keyResult k WHERE l.keyResult.id = :keyResultId ORDER BY l.id DESC LIMIT 1")
Copy link
Member

Choose a reason for hiding this comment

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

칭찬 스티커 0.5개 붙여드리겠습니다~
(스티커 반을 자르며)

List<Log> findLatestLogByKeyResultId(@Param("keyResultId") Long keyResultId);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package org.moonshot.server.domain.log.service;

import lombok.RequiredArgsConstructor;
import org.moonshot.server.domain.keyresult.dto.request.KeyResultCreateRequestDto;
import org.moonshot.server.domain.keyresult.dto.request.KeyResultCreateRequestInfoDto;
import org.moonshot.server.domain.keyresult.dto.request.KeyResultModifyRequestDto;
import org.moonshot.server.domain.keyresult.exception.KeyResultNotFoundException;
import org.moonshot.server.domain.keyresult.model.KeyResult;
import org.moonshot.server.domain.keyresult.repository.KeyResultRepository;
import org.moonshot.server.domain.log.dto.request.LogCreateRequestDto;
import org.moonshot.server.domain.log.model.Log;
import org.moonshot.server.domain.log.model.LogState;
import org.moonshot.server.domain.log.repository.LogRepository;
import org.moonshot.server.domain.user.exception.UserNotFoundException;
import org.moonshot.server.domain.user.model.User;
import org.moonshot.server.domain.user.repository.UserRepository;
import org.moonshot.server.global.auth.exception.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class LogService {

private final UserRepository userRepository;
private final KeyResultRepository keyResultRepository;
private final LogRepository logRepository;

@Transactional
public void createRecordLog(Long userId, LogCreateRequestDto request) {
User user = userRepository.findById(userId)
.orElseThrow(UserNotFoundException::new);
KeyResult keyResult = keyResultRepository.findById(request.keyResultId())
.orElseThrow(KeyResultNotFoundException::new);
if (!keyResult.getObjective().getUser().getId().equals(userId)) {
throw new AccessDeniedException();
}
List<Log> prevLog = logRepository.findLatestLogByKeyResultId(request.keyResultId());
long prevNum = -1;
if (!prevLog.isEmpty()) {
prevNum = prevLog.get(0).getCurrNum();
}
logRepository.save(Log.builder()
.date(LocalDateTime.now())
.state(LogState.RECORD)
.currNum(request.logNum())
.prevNum(prevNum)
.content(request.logContent())
.keyResult(keyResult)
.build());
}

@Transactional
public void createUpdateLog(KeyResultModifyRequestDto request, Long keyResultId) {
KeyResult keyResult = keyResultRepository.findById(keyResultId)
.orElseThrow(KeyResultNotFoundException::new);

logRepository.save(Log.builder()
.date(LocalDateTime.now())
.state(LogState.UPDATE)
.currNum(request.target())
.prevNum(keyResult.getTarget())
.content(request.logContent())
.keyResult(keyResult)
.build());
}

@Transactional
public void createKRLog(Object request, Long keyResultId) {
KeyResult keyResult = keyResultRepository.findById(keyResultId)
.orElseThrow(KeyResultNotFoundException::new);

if (request instanceof KeyResultCreateRequestInfoDto) {
KeyResultCreateRequestInfoDto dto = (KeyResultCreateRequestInfoDto) request;
logRepository.save(Log.builder()
.date(LocalDateTime.now())
.state(LogState.CREATE)
.currNum(dto.target())
.content("")
.keyResult(keyResult)
.build());
}
if (request instanceof KeyResultCreateRequestDto) {
KeyResultCreateRequestDto dto = (KeyResultCreateRequestDto) request;
logRepository.save(Log.builder()
.date(LocalDateTime.now())
.state(LogState.CREATE)
.currNum(dto.target())
.content("")
.keyResult(keyResult)
.build());
}
}
Copy link
Member

Choose a reason for hiding this comment

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

p5;
킵하고 나중에 좋은 설계가 있으면 같이 생각해보면 좋을거 같아용


}
Loading