Skip to content

Commit

Permalink
feat: 서버에서 충전소 정보들을 필터링 하는 기능을 만든다 (#218)
Browse files Browse the repository at this point in the history
* feat: 필터링 기능 추가

* test: 필터링 기능 테스트 및 기존 코드 리팩토링 진행

* feat: List<Station>을 관리하는 객체 생성

* test: List<Station>을 관리하는 객체 테스트

* refactor: getValue()에서 다른 부분과 겹치지 않기 위해서 따로 getter 재정의

* feat: 인덱스 적용 및 효율적인 연산을 위해서 fetch join 쿼리에서 BETWEEN 연산자 제거 및 범위 쿼리 사용

* refactor: 불필요한 인덱스 제거

* refactor: 코드 컨벤션 정리 및 일부 리팩토링 진행

* refactor: 에러 방지를 위해 fixture의 날짜를 수동으로 설정

* refactor: 네이밍 및 메서드 구조 변경

* refactor: 네이밍 및 메서드 구조 변경

* refactor: 테스트 통합화

* refactor: 데이터를 가져올 때 INNER JOIN으로 가져와서 null인 값들은 제외하도록 변경

* refactor: 메서드 분리

* refactor: 값을 복사하고 반환하도록 변경
  • Loading branch information
sosow0212 committed Jul 31, 2023
1 parent c1dfa95 commit 31fbd19
Show file tree
Hide file tree
Showing 13 changed files with 362 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.carffeine.carffeine.station.controller.station.dto.StationSpecificResponse;
import com.carffeine.carffeine.station.controller.station.dto.StationsSimpleResponse;
import com.carffeine.carffeine.station.domain.charger.ChargerType;
import com.carffeine.carffeine.station.domain.station.Station;
import com.carffeine.carffeine.station.service.station.StationService;
import com.carffeine.carffeine.station.service.station.dto.CoordinateRequest;
Expand All @@ -10,8 +11,10 @@
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

@RequiredArgsConstructor
Expand All @@ -22,12 +25,16 @@ public class StationController {
private final StationService stationService;

@GetMapping("/stations")
public ResponseEntity<StationsSimpleResponse> getStations(CoordinateRequest request) {
List<Station> stations = stationService.findByCoordinate(request);
public ResponseEntity<StationsSimpleResponse> getStations(CoordinateRequest request,
@RequestParam(required = false, defaultValue = "") List<String> companyNames,
@RequestParam(required = false, defaultValue = "") List<ChargerType> chargerTypes,
@RequestParam(required = false, defaultValue = "") List<BigDecimal> capacities) {
List<Station> stations = stationService.findByCoordinate(request, companyNames, chargerTypes, capacities);
StationsSimpleResponse chargerStationsSimpleResponse = StationsSimpleResponse.from(stations);
return ResponseEntity.ok(chargerStationsSimpleResponse);
}


@GetMapping("/stations/{stationId}")
public ResponseEntity<StationSpecificResponse> getStationById(@PathVariable String stationId) {
Station station = stationService.findStationById(stationId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
import java.time.LocalDateTime;

@ToString
Expand All @@ -23,7 +22,6 @@
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@IdClass(ChargerId.class)
@Entity
@Table(name = "charger_status")
public class ChargerStatus {

@Id
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.carffeine.carffeine.station.domain.station;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.math.BigDecimal;

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public class Coordinate {

private final Latitude minLatitude;
private final Latitude maxLatitude;
private final Longitude minLongitude;
private final Longitude maxLongitude;

public static Coordinate of(BigDecimal latitude,
BigDecimal latitudeDelta,
BigDecimal longitude,
BigDecimal longitudeDelta) {
Latitude originLatitude = Latitude.from(latitude);
Latitude minLatitude = originLatitude.calculateMinLatitudeByDelta(latitudeDelta);
Latitude maxLatitude = originLatitude.calculateMaxLatitudeByDelta(latitudeDelta);

Longitude originLongitude = Longitude.from(longitude);
Longitude minLongitude = originLongitude.calculateMinLongitudeByDelta(longitudeDelta);
Longitude maxLongitude = originLongitude.calculateMaxLongitudeByDelta(longitudeDelta);

return new Coordinate(minLatitude, maxLatitude, minLongitude, maxLongitude);
}

public BigDecimal minLatitudeValue() {
return minLatitude.getValue();
}

public BigDecimal maxLatitudeValue() {
return maxLatitude.getValue();
}

public BigDecimal minLongitudeValue() {
return minLongitude.getValue();
}

public BigDecimal maxLongitudeValue() {
return maxLongitude.getValue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.ArrayList;
Expand All @@ -24,7 +25,7 @@
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@EqualsAndHashCode(of = "stationId")
@Table(name = "charge_station")
@Table(name = "charge_station", indexes = @Index(name = "idx_station_coordination", columnList = "latitude, longitude, stationId"))
public class Station {

@Id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;

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

Expand All @@ -14,6 +16,16 @@ public interface StationRepository extends Repository<Station, Long> {
@EntityGraph(attributePaths = {"chargers", "chargers.chargerStatus"})
List<Station> findAllByLatitudeBetweenAndLongitudeBetween(Latitude minLatitude, Latitude maxLatitude, Longitude minLongitude, Longitude maxLongitude);

@Query("SELECT DISTINCT s FROM Station s " +
"INNER JOIN FETCH s.chargers c " +
"INNER JOIN FETCH c.chargerStatus " +
"WHERE s.latitude.value >= :minLatitude AND s.latitude.value <= :maxLatitude " +
"AND s.longitude.value >= :minLongitude AND s.longitude.value <= :maxLongitude")
List<Station> findAllFetchByLatitudeBetweenAndLongitudeBetween(@Param("minLatitude") BigDecimal minLatitude,
@Param("maxLatitude") BigDecimal maxLatitude,
@Param("minLongitude") BigDecimal minLongitude,
@Param("maxLongitude") BigDecimal maxLongitude);

Optional<Station> findChargeStationByStationId(String stationId);

@Query("SELECT DISTINCT s FROM Station s JOIN FETCH s.chargers")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.carffeine.carffeine.station.domain.station;

import com.carffeine.carffeine.station.domain.charger.ChargerType;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Stations {

private final List<Station> stations;

private Stations(List<Station> stations) {
this.stations = new ArrayList<>(stations);
}

public static Stations from(List<Station> stations) {
return new Stations(stations);
}

private static void filterByCompanyNames(List<Station> stations, List<String> companyNames) {
if (!companyNames.isEmpty()) {
stations.removeIf(station -> !companyNames.contains(station.getCompanyName()));
}
}

public List<Station> findFilteredStations(List<String> companyNames,
List<ChargerType> chargerTypes,
List<BigDecimal> capacities) {
List<Station> stations = new ArrayList<>(this.stations);
filterByCompanyNames(stations, companyNames);
filterByChargerTypes(stations, chargerTypes);
filterByCapacities(stations, capacities);
return Collections.unmodifiableList(stations);
}

private void filterByChargerTypes(List<Station> stations, List<ChargerType> chargerTypes) {
if (!chargerTypes.isEmpty()) {
stations.removeIf(station -> station
.getChargers()
.stream()
.noneMatch(charger -> chargerTypes.contains(charger.getType()))
);
}
}

private void filterByCapacities(List<Station> stations, List<BigDecimal> capacities) {
if (!capacities.isEmpty()) {
stations.removeIf(station -> station
.getChargers()
.stream()
.noneMatch(charger -> capacities.stream()
.anyMatch(capacity -> isSameCapacity(charger.getCapacity(), capacity))
));
}
}

private boolean isSameCapacity(BigDecimal capacity, BigDecimal filterCapacity) {
return capacity.compareTo(filterCapacity) == 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
import com.carffeine.carffeine.station.domain.charger.ChargerCondition;
import com.carffeine.carffeine.station.domain.charger.ChargerStatus;
import com.carffeine.carffeine.station.domain.charger.ChargerStatusRepository;
import com.carffeine.carffeine.station.domain.charger.ChargerType;
import com.carffeine.carffeine.station.domain.congestion.IdGenerator;
import com.carffeine.carffeine.station.domain.congestion.PeriodicCongestion;
import com.carffeine.carffeine.station.domain.congestion.PeriodicCongestionRepository;
import com.carffeine.carffeine.station.domain.congestion.RequestPeriod;
import com.carffeine.carffeine.station.domain.station.Latitude;
import com.carffeine.carffeine.station.domain.station.Longitude;
import com.carffeine.carffeine.station.domain.station.Coordinate;
import com.carffeine.carffeine.station.domain.station.Station;
import com.carffeine.carffeine.station.domain.station.StationRepository;
import com.carffeine.carffeine.station.domain.station.Stations;
import com.carffeine.carffeine.station.exception.StationException;
import com.carffeine.carffeine.station.exception.StationExceptionType;
import com.carffeine.carffeine.station.service.station.dto.CoordinateRequest;
Expand All @@ -35,18 +36,13 @@ public class StationService {
private final ChargerStatusRepository chargerStatusRepository;

@Transactional(readOnly = true)
public List<Station> findByCoordinate(CoordinateRequest request) {
Latitude originLatitude = Latitude.from(request.latitude());
BigDecimal deltaLatitude = request.latitudeDelta();
Latitude minLatitude = originLatitude.calculateMinLatitudeByDelta(deltaLatitude);
Latitude maxLatitude = originLatitude.calculateMaxLatitudeByDelta(deltaLatitude);
public List<Station> findByCoordinate(CoordinateRequest request, List<String> companyNames, List<ChargerType> chargerTypes, List<BigDecimal> capacities) {
Coordinate coordinate = Coordinate.of(request.latitude(), request.latitudeDelta(), request.longitude(), request.longitudeDelta());

Longitude originLongitude = Longitude.from(request.longitude());
BigDecimal deltaLongitude = request.longitudeDelta();
Longitude minLongitude = originLongitude.calculateMinLongitudeByDelta(deltaLongitude);
Longitude maxLongitude = originLongitude.calculateMaxLongitudeByDelta(deltaLongitude);
List<Station> stationsByCoordinate = stationRepository.findAllFetchByLatitudeBetweenAndLongitudeBetween(coordinate.minLatitudeValue(), coordinate.maxLatitudeValue(), coordinate.minLongitudeValue(), coordinate.maxLongitudeValue());
Stations stations = Stations.from(stationsByCoordinate);

return stationRepository.findAllByLatitudeBetweenAndLongitudeBetween(minLatitude, maxLatitude, minLongitude, maxLongitude);
return stations.findFilteredStations(companyNames, chargerTypes, capacities);
}

@Transactional(readOnly = true)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.carffeine.carffeine.station.controller.station;

import com.carffeine.carffeine.station.domain.charger.ChargerType;
import com.carffeine.carffeine.station.domain.station.Station;
import com.carffeine.carffeine.station.exception.StationException;
import com.carffeine.carffeine.station.exception.StationExceptionType;
Expand Down Expand Up @@ -59,14 +60,17 @@ class StationControllerTest {

// when
List<Station> fakeStations = List.of(선릉역_충전소_충전기_2_사용_1개);
when(stationService.findByCoordinate(coordinateRequest)).thenReturn(fakeStations);
when(stationService.findByCoordinate(coordinateRequest, List.of("볼튼"), List.of(ChargerType.DC_COMBO), List.of(new BigDecimal("50.00")))).thenReturn(fakeStations);

// then
mockMvc.perform(get("/api/stations")
.param("latitude", latitude.toString())
.param("longitude", longitude.toString())
.param("latitudeDelta", latitudeDelta.toString())
.param("longitudeDelta", longitudeDelta.toString())
.param("companyNames", "볼튼")
.param("chargerTypes", ChargerType.DC_COMBO.toString())
.param("capacities", "50.00")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
Expand All @@ -76,7 +80,10 @@ class StationControllerTest {
parameterWithName("latitude").description("기준 위도"),
parameterWithName("longitude").description("기준 경도"),
parameterWithName("latitudeDelta").description("변화 위도"),
parameterWithName("longitudeDelta").description("변화 경도")
parameterWithName("longitudeDelta").description("변화 경도"),
parameterWithName("companyNames").description("필터가 적용된 충전기 회사 이름"),
parameterWithName("chargerTypes").description("필터가 적용된 충전기 타입"),
parameterWithName("capacities").description("필터가 적용된 충전기 출력")
),
responseFields(
fieldWithPath("stations").type(JsonFieldType.ARRAY).description("충전소들"),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.carffeine.carffeine.station.domain.station;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand All @@ -24,6 +25,15 @@ public List<Station> findAllByLatitudeBetweenAndLongitudeBetween(Latitude minLat
.toList();
}

@Override
public List<Station> findAllFetchByLatitudeBetweenAndLongitudeBetween(final BigDecimal minLatitude, final BigDecimal maxLatitude, final BigDecimal minLongitude, final BigDecimal maxLongitude) {
return map.values().stream()
.filter(it -> it.getLatitude().getValue().compareTo(minLatitude) >= 0 && it.getLatitude().getValue().compareTo(maxLatitude) <= 0)
.filter(it -> it.getLongitude().getValue().compareTo(minLongitude) >= 0 && it.getLongitude().getValue().compareTo(maxLongitude) <= 0)
.toList();
}


@Override
public Optional<Station> findChargeStationByStationId(String stationId) {
return map.values().stream()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.carffeine.carffeine.station.domain.station;

import com.carffeine.carffeine.station.domain.charger.ChargerType;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.carffeine.carffeine.station.fixture.station.StationFixture.선릉역_충전소_충전기_2_사용_1_이름_변경됨;
import static com.carffeine.carffeine.station.fixture.station.StationFixture.천호역_충전소_충전기_2_사용_1개;
import static org.assertj.core.api.SoftAssertions.assertSoftly;

@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
@SuppressWarnings("NonAsciiCharacters")
class StationsTest {

@Test
void 회사_이름을_기준으로_충전소를_필터링한다() {
// given
Stations stations = Stations.from(List.of(
천호역_충전소_충전기_2_사용_1개,
선릉역_충전소_충전기_2_사용_1_이름_변경됨
));

// when
List<Station> result = stations.findFilteredStations(List.of("볼튼"), new ArrayList<>(), new ArrayList<>());

// then
assertSoftly(softly -> {
softly.assertThat(result.size()).isEqualTo(1);
softly.assertThat(result.get(0).getStationId()).isEqualTo(선릉역_충전소_충전기_2_사용_1_이름_변경됨.getStationId());
});
}

@Test
void 충전기_타입을_기준으로_충전소를_필터링한다() {
// given
Stations stations = Stations.from(List.of(
천호역_충전소_충전기_2_사용_1개,
선릉역_충전소_충전기_2_사용_1_이름_변경됨
));

// when
List<Station> result = stations.findFilteredStations(new ArrayList<>(), List.of(ChargerType.AC_SLOW), new ArrayList<>());

// then
assertSoftly(softly -> {
softly.assertThat(result.size()).isEqualTo(1);
softly.assertThat(result.get(0).getStationId()).isEqualTo(천호역_충전소_충전기_2_사용_1개.getStationId());
});
}

@Test
void 충전기_속도를_기준으로_충전소를_필터링한다() {
// given
Stations stations = Stations.from(List.of(
천호역_충전소_충전기_2_사용_1개,
선릉역_충전소_충전기_2_사용_1_이름_변경됨
));

// when
List<Station> result = stations.findFilteredStations(new ArrayList<>(), new ArrayList<>(), List.of(BigDecimal.valueOf(100.00)));

// then
assertSoftly(softly -> {
softly.assertThat(result.size()).isEqualTo(1);
softly.assertThat(result.get(0).getStationId()).isEqualTo(천호역_충전소_충전기_2_사용_1개.getStationId());
});
}
}

0 comments on commit 31fbd19

Please sign in to comment.