Skip to content

Commit

Permalink
refactor: 차량 필터링 관련 기능 명세 변경을 적용한다 (#536)
Browse files Browse the repository at this point in the history
* refactor: 멤버 토큰, 멤버 정보 변수 초기화 로직 실행 위치 수정

[#506]

* refactor: 멤버 아이디, 멤버 토큰이 없는 경우 에러 처리

- 로그인 하기 전 사용자가 멤버 필터링 정보에 접근하려고 하는 경우 빈 필터링정보를 반환한다.

[#506]

* refactor: 멤버의 차 아이디가 없는 경우 에러 처리

[#506]

* refactor: 분리돼있던 충전소 필터링 타입 병합

[#506]

* refactor: 유저 자동차 정보 타입에 null 추가

[#506]

* refactor: 불필요한 코드 삭제

[#506]

* refactor: 초기 렌더링시 msw작동 여부 판별하는 로직 수정

[#506]

* refactor: api 요청 메서드 분리

[#506]

* design: 차량 선택 모달 디자인 수정 (간단하게만)

[#506]

* fix: 명세 적용 실수 수정

[#506]

* fix: POST 요청 헤더에 'Content-Type': 'application/json' 추가

[#506]

* refactor: 전체 차량 조회 관련 mock api 수정

[#506]

* refactor: 오류 원인 파악을 위한 console.log 추가

[#506]

* test: 오류 원인 파악을 위한 console.log 추가

[#506]

* comment: TODO 추가

- 로그인 이후 유저의 필터링 정보가 바로 반영되지 않는 문제 해결하기

[#506]

* refactor: 유저 필터링 정보 반영 로직 수정

[#506]

* refactor: 쿼리키 상수호

[#506]

* fix: 로그인 런타임 에러 수정

[#506]

* refactor: memberInfo 초기 값 수정

[#506]

* refactor: 사용하지 않는 import 삭제

[#506]

* refactor: 리뷰 반영

[#506]
  • Loading branch information
kyw0716 authored Aug 16, 2023
1 parent ee10598 commit cc1df3a
Show file tree
Hide file tree
Showing 18 changed files with 266 additions and 174 deletions.
22 changes: 10 additions & 12 deletions frontend/src/components/google-maps/map/CarFfeineMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { toastActions } from '@stores/layout/toastStore';
import { memberTokenStore } from '@stores/login/memberTokenStore';
import { serverStationFilterAction } from '@stores/station-filters/serverStationFiltersStore';

import { useCarFilters } from '@hooks/tanstack-query/station-filters/useCarFilters';
import { useMemberFilters } from '@hooks/tanstack-query/station-filters/useMemberFilters';

import ToastContainer from '@common/Toast/ToastContainer';
Expand Down Expand Up @@ -74,23 +73,22 @@ const CarFfeineMapListener = () => {
return <></>;
};

// TODO: 유저 필터링이 로그인 된 이후 바로 적용되지 않는 문제 다시 발생. 이 부분 어떻게 수정할지 고민해보기
const UserFilterListener = () => {
const queryClient = useQueryClient();
const { data: memberFilters } = useMemberFilters();
const { data: carFilters } = useCarFilters();
const { setCarFilters, setAllServerStationFilters } = serverStationFilterAction;
const { setAllServerStationFilters } = serverStationFilterAction;

useEffect(() => {
if (memberTokenStore.getState() !== '' && memberFilters !== undefined) {
setAllServerStationFilters(memberFilters);
}

if (carFilters !== undefined) {
setCarFilters(carFilters);
}
console.log('현재 로그인한 유저가 등록한 필터 정보', memberFilters);
console.log(
'클라이언트 전역 상태에 저장된 필터 정보',
serverStationFilterAction.getAllServerStationFilters()
);

if (memberFilters !== undefined) {
setAllServerStationFilters(memberFilters);
queryClient.invalidateQueries([{ queryKey: [QUERY_KEY_STATIONS] }]);
}, [memberFilters, carFilters]);
}

return <></>;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { memberInfoStore } from '@stores/login/memberInfoStore';
import { memberTokenStore } from '@stores/login/memberTokenStore';
import { serverStationFilterAction } from '@stores/station-filters/serverStationFiltersStore';

import type { ServerStationFilters } from '@hooks/tanstack-query/station-filters/useServerStationFilters';
import { useServerStationFilters } from '@hooks/tanstack-query/station-filters/useServerStationFilters';
import { useServerStationFilterActions } from '@hooks/useServerStationFilterActions';

Expand All @@ -29,7 +28,7 @@ import type { Capacity, StationFilters } from '@type';

import FilterSection from './FilterOption';

const ServerStationFiltersComponent = () => {
const ServerStationFilters = () => {
const queryClient = useQueryClient();
const { showToast } = toastActions;
const { data: serverStationFilters, isLoading } = useServerStationFilters();
Expand Down Expand Up @@ -72,6 +71,7 @@ const ServerStationFiltersComponent = () => {
method: 'POST',
headers: {
Authorization: `Bearer ${memberToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
filters: [
Expand All @@ -96,7 +96,7 @@ const ServerStationFiltersComponent = () => {

showToast('필터가 적용되었습니다');
} catch {
const stationFilters = queryClient.getQueryData<ServerStationFilters>([
const stationFilters = queryClient.getQueryData<StationFilters>([
QUERY_KEY_MEMBER_SELECTED_FILTERS,
]);
resetAllServerStationFilters(stationFilters);
Expand Down Expand Up @@ -200,4 +200,4 @@ export const filterHeaderCss = css`
padding: 0 2rem;
`;

export default ServerStationFiltersComponent;
export default ServerStationFilters;
4 changes: 2 additions & 2 deletions frontend/src/components/ui/ServerStationFilters/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import ServerStationFiltersComponent from './ServerStationFilters';
import ServerStationFilters from './ServerStationFilters';

export default ServerStationFiltersComponent;
export default ServerStationFilters;
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { useNavigationBar } from '@ui/compound/NavigationBar/hooks/useNavigation
import { pillStyle } from '@style';

import { INITIAL_ZOOM_SIZE } from '@constants/googleMaps';
import { QUERY_KEY_STATIONS } from '@constants/queryKeys';
import { QUERY_KEY_SEARCHED_STATION, QUERY_KEY_STATIONS } from '@constants/queryKeys';

import type { StationPosition } from '@type/stations';

Expand Down Expand Up @@ -59,7 +59,7 @@ const StationSearchBar = () => {
showStationDetails({ stationId, latitude, longitude });
}

queryClient.invalidateQueries({ queryKey: ['searchedStations'] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEY_SEARCHED_STATION] });
};

const showStationDetails = ({ stationId, latitude, longitude }: StationPosition) => {
Expand Down
7 changes: 2 additions & 5 deletions frontend/src/components/ui/compound/NavigationBar/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import Button from '@common/Button';
import FlexBox from '@common/FlexBox';

import MswControlButton from '@ui/MswControlButton';
import ServerStationFiltersComponent from '@ui/ServerStationFilters';
import ServerStationFilters from '@ui/ServerStationFilters';
import StationSearchWindow from '@ui/StationSearchWindow';
import LogoIcon from '@ui/Svg/LogoIcon';
import CarModal from '@ui/modal/CarModal/CarModal';
Expand Down Expand Up @@ -95,10 +95,7 @@ const Menu = () => {
<Button aria-label="검색창 열기" onClick={() => openBasePanel(<StationSearchWindow />)}>
<MagnifyingGlassIcon width="2.8rem" stroke="#333" />
</Button>
<Button
aria-label="필터링 메뉴 열기"
onClick={() => openBasePanel(<ServerStationFiltersComponent />)}
>
<Button aria-label="필터링 메뉴 열기" onClick={() => openBasePanel(<ServerStationFilters />)}>
<AdjustmentsHorizontalIcon width="2.8rem" stroke="#333" />
</Button>
{memberToken !== '' ? (
Expand Down
138 changes: 54 additions & 84 deletions frontend/src/components/ui/modal/CarModal/CarModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,27 @@ import { useState } from 'react';

import { useQueryClient } from '@tanstack/react-query';

import { serverStore } from '@stores/config/serverStore';
import { modalActions } from '@stores/layout/modalStore';
import { toastActions } from '@stores/layout/toastStore';
import { memberInfoStore } from '@stores/login/memberInfoStore';
import { memberTokenStore } from '@stores/login/memberTokenStore';
import { serverStationFilterAction } from '@stores/station-filters/serverStationFiltersStore';

import { useCars } from '@hooks/tanstack-query/car/useCars';
import type { ServerStationFilters } from '@hooks/tanstack-query/station-filters/useServerStationFilters';

import ButtonNext from '@common/ButtonNext';
import FlexBox from '@common/FlexBox';
import Text from '@common/Text';

import LogoIcon from '@ui/Svg/LogoIcon';

import { SERVERS } from '@constants';
import { QUERY_KEY_STATIONS } from '@constants/queryKeys';

import type { StationFilters } from '@type';
import type { Car } from '@type/cars';
import { getCarFilters, submitMemberCar, submitMemberFilters } from './fetch';

const CarModal = () => {
const queryClient = useQueryClient();

const { data: cars, isLoading } = useCars();
const { getAllServerStationFilters, setCarFilters, setAllServerStationFilters } =
serverStationFilterAction;

const memberId = memberInfoStore.getState()?.memberId;
const memberToken = memberTokenStore.getState();

const { closeModal } = modalActions;
const { setAllServerStationFilters } = serverStationFilterAction;

const [carName, setCarName] = useState('');
const [vintage, setVintage] = useState('');
Expand All @@ -58,58 +46,19 @@ const CarModal = () => {
return;
}

const mode = serverStore.getState();

const memberCarInfo = await fetch(`${SERVERS[mode]}/members/${memberId}/cars`, {
method: 'POST',
headers: {
Authorization: `Bearer ${memberToken}`,
},
body: JSON.stringify({ name: carName, vintage }),
}).then<Car>((response) => response.json());

const carFilters = await fetch(`${SERVERS[mode]}/cars/${memberCarInfo.carId}/filters`).then<
Omit<ServerStationFilters, 'companies'>
>((response) => response.json());
try {
const { carId } = await submitMemberCar(carName, vintage);
const carFilters = await getCarFilters(carId);
const memberFilters = await submitMemberFilters(carFilters);

setCarFilters(carFilters);

const { capacities, companies, connectorTypes } = getAllServerStationFilters();

if (memberId === undefined) {
setAllServerStationFilters(memberFilters);
queryClient.invalidateQueries({ queryKey: [QUERY_KEY_STATIONS] });
return;
}

const memberFilters = await fetch(`${SERVERS[mode]}/members/${memberId}/filters`, {
method: 'POST',
headers: {
Authorization: `Bearer ${memberToken}`,
},
body: JSON.stringify({
filters: [
...capacities.map((capacity) => ({
type: 'capacity',
name: capacity,
})),
...companies.map((company) => ({
type: 'company',
name: company,
})),
...connectorTypes.map((connectorType) => ({
type: 'connectorType',
name: connectorType,
})),
],
}),
}).then<StationFilters>((response) => response.json());

setAllServerStationFilters(memberFilters);
queryClient.invalidateQueries({ queryKey: [QUERY_KEY_STATIONS] });

toastActions.showToast('챠량 등록이 완료되었습니다');

closeModal();
toastActions.showToast('챠량 등록이 완료되었습니다');
modalActions.closeModal();
} catch (error) {
toastActions.showToast(error.message, 'error');
}
};

if (isLoading || cars === undefined) {
Expand All @@ -124,26 +73,44 @@ const CarModal = () => {
const carNames = [...new Set([...(cars ?? []).map((car) => car.name)])];

return (
<FlexBox direction="column" alignItems="center">
<FlexBox>
<SelectBox options={['모델명', ...carNames]} onChange={handleSelectCarName} />
<SelectBox
options={[
'연식',
...cars
.filter((car) => car.name === (carName !== '' ? carName : carNames[0]))
.map((car) => car.vintage),
]}
onChange={handleSelectVintage}
/>
<FlexBox width={34} direction="column" alignItems="center" css={{ padding: '1rem' }}>
<Text variant="h5" mb={3}>
차량 선택
</Text>
<FlexBox width="100%">
<FlexBox css={{ flex: 1, height: '4rem' }}>
<SelectBox options={['모델명', ...carNames]} onChange={handleSelectCarName} />
</FlexBox>
<FlexBox css={{ flex: 1, height: '4rem' }}>
<SelectBox
options={[
'연식',
...cars
.filter((car) => car.name === (carName !== '' ? carName : carNames[0]))
.map((car) => car.vintage),
]}
onChange={handleSelectVintage}
/>
</FlexBox>
</FlexBox>
<FlexBox>
<ButtonNext onClick={handleFetchCarFilters} variant="outlined" color="success">
등록
</ButtonNext>
<ButtonNext onClick={closeModal} variant="outlined" color="error">
<FlexBox width="100%">
<ButtonNext onClick={modalActions.closeModal} variant="outlined" css={{ flex: 1 }}>
취소
</ButtonNext>
<ButtonNext
onClick={() => {
try {
handleFetchCarFilters();
} catch (error) {
console.log(error);
toastActions.showToast(error.message, 'error');
}
}}
variant="contained"
css={{ flex: 1 }}
>
등록
</ButtonNext>
</FlexBox>
</FlexBox>
);
Expand All @@ -158,12 +125,15 @@ const SelectBox = ({
}) => {
return (
<select
onChange={(e) => {
onChange(e.target.value);
onChange={({ target: { value } }) => {
onChange(value);
}}
style={{
flex: 1,
}}
>
{options.map((option, i) => (
<option key={i} value={option}>
{options.map((option, index) => (
<option key={index} value={option}>
{option}
</option>
))}
Expand Down
Loading

0 comments on commit cc1df3a

Please sign in to comment.