KDT-IaaS-Class-One-Group / KDT-IaaS-1team-ERP

0 stars 2 forks source link

user - 주문하기 - enter 입력시 수량 증가 #90

Closed csm009177 closed 7 months ago

csm009177 commented 7 months ago

'use client'

import { useEffect, useState } from 'react'; import { useSearchParams } from 'next/navigation'; import base64, { decode } from 'js-base64'; import Addr, { IAddr } from '@/app/ui/addressSearch';

const getUsernameSomehow = () => { const token = localStorage.getItem('token');

if (token) { try { const payload = token.split('.')[1]; const decodedPayload = decode(payload); const payloadObject = JSON.parse(decodedPayload); return payloadObject.username; } catch (error) { console.error('토큰 파싱 오류:', error); } }

return null; };

export default function Purchase() { const username = getUsernameSomehow(); const [productsInfo, setProductsInfo] = useState< { name: string; price: number; productKey: number; quantity: number }[]

([]); const [totalPrice, setTotalPrice] = useState(0); const [selectedAddress, setSelectedAddress] = useState({ address: '', zonecode: '' }); const searchParams = useSearchParams();

useEffect(() => { const params = Object.fromEntries(searchParams); if (params.productName && params.price && params.productKey && params.quantity) { const productList = params.productName.split(','); const productKeyList = params.productKey.split(','); const priceList = params.price.split(',').map((price: string) => parseInt(price, 10)); const quantityList = params.quantity.split(',').map((quantity: string) => parseInt(quantity, 10));

  const productsWithPrices = productList.map((productName, index) => ({
    name: productName,
    price: priceList[index],
    productKey: parseInt(productKeyList[index], 10),
    quantity: quantityList[index],
  }));

  const totalPriceSum = calculateTotalPrice(productsWithPrices);

  setProductsInfo(productsWithPrices);
  setTotalPrice(totalPriceSum);
}

}, [searchParams]);

const handleIncrement = (index: number) => { setProductsInfo((prevProducts) => { const updatedProducts = [...prevProducts]; updatedProducts[index] = { ...updatedProducts[index], quantity: updatedProducts[index].quantity + 1, }; setTotalPrice(calculateTotalPrice(updatedProducts)); return updatedProducts; }); };

const handleDecrement = (index: number) => { setProductsInfo((prevProducts) => { const updatedProducts = [...prevProducts]; if (updatedProducts[index].quantity > 1) { updatedProducts[index] = { ...updatedProducts[index], quantity: updatedProducts[index].quantity - 1, }; setTotalPrice(calculateTotalPrice(updatedProducts)); } return updatedProducts; }); };

const calculateTotalPrice = ( products: { name: string; price: number; quantity: number }[] ) => { return products.reduce( (acc, product) => acc + product.price * product.quantity, 0 ); };

const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); const fullAddress = ${selectedAddress.address} ${selectedAddress.detailedAddress}.trim(); const data = { username: username, customer: e.currentTarget.customer.value, receiver: e.currentTarget.receiver.value, phoneNumber: e.currentTarget.phoneNumber.value, address: fullAddress, price: totalPrice, productName: productsInfo.map((product) => product.name).join(','), productKey: productsInfo .map((product) => product.productKey) .join(','), quantity: productsInfo.map((product) => product.quantity).join(','), };

try {
  const response = await fetch('/createOrder', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });

  if (response.ok) {
    console.log('주문이 성공적으로 생성되었습니다.');
    alert('주문 완료');
    window.location.href = '/';
  } else {
    console.error('주문 생성 실패');
    alert('잔액이 부족합니다');
  }
} catch (error) {
  console.error('주문 생성 중 에러:', error);
}

};

const handlePhoneNumberChange = (e: React.ChangeEvent) => { let value = e.target.value;

// 숫자와 - 외의 문자는 제거
value = value.replace(/[^\d]/g, '');

// 길이 제한
if (value.length > 11) {
  value = value.slice(0, 11); // 11자리까지만 유지
}

// 원하는 형식으로 변환
if (value.length >= 3 && value.length <= 7) {
  value = value.replace(/(\d{3})(\d{1,4})/, "$1-$2");
} else if (value.length > 7) {
  value = value.replace(/(\d{3})(\d{4})(\d{1,4})/, "$1-$2-$3");
}

// 직접 input 요소의 value 속성을 업데이트
(e.target as HTMLInputElement).value = value;

};

const handleAddressSelect = (data: IAddr) => { setSelectedAddress(data); };

const handleDetailedAddressChange = (e: React.ChangeEvent) => { const { value } = e.target; setSelectedAddress((prevAddress) => ({ ...prevAddress, detailedAddress: value })); };

return (

주문하기

배송정보

    {productsInfo.map((product, index) => (

    상품명: {product.name}

    수량: {product.quantity}

    금액: {product.price * product.quantity}원

    ))}
{ if (e.key === 'Enter') { e.preventDefault(); } }} required />
{ if (e.key === 'Enter') { e.preventDefault(); } }} required />
{ if (e.key === 'Enter') { e.preventDefault(); } }} required />
{ if (e.key === 'Enter') { e.preventDefault(); } }} readOnly />
{ if (e.key === 'Enter') { e.preventDefault(); } }} required />
    <div className="flex justify-end mt-4">
      <div className="w-1/2 border border-gray-300 px-3 py-2 text-base rounded-md">
        <div className="flex justify-end items-center mb-4">
          <p className="text-xl mb-2 mr-auto">총 가격 : {totalPrice}원</p>
          <button
            className="bg-blue-500 text-white px-4 py-2 rounded-md"
            type="submit"
          >
            결제하기
          </button>
        </div>
      </div>
    </div>
  </form>
</div>

); }