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] 선택한 경로로 출발하기 및 이동 중 관련 기능 구현 #58

Open
wants to merge 28 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
c7cb668
refactor: DTO 패키지 request, response로 분리 #53
codrin2 Feb 6, 2025
72bb349
feat: Plan 생성하기 위한 Request DTO 구현 #53
codrin2 Feb 6, 2025
84b115e
feat: String을 TrafficType으로 변환하는 로직 추가 #53
codrin2 Feb 6, 2025
a962b37
fix: Path 출처 RouteSearchResponseDto에서 PlanSaveRequest로 수정ㅇ #53
codrin2 Feb 6, 2025
b938ff2
feat: INVALID_TRAFFIC_TYPE 에러코드 추가 #53
codrin2 Feb 6, 2025
6ad370c
feat: InvalidTrafficTypeException 예외 추가 #53
codrin2 Feb 6, 2025
0857cb3
refactor: RouteSearchResponseDto 명칭 RouteSearchResponse로 수정 #53
codrin2 Feb 6, 2025
bab288a
feat: Plan 생성하는 static method 구현 #53
codrin2 Feb 6, 2025
dec505b
feat: Path 생성하는 static method 구현 #53
codrin2 Feb 6, 2025
c5509db
remove: Path 혼잡도 column 삭제 #53
codrin2 Feb 6, 2025
50e08a2
feat: Plan 생성 비즈니스 로직 구현 #53
codrin2 Feb 6, 2025
adca4da
feat: Plan 생성 API 구현 #53
codrin2 Feb 6, 2025
bc8c41c
feat: PLAN_NOT_FOUND 예외 구현 #53
codrin2 Feb 6, 2025
35bde55
feat: tokenInterceptor에 /plans/** 루트 추가 #53
codrin2 Feb 7, 2025
2a7f8e9
refactor: TokenInterceptor 줄 간격 조정 #53
codrin2 Feb 7, 2025
6a25688
feat: Path와 Todo 일대다 양방향 관계 추가 #53
codrin2 Feb 7, 2025
5044767
feat: 회원의 최근 이동중 데이터 응답 DTO 구현 #53
codrin2 Feb 7, 2025
b1aaa99
feat: findByPlanWithTodosOrderByPathOrder Querydsl을 통해 구현 #53
codrin2 Feb 7, 2025
6993f3a
feat: 유저의 최근 Plan 관련 데이터 조회 비즈니스 로직 구현 #53
codrin2 Feb 7, 2025
1b8911d
feat: 회원의 상태가 이동중이 아닌 경우 예외 구현 #53
codrin2 Feb 7, 2025
4de1149
feat: TodoType에 진행중 타입 추가 #53
codrin2 Feb 7, 2025
f79b5be
feat: 유저의 최근 Plan 관련 데이터 조회 API 구현 #53
codrin2 Feb 7, 2025
fe53f46
feat: 출발하기 비즈니스 로직에 오늘 할일을 찾아 복사 후 저장 로직 추가 #53
codrin2 Feb 7, 2025
2585ae0
feat: Plan에 OneToMany 관계 paths 추가 #53
codrin2 Feb 7, 2025
ee2e373
feat: 이동 중 취소 비즈니스 로직 구현 #53
codrin2 Feb 7, 2025
ca1c04e
feat: 이동 중 취소 API 구현 #53
codrin2 Feb 7, 2025
9cc43be
feat: PlanRecentResponse DTO에 planId 값 추가 #53
codrin2 Feb 7, 2025
7e82029
Merge branch 'develop' into feat/#53
codrin2 Feb 8, 2025
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 @@ -38,7 +38,6 @@ public void addFormatters(FormatterRegistry registry) {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tokenInterceptor)
.addPathPatterns("/members/**")
.addPathPatterns("/routes/**");
.addPathPatterns("/members/**", "/plans/**", "/routes/**");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public enum ErrorCode {
UNSUPPORTED_SOCIAL_LOGIN(BAD_REQUEST, "지원하지 않는 소셜 로그인 타입입니다."),

// Member
INVALID_MEMBER_STATUS(BAD_REQUEST, "회원의 상태가 %s인 경우 해당 API를 이용할 수 없습니다."),
MEMBER_NOT_FOUND(NOT_FOUND, "회원을 찾을 수 없습니다. memberId : %d"),

// Address
Expand All @@ -40,22 +41,25 @@ public enum ErrorCode {
// Category
CATEGORY_NOT_FOUND(NOT_FOUND, "카테고리를 찾을 수 없습니다. categoryName : %s"),

// Plan
PLAN_NOT_FOUND(NOT_FOUND, "계획을 찾을 수 없습니다. planId : %d"),

// Path
INVALID_TRAFFIC_TYPE(BAD_REQUEST, "지원하지 않는 대중교통 형식입니다. trafficType : %s"),

// Member_Category
MEMBER_CATEGORY_NOT_FOUND(NOT_FOUND, "회원의 카테고리 정보를 찾을 수 없습니다. memberId : %d"),

// Todo
TODO_NOT_FOUND(NOT_FOUND, "해당 할 일이 존재하지 않습니다."),

ALREADY_ADDED_TODO(BAD_REQUEST, "이미 추가된 할 일 입니다."),

TODO_LIMIT_EXCEEDED(BAD_REQUEST, "할 일은 최대 3개까지 추가할 수 있습니다."),

// Schedule
SCHEDULE_NOT_FOUND(NOT_FOUND, "스케줄을 찾을 수 없습니다."),

// External API
NAVER_SERVICE_UNAVAILABLE(SERVICE_UNAVAILABLE, "네이버 API 서버가 장애 상태입니다."),

;

public final HttpStatus httpStatus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
Long memberId = tokenService.validateToken(token);

request.setAttribute("memberId", memberId);

}
return true;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.dubu.backend.plan.api;

import com.dubu.backend.global.domain.SuccessResponse;
import com.dubu.backend.plan.application.PlanService;
import com.dubu.backend.plan.dto.request.PlanSaveRequest;
import com.dubu.backend.plan.dto.response.PlanRecentResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("/plans")
public class PlanController {
private final PlanService planService;

@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public void savePlan(
@RequestAttribute("memberId") Long memberId,
@RequestBody PlanSaveRequest planSaveRequest
) {
planService.savePlan(memberId, planSaveRequest);
}

@GetMapping("/recent")
public SuccessResponse<PlanRecentResponse> getRecentPlan(
@RequestAttribute("memberId") Long memberId
) {
PlanRecentResponse response = planService.findRecentPlan(memberId);

return new SuccessResponse<>(response);
}

@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping
public void deletePlan(
@RequestAttribute("memberId") Long memberId,
@RequestParam("planId") Long planId
){
planService.removePlan(memberId, planId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import com.dubu.backend.global.domain.SuccessResponse;
import com.dubu.backend.plan.application.RouteService;
import com.dubu.backend.plan.dto.RouteSearchResponseDto;
import com.dubu.backend.plan.dto.response.RouteSearchResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

Expand All @@ -16,14 +16,14 @@ public class RouteController {
private final RouteService routeService;

@GetMapping("/search")
public SuccessResponse<List<RouteSearchResponseDto>> routeSearch(
public SuccessResponse<List<RouteSearchResponse>> routeSearch(
@RequestAttribute("memberId") Long memberId,
@RequestParam("startX") Double startX,
@RequestParam("startY") Double startY,
@RequestParam("endX") Double endX,
@RequestParam("endY") Double endY
) {
List<RouteSearchResponseDto> response = routeService.getRoutesByStartAndDestination(memberId, startX, startY, endX, endY);
List<RouteSearchResponse> response = routeService.getRoutesByStartAndDestination(memberId, startX, startY, endX, endY);

return new SuccessResponse<>(response);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.dubu.backend.plan.application;

import com.dubu.backend.member.domain.Member;
import com.dubu.backend.member.domain.enums.Status;
import com.dubu.backend.member.exception.MemberNotFoundException;
import com.dubu.backend.member.infra.repository.MemberRepository;
import com.dubu.backend.plan.domain.Path;
import com.dubu.backend.plan.domain.Plan;
import com.dubu.backend.plan.dto.request.PlanSaveRequest;
import com.dubu.backend.plan.dto.response.PlanRecentResponse;
import com.dubu.backend.plan.exception.InvalidMemberStatusException;
import com.dubu.backend.plan.exception.PlanNotFoundException;
import com.dubu.backend.plan.infra.repository.PathRepository;
import com.dubu.backend.plan.infra.repository.PlanRepository;
import com.dubu.backend.todo.entity.Schedule;
import com.dubu.backend.todo.entity.Todo;
import com.dubu.backend.todo.exception.ScheduleNotFoundException;
import com.dubu.backend.todo.repository.ScheduleRepository;
import com.dubu.backend.todo.repository.TodoRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

@Service
@RequiredArgsConstructor
public class PlanService {
private final MemberRepository memberRepository;
private final PlanRepository planRepository;
private final PathRepository pathRepository;
private final ScheduleRepository scheduleRepository;
private final TodoRepository todoRepository;

@Transactional
public void savePlan(Long memberId, PlanSaveRequest planSaveRequest) {
Member currentMember = memberRepository.findById(memberId)
.orElseThrow(() -> new MemberNotFoundException(memberId));

if (currentMember.getStatus() != Status.STOP) {
throw new InvalidMemberStatusException(currentMember.getStatus().name());
}

Plan newPlan = Plan.createPlan(currentMember, planSaveRequest.totalSectionTime());
planRepository.save(newPlan);

List<Path> paths = IntStream.range(0, planSaveRequest.paths().size())
.mapToObj(index -> Path.createPath(newPlan, planSaveRequest.paths().get(index), index))
.toList();
pathRepository.saveAll(paths);

Schedule schedule = scheduleRepository.findScheduleByMemberAndDate(currentMember, LocalDate.now())
.orElseThrow(() -> new ScheduleNotFoundException());

List<Todo> existingTodos = schedule.getTodos();

List<Todo> newTodos = new ArrayList<>();

for (int i = 0; i < existingTodos.size(); i++) {
Todo original = existingTodos.get(i);
// round-robin으로 Path 할당
Path assignedPath = paths.get(i % paths.size());
Todo clonedTodo = Todo.copyOf(original, assignedPath);

newTodos.add(clonedTodo);
}
todoRepository.saveAll(newTodos);
Copy link
Collaborator

Choose a reason for hiding this comment

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

todo 를 하나씩 저장하는 것이 아닌 한 번에 저장하는 것이 좋았습니다!!

currentMember.updateStatus(Status.MOVE);
}

@Transactional(readOnly = true)
public PlanRecentResponse findRecentPlan(Long memberId) {
memberRepository.findById(memberId)
.orElseThrow(() -> new MemberNotFoundException(memberId));

Plan recentPlan = planRepository.findTopByMemberIdOrderByCreatedAtDesc(memberId)
.orElseThrow(() -> new PlanNotFoundException());

List<Path> paths = pathRepository.findByPlanWithTodosOrderByPathOrder(recentPlan);

return PlanRecentResponse.of(recentPlan, paths);
}

@Transactional
public void removePlan(Long memberId, Long planId) {
memberRepository.findById(memberId)
.orElseThrow(() -> new MemberNotFoundException(memberId));

planRepository.deleteById(planId);
Copy link
Collaborator

Choose a reason for hiding this comment

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

deleteById 로 해당 plan 의 존재 여부를 확인하지 않고 바로 삭제하는 것이 좋네요!! 배워갑니다!!

Copy link
Member Author

Choose a reason for hiding this comment

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

토끼친구는 존재 여부를 확인하고 삭제하라고 하는데 현원님은 어떻게 생각하시나요?
저는 존재 여부를 확인하지 않은 이유가 Plan이 실제로 있었든 없었든 결과적으로는 삭제되는 것이 동일하다고 생각해서 존재 여부를 확인하지 않았습니다!

}
Comment on lines +87 to +93
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enforce plan ownership checks when deleting a plan.
The current logic only verifies that the member exists but not that the plan belongs to the member. This could allow a member to delete another user’s plan unintentionally.

Below is an example code diff to ensure the plan is bound to the correct member:

 @Transactional
 public void removePlan(Long memberId, Long planId) {
    memberRepository.findById(memberId)
        .orElseThrow(() -> new MemberNotFoundException(memberId));

+   Plan plan = planRepository.findById(planId)
+       .orElseThrow(() -> new PlanNotFoundException());
+   if (!plan.getMember().getId().equals(memberId)) {
+       throw new PlanNotFoundException(); // or any relevant unauthorized exception
+   }

-   planRepository.deleteById(planId);
+   planRepository.delete(plan);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Transactional
public void removePlan(Long memberId, Long planId) {
memberRepository.findById(memberId)
.orElseThrow(() -> new MemberNotFoundException(memberId));
planRepository.deleteById(planId);
}
@Transactional
public void removePlan(Long memberId, Long planId) {
memberRepository.findById(memberId)
.orElseThrow(() -> new MemberNotFoundException(memberId));
Plan plan = planRepository.findById(planId)
.orElseThrow(() -> new PlanNotFoundException());
if (!plan.getMember().getId().equals(memberId)) {
throw new PlanNotFoundException(); // or any relevant unauthorized exception
}
planRepository.delete(plan);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,20 @@
import com.dubu.backend.plan.domain.Path;
import com.dubu.backend.plan.domain.Plan;
import com.dubu.backend.plan.domain.vo.PathIdentifier;
import com.dubu.backend.plan.dto.OdsayRouteApiResponse;
import com.dubu.backend.plan.dto.RouteSearchResponseDto;
import com.dubu.backend.plan.dto.response.OdsayRouteApiResponse;
import com.dubu.backend.plan.dto.response.RouteSearchResponse;
import com.dubu.backend.plan.infra.client.OdsayApiClient;
import com.dubu.backend.plan.infra.repository.PathRepository;
import com.dubu.backend.plan.infra.repository.PlanRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class RouteService {
private final OdsayApiClient odsayApiClient;
Expand All @@ -30,18 +32,18 @@ public class RouteService {
* Route = Path
* Path = SubPath
*/
public List<RouteSearchResponseDto> getRoutesByStartAndDestination(Long memberId, Double startX, Double startY, Double endX, Double endY) {
public List<RouteSearchResponse> getRoutesByStartAndDestination(Long memberId, Double startX, Double startY, Double endX, Double endY) {
memberRepository.findById(memberId)
.orElseThrow(() -> new MemberNotFoundException(memberId));

List<PathIdentifier> recentlyUsedRoute = loadRecentlyUsedRoute(memberId);

OdsayRouteApiResponse odsayRouteApiResponse = odsayApiClient.searchPublicTransportRoute(startX, startY, endX, endY);

List<RouteSearchResponseDto> response = new ArrayList<>();
List<RouteSearchResponse> response = new ArrayList<>();
for (OdsayRouteApiResponse.Path apiPath : odsayRouteApiResponse.result().path()) {
boolean isRecentlyUsed = isSameAsRecentlyUsedRoute(apiPath, recentlyUsedRoute);
RouteSearchResponseDto routeDto = convertApiPathToRoute(apiPath, isRecentlyUsed);
RouteSearchResponse routeDto = convertApiPathToRoute(apiPath, isRecentlyUsed);
response.add(routeDto);
}

Expand Down Expand Up @@ -107,28 +109,28 @@ private List<PathIdentifier> extractRouteKeys(OdsayRouteApiResponse.Path apiPath
}


private RouteSearchResponseDto convertApiPathToRoute(OdsayRouteApiResponse.Path apiPath, boolean isRecentlyUsed) {
private RouteSearchResponse convertApiPathToRoute(OdsayRouteApiResponse.Path apiPath, boolean isRecentlyUsed) {
OdsayRouteApiResponse.Info info = apiPath.info();

int totalTime = info.totalTime();
int totalSectionTime = 0;

List<RouteSearchResponseDto.Path> pathDtoList = new ArrayList<>();
List<RouteSearchResponse.Path> pathDtoList = new ArrayList<>();

// SubPath(=ODsay) → Path(=두리번)Dto 변환
for (OdsayRouteApiResponse.SubPath subPath : apiPath.subPath()) {
RouteSearchResponseDto.Path dtoPath = convertApiSubPathToPathDto(subPath);
RouteSearchResponse.Path dtoPath = convertApiSubPathToPathDto(subPath);

if ("BUS".equals(dtoPath.trafficType()) || "SUBWAY".equals(dtoPath.trafficType())) {
totalSectionTime += dtoPath.sectionTime();
}
pathDtoList.add(dtoPath);
}

return new RouteSearchResponseDto(isRecentlyUsed, totalTime, totalSectionTime, pathDtoList);
return new RouteSearchResponse(isRecentlyUsed, totalTime, totalSectionTime, pathDtoList);
}

private RouteSearchResponseDto.Path convertApiSubPathToPathDto(OdsayRouteApiResponse.SubPath subPath) {
private RouteSearchResponse.Path convertApiSubPathToPathDto(OdsayRouteApiResponse.SubPath subPath) {
int tType = subPath.trafficType();
String trafficType = switch (tType) {
case 1 -> "SUBWAY";
Expand Down Expand Up @@ -159,7 +161,7 @@ private RouteSearchResponseDto.Path convertApiSubPathToPathDto(OdsayRouteApiResp
}
}

return new RouteSearchResponseDto.Path(
return new RouteSearchResponse.Path(
trafficType,
subPath.sectionTime(),
subwayName,
Expand Down
24 changes: 19 additions & 5 deletions backend/src/main/java/com/dubu/backend/plan/domain/Path.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package com.dubu.backend.plan.domain;

import com.dubu.backend.global.domain.BaseTimeEntity;
import com.dubu.backend.plan.domain.enums.CongestionLevel;
import com.dubu.backend.plan.domain.enums.TrafficType;
import com.dubu.backend.plan.dto.request.PlanSaveRequest;
import com.dubu.backend.todo.entity.Todo;
import jakarta.persistence.*;
import lombok.*;

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

@Entity
@Getter
@Builder
Expand All @@ -24,6 +28,9 @@ public class Path extends BaseTimeEntity {
@JoinColumn(name = "plan_id", nullable = false)
private Plan plan;

@OneToMany(mappedBy = "path", cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<Todo> todos = new ArrayList<>();

@Column(nullable = false)
@Enumerated(EnumType.STRING)
private TrafficType trafficType;
Expand All @@ -37,10 +44,17 @@ public class Path extends BaseTimeEntity {
@Column(nullable = false, columnDefinition = "SMALLINT")
private Integer sectionTime;

@Column(nullable = false)
@Enumerated(EnumType.STRING)
private CongestionLevel congestionLevel;

@Column(nullable = false, columnDefinition = "SMALLINT")
private Integer pathOrder;

public static Path createPath(Plan plan, PlanSaveRequest.Path pathRequest, int pathOrder) {
return Path.builder()
.plan(plan)
.trafficType(TrafficType.from(pathRequest.trafficType()))
.startName(pathRequest.startName())
.endName(pathRequest.endName())
.sectionTime(pathRequest.sectionTime())
.pathOrder(pathOrder)
.build();
}
}
13 changes: 13 additions & 0 deletions backend/src/main/java/com/dubu/backend/plan/domain/Plan.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import jakarta.persistence.*;
import lombok.*;

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

@Entity
@Getter
@Builder
Expand All @@ -20,6 +23,16 @@ public class Plan extends BaseTimeEntity {
@JoinColumn(name = "member_id", nullable = false)
private Member member;

@OneToMany(mappedBy = "plan", cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<Path> paths = new ArrayList<>();

@Column(nullable = false, columnDefinition = "SMALLINT")
private Integer totalTime;

public static Plan createPlan(Member member, Integer totalTime) {
return Plan.builder()
.member(member)
.totalTime(totalTime)
.build();
}
}
Loading