Skip to content

Commit

Permalink
[Fix] #42 : 충돌 병합
Browse files Browse the repository at this point in the history
  • Loading branch information
its-sky committed Jan 9, 2024
2 parents 0c3d240 + a91005a commit aea1ff0
Show file tree
Hide file tree
Showing 16 changed files with 269 additions and 21 deletions.
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(
Integer 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(
Integer 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 Integer idx;
Expand Down Expand Up @@ -68,7 +68,7 @@ public void modifyIdx(Integer 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 @@ -12,11 +12,14 @@
import org.moonshot.server.domain.keyresult.model.KeyResult;
import org.moonshot.server.domain.keyresult.repository.KeyResultRepository;
import org.moonshot.server.domain.objective.dto.request.ModifyIndexRequestDto;
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.IndexService;
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 @@ -36,6 +39,8 @@ public class KeyResultService implements IndexService {
private final TaskRepository taskRepository;
private final TaskService taskService;
private final UserService userService;
private final LogService logService;
private final LogRepository logRepository;

//TODO
// 여기 모든 로직에 User 관련 기능이 추가된 이후
Expand All @@ -54,8 +59,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);
}
}
}
}
Expand All @@ -77,7 +90,7 @@ public void createKeyResult(KeyResultCreateRequestDto request, Long userId) {
for (int 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 @@ -86,6 +99,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 @@ -94,6 +108,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 @@ -123,6 +138,9 @@ 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) {
Expand Down
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")
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());
}
}

}
Loading

0 comments on commit aea1ff0

Please sign in to comment.