Skip to content

Commit

Permalink
Merge pull request #336 from SCBJ-7/feat/#319-transferWritingPrice
Browse files Browse the repository at this point in the history
[#319] 판매글 작성 페이지 로직 커스텀 훅으로 정리
  • Loading branch information
Bumang-Cyber authored Mar 7, 2024
2 parents bdf3fb8 + 610d0f9 commit 31317c1
Show file tree
Hide file tree
Showing 20 changed files with 421 additions and 215 deletions.
3 changes: 0 additions & 3 deletions src/apis/fetchMainItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ export const fetchMainItem = async (): Promise<
"?cityNames=서울&cityNames=강원&cityNames=부산&cityNames=제주&cityNames=경상&cityNames=전라",
);

console.log(data);

const { weekend, ...locale } = data.data;
console.log(locale, "locale");
const temp = weekend.content.length ? weekend.content : [];

return [locale, temp];
Expand Down
3 changes: 2 additions & 1 deletion src/apis/logout.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ACCESS_TOKEN, END_POINTS, REFRESH_TOKEN } from "@/constants/api";
import { axiosInstance } from "@apis/axiosInstance";

import { ACCESS_TOKEN, END_POINTS, REFRESH_TOKEN } from "@/constants/api";

export const logout = async () => {
await axiosInstance.post(`${END_POINTS.USER_INFO}/logout`, {
accessToken: localStorage.getItem(ACCESS_TOKEN),
Expand Down
3 changes: 2 additions & 1 deletion src/components/Helmet/Helmet.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { PATH } from "@/constants/path";
import { Helmet } from "react-helmet-async";

import { PATH } from "@/constants/path";

export const HelmetTag = ({ text }: { text: string }) => {
return (
<Helmet>
Expand Down
68 changes: 68 additions & 0 deletions src/hooks/api/usePostTransferItems.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate } from "react-router-dom";

import { postTransferItems } from "@/apis/postTransferItems";
import { PATH } from "@/constants/path";
import { useSelectedItemStore } from "@/store/store";
import { ProfileData } from "@/types/profile";

interface PostTransferItems {
firstPrice: string;
secondPrice: string;
downTimeAfter: string;
is2ndChecked: boolean;
opt1: boolean;
opt2: boolean;
opt3: boolean;
optFinal: boolean;
bank: string | null;
accountNumber: string | null;
userData: ProfileData;
}
const usePostTransferItems = ({
firstPrice,
secondPrice,
downTimeAfter,
is2ndChecked,
opt1,
opt2,
opt3,
optFinal,
bank,
accountNumber,
userData,
}: PostTransferItems) => {
const selectedItem = useSelectedItemStore((state) => state.selectedItem);

// 처음 들어올 때 계좌가 있는지 여부.
const [firstlyNoAccount] = useState(userData?.accountNumber ? false : true);

const navigate = useNavigate();
const { mutate } = useMutation({
mutationFn: () =>
postTransferItems({
pathVariable: `${selectedItem.reservationId}`,
firstPrice: Number(firstPrice.split(",").join("")),
secondPrice: Number(secondPrice.split(",").join("")),
bank: bank as string,
accountNumber: accountNumber as string,
secondGrantPeriod: Number(downTimeAfter),
isRegistered: is2ndChecked,
standardTimeSellingPolicy: opt1,
totalAmountPolicy: opt2,
sellingModificationPolicy: opt3,
productAgreement: optFinal,
}),
onSuccess: () => {
alert("판매 게시물이 성공적으로 등록되었습니다!");
navigate(PATH.WRITE_TRANSFER_SUCCESS + "?FNA=" + `${firstlyNoAccount}`, {
state: { bank, accountNumber },
});
},
});

return { mutate };
};

export default usePostTransferItems;
6 changes: 5 additions & 1 deletion src/hooks/common/useAnimateCarousel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ interface CarouselProps {
}

const inrange = (v: number, min: number, max: number) => {
// v는 current number?
// v는 델타x
if (v < min) return min;
if (v > max) return max;
return v;
Expand Down Expand Up @@ -38,6 +38,7 @@ export const useAnimateCarousel = ({

const handleDragChange = (deltaX: number) => {
setTransX(inrange(deltaX, -slideWidth, slideWidth));
console.log(deltaX, "deltaX");
};

const handleDragEnd = (deltaX: number) => {
Expand Down Expand Up @@ -68,6 +69,7 @@ export const useAnimateCarousel = ({
const handleTouchMove = (moveEvent: globalThis.TouchEvent) => {
if (moveEvent.cancelable) moveEvent.preventDefault();

console.log(moveEvent.touches, "moveEvent.touches");
const delta = moveEvent.touches[0].pageX - touchEvent.touches[0].pageX;
handleDragChange(delta);
};
Expand All @@ -94,6 +96,8 @@ export const useAnimateCarousel = ({
clickEvent.preventDefault();

const handleMouseMove = (moveEvent: MouseEvent) => {
console.log(moveEvent.pageX, "mouseEvent pageX");
console.log(clickEvent.pageX, "clickevent pageX");
const deltaX = moveEvent.pageX - clickEvent.pageX;
handleDragChange(deltaX);
};
Expand Down
55 changes: 55 additions & 0 deletions src/hooks/common/useChangePage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

import { PATH } from "@/constants/path";
import { useSelectedItemStore, useStateHeaderStore } from "@/store/store";

interface changePageProps {
is2ndChecked: boolean;
firstCheckRef: React.MutableRefObject<null>;
}

const useChangePage = ({ is2ndChecked, firstCheckRef }: changePageProps) => {
const navigate = useNavigate();
const setHeaderConfig = useStateHeaderStore((state) => state.setHeaderConfig);
const selectedItem = useSelectedItemStore((state) => state.selectedItem);

// 현재 페이지가 어디인지
const [accountSetting, setAccountSetting] = useState<"none" | "enter">(
"none",
);

// 페이지 전환 시 적용할 효과
useEffect(() => {
if (accountSetting === "none") {
setHeaderConfig({
title: selectedItem.hotelName,
undo: () => {
navigate(PATH.WRITE_TRANSFER);
},
});

if (is2ndChecked && firstCheckRef.current) {
(firstCheckRef.current as HTMLInputElement).checked = true;
}
}

if (accountSetting === "enter") {
setHeaderConfig({
title: "계좌 연동하기",
undo: () => {
setAccountSetting("none");
},
});

if (is2ndChecked && firstCheckRef.current) {
(firstCheckRef.current as HTMLInputElement).checked = false;
}
}
// eslint-disable-next-line
}, [accountSetting]);

return { accountSetting, setAccountSetting };
};

export default useChangePage;
79 changes: 79 additions & 0 deletions src/hooks/common/useReadyToSubmit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { useEffect } from "react";

import { ProfileData } from "@/types/profile";

interface ReadyToSubmitProps {
setReadyToSubmit: React.Dispatch<React.SetStateAction<boolean>>;
firstPrice: string;
secondPrice: string;
opt1: boolean;
opt2: boolean;
opt3: boolean;
optFinal: boolean;
bank: string | null;
accountNumber: string | null;
is2ndChecked: boolean;
downTimeAfter: string;
userData: ProfileData;
}

const useReadyToSubmit = ({
setReadyToSubmit,
firstPrice,
opt1,
opt2,
opt3,
optFinal,
bank,
accountNumber,
is2ndChecked,
secondPrice,
downTimeAfter,
userData,
}: ReadyToSubmitProps) => {
useEffect(() => {
setReadyToSubmit(() => {
if (
firstPrice &&
opt1 &&
opt2 &&
opt3 &&
optFinal &&
bank &&
accountNumber
) {
// accountNumber 추가
if (!is2ndChecked) return true; // 2차 가격 설정하기 체크 안 하고 계좌 등록된 경우

if (is2ndChecked && secondPrice && downTimeAfter) {
return true; // 2차 가격 설정한 경우
} else if (is2ndChecked && !secondPrice && !downTimeAfter) {
return false; // 2차 가격 체크했지만 아무것도 쓰지 않은 경우는 일단 가능
} else if (is2ndChecked && !secondPrice && downTimeAfter) {
return false; // 2차 가격 체크하고 2차 가격 입력 안 하고 시간만 입력한 경우
} else if (is2ndChecked && secondPrice && !downTimeAfter) {
return false; // 2차 가격 체크하고 2차 시간 입력 안 하고 가격만 입력한 경우
} else if (!userData?.bank || !userData?.accountNumber) {
return false;
}
}

return false; // 1차가격 설정과 약관 동의 안한 경우
});
}, [
setReadyToSubmit,
firstPrice,
opt1,
opt2,
opt3,
optFinal,
is2ndChecked,
secondPrice,
downTimeAfter,
userData,
bank,
accountNumber,
]);
};

export default useReadyToSubmit;
127 changes: 127 additions & 0 deletions src/hooks/common/useSubmitHandler.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import useToastConfig from "@/hooks/common/useToastConfig";
import { useSelectedItemStore } from "@/store/store";
import { ProfileData } from "@/types/profile";

interface SubmitProps {
readyToSubmit: boolean;
firstPrice: string;
secondPrice: string;
downTimeAfter: string;
firstInputRef: React.MutableRefObject<null>;
secondPriceInputRef: React.MutableRefObject<null>;
secondTimeInputRef: React.MutableRefObject<null>;
is2ndChecked: boolean;
userData: ProfileData;
mutate: () => void;
opt1: boolean;
opt2: boolean;
opt3: boolean;
optFinal: boolean;
}

const useSubmitHandler = ({
readyToSubmit,
firstPrice,
secondPrice,
downTimeAfter,
firstInputRef,
secondPriceInputRef,
secondTimeInputRef,
is2ndChecked,
userData,
mutate,
opt1,
opt2,
opt3,
optFinal,
}: SubmitProps) => {
const { handleToast } = useToastConfig();
const selectedItem = useSelectedItemStore((state) => state.selectedItem);

const submitHandler = () => {
if (!readyToSubmit) {
const firstPriceNum = Number(firstPrice.split(",").join(""));
const secondPriceNum = Number(secondPrice.split(",").join(""));
const downTimeAfterNum = Number(downTimeAfter);

if (!firstPriceNum) {
handleToast(true, [<>1차 가격을 설정해주세요</>]);
if (firstInputRef.current) {
(firstInputRef.current as HTMLInputElement).focus();
// + 스크롤 상단으로 올리기
}
// 1차 가격이 판매가보다 높을 때
} else if (firstPriceNum > selectedItem.purchasePrice) {
handleToast(true, [
<>판매가격이 구매가보다 높아요! 판매가격을 확인해주세요</>,
]);

if (firstInputRef.current) {
(firstInputRef.current as HTMLInputElement).focus();
// + 스크롤 상단으로 올리기
}
// 2차 가격이 1차 가격보다 높을 때
} else if (secondPriceNum > firstPriceNum) {
handleToast(true, [<>2차가격은 1차 가격보다 낮게 설정해주세요</>]);

if (secondPriceInputRef.current) {
(secondPriceInputRef.current as HTMLInputElement).focus();
// + 스크롤 상단으로 올리기
}
// 2차가격 인하 시간을 3시간 이하로 설정했을 때
} else if (downTimeAfterNum && downTimeAfterNum < 3) {
handleToast(true, [
<>체크인 3시간 전까지만 2차 가격 설정이 가능해요</>,
]);

if (secondTimeInputRef.current) {
(secondTimeInputRef.current as HTMLInputElement).focus();
// + 스크롤 상단으로 올리기
}
// 2차 가격만 입력하고 2차 기준시간은 입력 안 했을 때
} else if (is2ndChecked && secondPrice && !downTimeAfter) {
handleToast(true, [<>2차 가격으로 내릴 시간을 입력해주세요</>]);

if (secondTimeInputRef.current) {
(secondTimeInputRef.current as HTMLInputElement).focus();
// + 스크롤 상단으로 올리기
}
// 2차 기준시간만 입력하고 2차 가격은 입력 안 했을 때
} else if (is2ndChecked && !secondPrice && downTimeAfter) {
handleToast(true, [<>2차 가격을 입력해주세요</>]);

if (secondPriceInputRef.current) {
(secondPriceInputRef.current as HTMLInputElement).focus();
// + 스크롤 상단으로 올리기
}
// 2차 가격 설정을 체크해놓고 2차 가격과 시간 모두 입력 안 했을 때
} else if (is2ndChecked && !secondPrice && !downTimeAfter) {
handleToast(true, [<>2차 가격을 입력해주세요</>]);

if (secondTimeInputRef.current) {
(secondTimeInputRef.current as HTMLInputElement).focus();
// + 스크롤 상단으로 올리기
}
}
// 약관 동의를 다 안 했을 때
else if (!opt1 || !opt2 || !opt3 || !optFinal) {
handleToast(true, [<>판매 진행 약관에 동의해주세요</>]);

// 계좌를 입력 안 한 경우
} else if (!userData?.accountNumber) {
handleToast(true, [<>계좌를 입력해주세요</>]);
}

return;
}

const confirmToProceed = confirm("판매 게시물을 등록하시겠어요?");
if (confirmToProceed) {
mutate();
}
};

return [submitHandler];
};

export default useSubmitHandler;
Loading

0 comments on commit 31317c1

Please sign in to comment.