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

fix: 위치 관련 오류 수정, 리뷰 기능 수정, 외부 API 테스트 작성 #81

Merged
merged 12 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -3,7 +3,7 @@

import com.gamsa.activity.constant.Category;
import com.gamsa.activity.domain.Activity;
import com.gamsa.review.dto.QuestionResponse;
import com.gamsa.review.domain.Question;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -41,7 +41,7 @@ public class ActivityDetailResponse {
private final InstituteDetailResponse institute;
private final DistrictDetailResponse sidoGungu;

public static ActivityDetailResponse from(Activity activity, Map<QuestionResponse, BigDecimal> scores) {
public static ActivityDetailResponse from(Activity activity, Map<Question, BigDecimal> scores) {
return ActivityDetailResponse.builder()
.actId(activity.getActId())
.actTitle(activity.getActTitle())
Expand Down
16 changes: 12 additions & 4 deletions src/main/java/com/gamsa/activity/dto/InstituteDetailResponse.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package com.gamsa.activity.dto;

import com.gamsa.activity.domain.Institute;
import com.gamsa.review.dto.QuestionResponse;
import com.gamsa.review.domain.Question;
import com.gamsa.review.dto.ReviewResponse;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
@Builder
Expand All @@ -20,17 +23,22 @@ public class InstituteDetailResponse {
private final BigDecimal latitude;
private final BigDecimal longitude;
private final String phone;
private final Map<QuestionResponse, BigDecimal> scores;
private final List<ReviewResponse> scores;

public static InstituteDetailResponse from(Institute institute, Map<Question, BigDecimal> scores) {
List<ReviewResponse> reviewResponses = scores.entrySet().stream()
.map(entry -> ReviewResponse.from(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());


public static InstituteDetailResponse from(Institute institute, Map<QuestionResponse, BigDecimal> scores) {
return InstituteDetailResponse.builder()
.instituteId(institute.getInstituteId())
.name(institute.getName())
.location(institute.getLocation())
.latitude(institute.getLatitude())
.longitude(institute.getLongitude())
.phone(institute.getPhone())
.scores(scores)
.scores(reviewResponses)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,10 @@ public class ActivityJpaEntity extends BaseEntity {
@Column(name = "online_possible")
private boolean onlinePossible;

@Column(name = "latitude", precision = 10, scale = 6)
@Column(name = "latitude", precision = 10, scale = 8)
private BigDecimal latitude;

@Column(name = "longitude", precision = 10, scale = 6)
@Column(name = "longitude", precision = 11, scale = 8)
private BigDecimal longitude;

@Column(name = "act_week")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ public class DistrictJpaEntity extends BaseEntity {
@Column(name = "sido_code", nullable = false)
private int sidoCode;

@Column(name = "latitude", precision = 10, scale = 6)
@Column(name = "latitude", precision = 10, scale = 8)
private BigDecimal latitude;

@Column(name = "longitude", precision = 10, scale = 6)
@Column(name = "longitude", precision = 11, scale = 8)
private BigDecimal longitude;

@Column(name = "sido_name", length = 15, nullable = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ public class InstituteJpaEntity extends BaseEntity {
@Column(name = "location", length = 255)
private String location;

@Column(name = "latitude")
@Column(name = "latitude", precision = 10, scale = 8)
private BigDecimal latitude;

@Column(name = "longitude")
@Column(name = "longitude", precision = 11, scale = 8)
private BigDecimal longitude;

@ManyToOne(fetch = FetchType.EAGER)
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/gamsa/activity/service/ActivityService.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.gamsa.activity.dto.ActivitySaveRequest;
import com.gamsa.activity.exception.ActivityException;
import com.gamsa.activity.repository.ActivityRepository;
import com.gamsa.review.domain.Question;
import com.gamsa.review.dto.QuestionResponse;
import com.gamsa.review.service.QuestionService;
import com.gamsa.review.service.ReviewService;
Expand Down Expand Up @@ -55,10 +56,10 @@ public ActivityDetailResponse findById(Long activityId) {
.orElseThrow(() -> new ActivityException(ActivityErrorCode.ACTIVITY_NOT_EXISTS));


Map<QuestionResponse, BigDecimal> scores = new HashMap<>();
Map<Question, BigDecimal> scores = new HashMap<>();
long instituteId = activity.getInstitute().getInstituteId();

questionService.findAllResponse().forEach(question -> {
questionService.findAll().forEach(question -> {
BigDecimal score = reviewService.getAverageScore(instituteId, question.getQuestionId());
scores.put(question, score);
});
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/com/gamsa/dataupdate/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.gamsa.dataupdate;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
5 changes: 0 additions & 5 deletions src/main/java/com/gamsa/dataupdate/DataUpdateErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@ public enum DataUpdateErrorCode {
OPENAPI_NOT_RESPOND(504, "Open API가 응답하지 않습니다."),
OPENAPI_ERROR(504, "Open API의 반환 값을 처리할 수 없습니다."),


// 카카오 API 오류
KAKAOLOCALAPI_NOT_RESPOND(504, "카카오 API가 정상적으로 응답하지 않습니다."),
KAKAOLOCALAPT_ERROR(504, "카카오 API의 반환 값을 처리할 수 없습니다."),

// 내부 처리 오류
INVALID_CSV(500, "주어진 CSV 파일을 처리할 수 없습니다"),
INVALID_FILE_SOURCE(500, "주어진 파일 경로가 올바르지 않습니다.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ public void saveInstitute(String programNo) {
try {
var instituteApiResponse = activityDataUtils.getInstituteApiResponse(programNo);
InstituteSaveRequest saveRequest = instituteApiResponse.toSaveRequest(
districtService.findCoordinates(instituteApiResponse.getSidoGunguCode()));
kakaoLocalUtils.getCoordinateByAddress(instituteApiResponse.getLocation()).orElse(
districtService.findCoordinates(instituteApiResponse.getSidoGunguCode())));
instituteService.save(saveRequest);
} catch (Exception e) {
log.warn("Failed to save institute for program number {}: {}", programNo, e.getMessage());
Expand Down
26 changes: 14 additions & 12 deletions src/main/java/com/gamsa/dataupdate/utils/ActivityDataUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,35 @@
import com.gamsa.activity.dto.InstituteApiResponse;
import com.gamsa.dataupdate.DataUpdateErrorCode;
import com.gamsa.dataupdate.DataUpdateException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class ActivityDataUtils {
@Value(value = "${openapi.key}")
private String openapiKey;

@Value(value = "${openapi.url}")
private String openapiUrl;
private final String openapiUrl = "http://openapi.1365.go.kr/openapi/service/rest/VolunteerPartcptnService/";

@Value(value = "${openapi.volurl}")
private String volUrl;

private final RestTemplate restTemplate = new RestTemplate();
private final RestTemplate restTemplate;

public ActivityDataUtils(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

Expand Down Expand Up @@ -158,8 +160,8 @@ public ActivitySaveRequest getVolunteerDetail(String programNo) {
.actEndTime(item.path("actEndTm").asInt())
.recruitTotalNum(item.path("rcritNmpr").asInt())
.actLocation(item.path("areaAddress1").asText())
.longitude(new BigDecimal(item.path("areaLalo1").asText().split(",")[0]))
.latitude(new BigDecimal(item.path("areaLalo1").asText().split(",")[1]))
.latitude(new BigDecimal(item.path("areaLalo1").asText().split(",")[0]))
.longitude(new BigDecimal(item.path("areaLalo1").asText().split(",")[1]))
.adultPossible(item.path("adultPosblAt").asText("").equals("Y"))
.teenPossible(item.path("yngbgsPosblAt").asText("").equals("Y"))
.groupPossible(item.path("grpPosblAt").asText("").equals("Y")).actWeek(item.path("actWkdy").asInt())
Expand Down
58 changes: 33 additions & 25 deletions src/main/java/com/gamsa/dataupdate/utils/KakaoLocalUtils.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
package com.gamsa.dataupdate.utils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
Expand All @@ -15,21 +10,31 @@
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Component
public class KakaoLocalUtils {

@Value("${kakao.localkey}")
private String kakaoKey;

private final RestTemplate restTemplate = new RestTemplate();
private final RestTemplate restTemplate;

public KakaoLocalUtils(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

public Optional<Map<String, BigDecimal>> getCoordinateByAddress(String address) {
// 요청 URL 생성
String url = UriComponentsBuilder.fromHttpUrl("https://dapi.kakao.com/v2/local/search/address.json")
.queryParam("query", address)
.build()
.toUriString();
.queryParam("query", address)
.build()
.toUriString();

// 헤더 설정
HttpHeaders headers = new HttpHeaders();
Expand All @@ -40,26 +45,29 @@ public Optional<Map<String, BigDecimal>> getCoordinateByAddress(String address)
ResponseEntity<Map> response = restTemplate.exchange(
url, HttpMethod.GET, entity, Map.class);

// 응답 처리
if (response.getStatusCode().is2xxSuccessful()) {
Map<String, Object> result = response.getBody();
if (result != null && result.containsKey("documents")) {
// 첫 번째 결과의 x, y 좌표 반환
var documents = (List<Map<String, Object>>) result.get("documents");
if (!documents.isEmpty()) {
Map<String, Object> firstDoc = documents.getFirst();
BigDecimal x = new BigDecimal(firstDoc.get("x").toString());
BigDecimal y = new BigDecimal(firstDoc.get("y").toString());
try {
// 응답 처리
if (response.getStatusCode().is2xxSuccessful()) {

Map<String, Object> result = response.getBody();
if (result != null && result.containsKey("documents")) {
// 첫 번째 결과의 x, y 좌표 반환
var documents = (List<Map<String, Object>>) result.get("documents");
if (!documents.isEmpty()) {
Map<String, Object> firstDoc = documents.getFirst();
BigDecimal x = new BigDecimal(firstDoc.get("x").toString());
BigDecimal y = new BigDecimal(firstDoc.get("y").toString());

Map<String, BigDecimal> coordinates = new HashMap<>();
coordinates.put("longitude", x);
coordinates.put("latitude", y);
return Optional.of(coordinates);
Map<String, BigDecimal> coordinates = new HashMap<>();
coordinates.put("longitude", x);
coordinates.put("latitude", y);
return Optional.of(coordinates);
}
}
}
} catch (Exception e) {
log.error("API 요청 실패: " + response.getStatusCode() + e.getMessage());
}

log.error("API 요청 실패: " + response.getStatusCode());
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
package com.gamsa.history.dto;

import com.gamsa.activity.dto.ActivityDetailResponse;
import com.gamsa.activity.dto.ActivityFindSliceResponse;
import com.gamsa.history.constant.ActivityStatus;
import com.gamsa.history.domain.History;
import com.gamsa.review.dto.QuestionResponse;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.math.BigDecimal;
import java.util.Map;

@Getter
@Builder
@RequiredArgsConstructor
public class HistoryFindSliceResponse {

private final long historyId;
private final long avatarId;
private final ActivityDetailResponse activity;
private final ActivityFindSliceResponse activity;
private final ActivityStatus activityStatus;
private final boolean reviewed;

public static HistoryFindSliceResponse from(History history, Map<QuestionResponse, BigDecimal> scores) {
public static HistoryFindSliceResponse from(History history) {
return HistoryFindSliceResponse.builder()
.historyId(history.getHistoryId())
.avatarId(history.getAvatar().getAvatarId())
.activityStatus(history.getActivityStatus())
.reviewed(history.isReviewed())
.activity(ActivityDetailResponse.from(history.getActivity(), scores))
.activity(ActivityFindSliceResponse.from(history.getActivity()))
.build();
}
}
20 changes: 1 addition & 19 deletions src/main/java/com/gamsa/history/service/HistoryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,12 @@
import com.gamsa.history.dto.HistoryFindSliceResponse;
import com.gamsa.history.dto.HistorySaveRequest;
import com.gamsa.history.repository.HistoryRepository;
import com.gamsa.review.dto.QuestionResponse;
import com.gamsa.review.service.QuestionService;
import com.gamsa.review.service.ReviewService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;

@RequiredArgsConstructor
Expand All @@ -28,8 +22,6 @@ public class HistoryService {
private final HistoryRepository historyRepository;
private final AvatarRepository avatarRepository;
private final ActivityRepository activityRepository;
private final QuestionService questionService;
private final ReviewService reviewService;

public void save(HistorySaveRequest saveRequest, Long userId) {

Expand All @@ -49,17 +41,7 @@ public Slice<HistoryFindSliceResponse> findSliceByAvatarId(Long userId, Pageable
.findSliceByAvatarId(avatar.getAvatarId(), pageable);
histories.forEach(this::checkDate);

return histories.map(history -> {
Map<QuestionResponse, BigDecimal> scores = new HashMap<>();
long instituteId = history.getActivity().getInstitute().getInstituteId();

questionService.findAllResponse().forEach(question -> {
BigDecimal score = reviewService.getAverageScore(instituteId, question.getQuestionId());
scores.put(question, score);
});

return HistoryFindSliceResponse.from(history, scores);
});
return histories.map(HistoryFindSliceResponse::from);
}

public void delete(long historyId) {
Expand Down
Loading