Skip to content

Commit

Permalink
refactor(ui): 주문하기 페이지에서 선택한 옵션을 모두 확인할 수 있게 UI 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
userjmmm authored and userjmmm committed Aug 4, 2024
1 parent 9edd99b commit a876457
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 63 deletions.
1 change: 0 additions & 1 deletion src/api/hooks/useGetProductOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export const getProductOptions = async (params: ProductDetailRequestParams) => {
const response = await fetchInstance.get<ProductOptionsResponseData>(
getProductOptionsPath(params.productId),
);
console.log("options: ", response.data);
return response.data;
};

Expand Down
25 changes: 12 additions & 13 deletions src/components/features/Order/OrderForm/GoodsInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,18 @@ import type { OrderHistory } from '@/types';
import { LabelText } from '../Common/LabelText';

type Props = {
orderHistory: OrderHistory;
orderHistory: OrderHistory[];
};

export const GoodsInfo = ({ orderHistory }: Props) => {
const { productId, optionId, quantity } = orderHistory;
const productId = orderHistory[0].productId;
const { data: detail, isLoading: isDetailLoading } = useGetProductDetail({ productId: productId.toString() });
const { data: options, isLoading: isOptionsLoading } = useGetProductOptions({ productId: productId.toString() });

if (isDetailLoading || isOptionsLoading) {
return <div>정보를 불러오는 중입니다...</div>;
}

const selectedOption = options.find(option => option.id === optionId);

return (
<Wrapper>
<LabelText>선물내역</LabelText>
Expand All @@ -32,15 +30,16 @@ export const GoodsInfo = ({ orderHistory }: Props) => {
<Image src={detail.imageUrl} width={86} ratio="square" />
</GoodsInfoImage>
<GoodsInfoTextWrapper>
<GoodsInfoTextTitle>
{detail.name} X {quantity}
</GoodsInfoTextTitle>
<GoodsInfoTextMessage>
{orderHistory.message}
</GoodsInfoTextMessage>
<GoodsInfoTextOption>
{selectedOption ? selectedOption.name : '옵션 없음'}
</GoodsInfoTextOption>
<GoodsInfoTextTitle>{detail.name}</GoodsInfoTextTitle>
{orderHistory.map((order, index) => {
const selectedOption = options.find(option => option.id === order.optionId);
return (
<GoodsInfoTextOption key={index}>
{selectedOption ? `${selectedOption.name} X ${order.quantity}개` : '옵션 없음'}
</GoodsInfoTextOption>
);
})}
<GoodsInfoTextMessage>{orderHistory[0].message}</GoodsInfoTextMessage>
</GoodsInfoTextWrapper>
</GoodsInfoWrapper>
</GoodsWrapper>
Expand Down
32 changes: 16 additions & 16 deletions src/components/features/Order/OrderForm/OrderInfo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import { Divider } from '@chakra-ui/react';
import styled from '@emotion/styled';

import { useGetProductDetail } from '@/api/hooks/useGetProductDetail';
import { useGetProductOptions } from '@/api/hooks/useGetProductOptions';
import { Button } from '@/components/common/Button';
import { Spacing } from '@/components/common/layouts/Spacing';
import type { OrderHistory } from '@/types';

import { HeadingText } from '../Common/HeadingText';
import { LabelText } from '../Common/LabelText';
import { CashReceiptFields } from '../Fields/CashReceiptFields';
import { LoadingView } from '@/components/common/View/LoadingView';

type Props = {
orderHistory: OrderHistory;
orderHistory: OrderHistory[];
};

export const OrderFormOrderInfo = ({ orderHistory }: Props) => {
const { productId, optionId, quantity, message } = orderHistory;

const productId = orderHistory[0].productId;
const { data: detail, isLoading: isDetailLoading } = useGetProductDetail({ productId: productId.toString() });
const { data: options, isLoading: isOptionsLoading } = useGetProductOptions({ productId: productId.toString() });

Expand All @@ -30,8 +27,10 @@ export const OrderFormOrderInfo = ({ orderHistory }: Props) => {
return <div>상품 정보를 불러오는 중 오류가 발생했습니다.</div>;
}

const selectedOption = options.find(option => option.id === optionId);
const totalPrice = selectedOption ? detail.price * quantity : 0;
const totalPrice = orderHistory.reduce((total, order) => {
const selectedOption = options.find(option => option.id === order.optionId);
return total + (selectedOption ? detail.price * order.quantity : 0);
}, 0);

return (
<Wrapper>
Expand All @@ -45,17 +44,18 @@ export const OrderFormOrderInfo = ({ orderHistory }: Props) => {
<LabelText>상품명</LabelText>
<HeadingText>{detail.name}</HeadingText>
</ItemWrapper>
<ItemWrapper>
<LabelText>선택한 옵션</LabelText>
<HeadingText>{selectedOption ? selectedOption.name : '옵션 없음'}</HeadingText>
</ItemWrapper>
<ItemWrapper>
<LabelText>주문 수량</LabelText>
<HeadingText>{quantity}</HeadingText>
</ItemWrapper>
{orderHistory.map((order, index) => {
const selectedOption = options.find(option => option.id === order.optionId);
return (
<ItemWrapper key={index}>
<LabelText>선택한 옵션</LabelText>
<HeadingText>{selectedOption ? `${selectedOption.name} X ${order.quantity}개` : '옵션 없음'}</HeadingText>
</ItemWrapper>
);
})}
<ItemWrapper>
<LabelText>메시지</LabelText>
<HeadingText>{message}</HeadingText>
<HeadingText>{orderHistory[0].message}</HeadingText>
</ItemWrapper>
<ItemWrapper>
<LabelText>최종 결제금액</LabelText>
Expand Down
63 changes: 30 additions & 33 deletions src/components/features/Order/OrderForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { OrderFormOrderInfo } from './OrderInfo';
import { getBaseUrl } from '@/api/instance';
import { useAuth } from '@/provider/Auth';
import { orderHistorySessionStorage } from '@/utils/storage';
import { useEffect } from 'react';

type Props = {
orderHistory: OrderHistory[];
Expand All @@ -28,16 +27,9 @@ export const OrderForm = ({ orderHistory }: Props) => {
},
});

const { handleSubmit, watch } = methods;
const { handleSubmit } = methods;
const authInfo = useAuth();

const message = watch('message');
console.log('OrderForm에서 현재 메시지:', message);

useEffect(() => {
console.log('OrderForm useEffect - 메시지 변경:', message);
}, [message]);

const handleForm = async (values: OrderFormData) => {
const { errorMessage, isValid } = validateOrderForm(values);

Expand All @@ -48,17 +40,14 @@ export const OrderForm = ({ orderHistory }: Props) => {

const orders = orderHistorySessionStorage.get() as OrderHistory[];

console.log('유효성 검사 통과 후 값:', values);
console.log('선택된 옵션 및 수량:', orders);

const requests = orders.map(order => {
const requestBody = {
optionId: order.optionId,
quantity: order.quantity,
message: values.message,
};

console.log('서버로 전송하는 요청 데이터:', requestBody);
console.log('서버로 전송하는 요청 데이터:', JSON.stringify(requestBody, null, 2));

return fetch(`${getBaseUrl()}/api/orders`, {
method: 'POST',
Expand All @@ -69,29 +58,39 @@ export const OrderForm = ({ orderHistory }: Props) => {
body: JSON.stringify(requestBody),
credentials: 'include',
})
.then(response => {
.then(async response => {
if (!response.ok) {
throw new Error(`주문 실패: ${response.status}`);
const errorBody = await response.text();
console.error(`옵션 ID ${order.optionId} 주문 실패:`, response.status, errorBody);
return { success: false, optionId: order.optionId, error: errorBody };
}
return response.json();
})
.then(data => {
const data = await response.json();
console.log(`옵션 ID ${order.optionId} 주문 성공:`, data);
return data;
return { success: true, optionId: order.optionId, data };
})
.catch(error => {
console.error(`옵션 ID ${order.optionId} 주문 에러:`, error);
throw error;
return { success: false, optionId: order.optionId, error: error.message };
});
});

try {
const results = await Promise.all(requests);
alert('모든 주문이 완료되었습니다.');
console.log('모든 주문 결과:', results);
const successfulOrders = results.filter(result => result.success);
const failedOrders = results.filter(result => !result.success);

if (successfulOrders.length > 0) {
console.log('성공한 주문:', successfulOrders);
alert(`${successfulOrders.length}개의 주문이 완료되었습니다.`);
}

if (failedOrders.length > 0) {
console.error('실패한 주문:', failedOrders);
alert(`${failedOrders.length}개의 주문 중 오류가 발생했습니다.`);
}
} catch (error) {
console.error('주문 에러:', error);
alert('주문 중 에러가 발생했습니다.');
console.error('주문 처리 중 예외 발생:', error);
alert('주문 처리 중 예기치 않은 오류가 발생했습니다.');
}
};

Expand All @@ -105,15 +104,13 @@ export const OrderForm = ({ orderHistory }: Props) => {
return (
<FormProvider {...methods}>
<form action="" onSubmit={handleSubmit(handleForm)} onKeyDown={preventEnterKeySubmission}>
{orderHistory.map((order, index) => (
<SplitLayout key={index} sidebar={<OrderFormOrderInfo orderHistory={order} />}>
<Wrapper>
<OrderFormMessageCard />
<Spacing height={8} backgroundColor="#ededed" />
<GoodsInfo orderHistory={order} />
</Wrapper>
</SplitLayout>
))}
<SplitLayout sidebar={<OrderFormOrderInfo orderHistory={orderHistory} />}>
<Wrapper>
<OrderFormMessageCard />
<Spacing height={8} backgroundColor="#ededed" />
<GoodsInfo orderHistory={orderHistory} />
</Wrapper>
</SplitLayout>
</form>
</FormProvider>
);
Expand Down

0 comments on commit a876457

Please sign in to comment.