Skip to content

Commit

Permalink
Merge pull request #89 from Try-AngIe/feat/product
Browse files Browse the repository at this point in the history
feat: 상품을 수정 및 삭제할 수 있다.
  • Loading branch information
pogihae authored Jul 15, 2024
2 parents e9b7482 + bd86cde commit b52b728
Show file tree
Hide file tree
Showing 11 changed files with 219 additions and 223 deletions.
2 changes: 1 addition & 1 deletion client/src/apis/product.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const updateProduct = async (productId, productData) => {
};

// 상품 삭제
export const DeleteProduct = async productId => {
export const deleteProduct = async productId => {
try {
const res = await publicAxios.delete(`/v1/vendor/product/${productId}`);
return res;
Expand Down
72 changes: 48 additions & 24 deletions client/src/components/vendor/modal/ProductModal.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import BaseModal from '@/components/common/BaseModal';
import { createProduct } from '@/apis/product';
import { createProduct, deleteProduct, updateProduct } from '@/apis/product';
import InputWeb from '@/components/common/inputs/InputWeb';

const ProductModal = ({
Expand All @@ -15,6 +15,20 @@ const ProductModal = ({
const [productMemo, setProductMemo] = useState('');
const [contractNumber, setContractNumber] = useState('');

// 모달이 열릴 때마다 초기 상태 설정
useEffect(() => {
if (modalTitle === '상품 등록') {
setProductName(''); // 빈값
setProductPrice('');
setProductMemo('');
} else if (modalTitle === '상품 상세 정보' && productDetailData) {
setProductName(productDetailData.productName); // 기존 데이터값
setProductPrice(productDetailData.productPrice);
setProductMemo(productDetailData.productMemo);
}
}, [isShowModal, modalTitle, productDetailData]);

// 상품 등록 이벤트핸들러
const handleCreateProduct = async () => {
const productData = {
productName,
Expand All @@ -24,37 +38,45 @@ const ProductModal = ({

try {
await createProduct(productData);
// alert('상품을 등록했습니다.');
setIsShowModal(false);
alert('상품을 등록했습니다.');
setIsShowModal(false); // 상품 등록 후 모달 닫기
refreshProductList(); // 등록 후 상품 목록 리렌더링
} catch (err) {
alert('상품 등록에 실패했습니다.');
console.error('axiosProductDetail => ', err.response.data);
console.error('axiosProductCreate => ', err.response.data);
}
};

// 공백입력 막기
const handleKeyDown = e => {
e.key === ' ' && e.preventDefault();
};
// 상품 수정 이벤트핸들러
const handleUpdateProduct = async productId => {
const productData = {
productPrice,
productMemo,
};

// 모달이 열릴 때마다 초기 상태 설정
useEffect(() => {
if (modalTitle === '상품 등록') {
setProductName(''); // 빈값
setProductPrice('');
setProductMemo('');
} else if (modalTitle === '상품 상세 정보' && productDetailData) {
setProductName(productDetailData.productName); // 기존 데이터값
setProductPrice(productDetailData.productPrice);
setProductMemo(productDetailData.productMemo);
try {
await updateProduct(productDetailData.productId, productData);
alert('상품을 수정했습니다.');
setIsShowModal(false);
refreshProductList();
} catch (err) {
alert('상품 수정에 실패했습니다.');
console.error('axiosProductUpdate => ', err.response.data);
}
}, [isShowModal, modalTitle, productDetailData]);
};

const handleDelete = () => {
const isConfirmed = window.confirm('정말 삭제하시겠습니까?');
const handleDeleteProduct = async () => {
const isConfirmed = window.confirm('정말 삭제하시겠습니까?'); // 고도화 필요
if (isConfirmed) {
setIsShowModal(false);
try {
await deleteProduct(productDetailData.productId);
alert('상품을 삭제했습니다.');
setIsShowModal(false);
refreshProductList();
} catch (err) {
alert('상품 삭제에 실패했습니다.');
console.error('axiosProductDelete => ', err.response.data);
}
}
};

Expand Down Expand Up @@ -155,10 +177,12 @@ const ProductModal = ({
</button>
<button
className='bg-mint text-white px-7 py-2 rounded-md hover:bg-mint_hover h-10 w-28'
onClick={handleDelete}>
onClick={handleDeleteProduct}>
<span>삭제</span>
</button>
<button className='bg-mint text-white px-10 py-2 rounded-md hover:bg-mint_hover flex flex-row items-center w-36 justify-center'>
<button
className='bg-mint text-white px-10 py-2 rounded-md hover:bg-mint_hover flex flex-row items-center w-36 justify-center'
onClick={handleUpdateProduct}>
<span>수정</span>
</button>
</>
Expand Down
2 changes: 1 addition & 1 deletion client/src/pages/vendor/product/ProductListPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ const ProductListPage = () => {
className={`mx-1 px-3 py-1 border rounded w-24 h-8 flex items-center justify-center ${endPage >= totalPages ? 'invisible' : 'bg-white border border-white'}`}
onClick={() => handlePageGroupChange('next')}
disabled={endPage >= totalPages}>
{'이후'}&nbsp;&nbsp;&nbsp;{'>'}
{'다음'}&nbsp;&nbsp;&nbsp;{'>'}
</button>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
package kr.or.kosa.cmsplusmain.domain.messaging.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import kr.or.kosa.cmsplusmain.domain.messaging.dto.SmsVerifyDto;
import kr.or.kosa.cmsplusmain.domain.messaging.service.SmsService;
import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/vendor/auth")
public class MessagingController {

private final SmsService smsService;

// SMS 인증번호 요청
@PostMapping("/sms/sending")
public ResponseEntity<String> sendSms(@RequestBody SmsVerifyDto smsVerifyDto) {
try {
smsService.sendSmsCode(smsVerifyDto);
return ResponseEntity.ok("[SMS] 인증코드 전송 성공");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}

// SMS 인증번호 검사
@PostMapping("/sms/verification")
public ResponseEntity<String> SmsVerification(@RequestBody SmsVerifyDto smsVerifyDto) {
try {
smsService.verifySmsCode(smsVerifyDto);
return ResponseEntity.ok("[SMS] 인증 성공");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}

}
//package kr.or.kosa.cmsplusmain.domain.messaging.controller;
//
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import kr.or.kosa.cmsplusmain.domain.messaging.dto.SmsVerifyDto;
//import kr.or.kosa.cmsplusmain.domain.messaging.service.SmsService;
//import lombok.RequiredArgsConstructor;
//
//@RestController
//@RequiredArgsConstructor
//@RequestMapping("/api/v1/vendor/auth")
//public class MessagingController {
//
// private final SmsService smsService;
//
// // SMS 인증번호 요청
// @PostMapping("/sms/sending")
// public ResponseEntity<String> sendSms(@RequestBody SmsVerifyDto smsVerifyDto) {
// try {
// smsService.sendSmsCode(smsVerifyDto);
// return ResponseEntity.ok("[SMS] 인증코드 전송 성공");
// } catch (Exception e) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
// }
// }
//
// // SMS 인증번호 검사
// @PostMapping("/sms/verification")
// public ResponseEntity<String> SmsVerification(@RequestBody SmsVerifyDto smsVerifyDto) {
// try {
// smsService.verifySmsCode(smsVerifyDto);
// return ResponseEntity.ok("[SMS] 인증 성공");
// } catch (Exception e) {
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
// }
// }
//
//}
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
package kr.or.kosa.cmsplusmain.domain.messaging.repository;

import java.time.Duration;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
public class SmsRepository {

// Redis 데이터 설정
private final String PREFIX = "SMS-"; // 저장되는 키 값은 "SMS-01011111111" 형태
private final int LIMIT_TIME = 5 * 60; // 300초(5분)동안 캐싱

private final StringRedisTemplate redisTemplate;

public void createSmsVerification(String phone, String certificationNumber) {
redisTemplate.opsForValue()
.set(PREFIX + phone, certificationNumber, Duration.ofSeconds(LIMIT_TIME));
}

public String getSmsVerification(String phone) {
return redisTemplate.opsForValue().get(PREFIX + phone);
}

public void removeSmsCertification(String phone) {
redisTemplate.delete(PREFIX + phone);
}

public boolean hasKey(String phone) {
return redisTemplate.hasKey(PREFIX + phone);
}

}
//package kr.or.kosa.cmsplusmain.domain.messaging.repository;
//
//import java.time.Duration;
//
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.stereotype.Repository;
//
//import lombok.RequiredArgsConstructor;
//
//@Repository
//@RequiredArgsConstructor
//public class SmsRepository {
//
// // Redis 데이터 설정
// private final String PREFIX = "SMS-"; // 저장되는 키 값은 "SMS-01011111111" 형태
// private final int LIMIT_TIME = 5 * 60; // 300초(5분)동안 캐싱
//
// private final StringRedisTemplate redisTemplate;
//
// public void createSmsVerification(String phone, String certificationNumber) {
// redisTemplate.opsForValue()
// .set(PREFIX + phone, certificationNumber, Duration.ofSeconds(LIMIT_TIME));
// }
//
// public String getSmsVerification(String phone) {
// return redisTemplate.opsForValue().get(PREFIX + phone);
// }
//
// public void removeSmsCertification(String phone) {
// redisTemplate.delete(PREFIX + phone);
// }
//
// public boolean hasKey(String phone) {
// return redisTemplate.hasKey(PREFIX + phone);
// }
//
//}
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
package kr.or.kosa.cmsplusmain.domain.messaging.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import kr.or.kosa.cmsplusmain.domain.messaging.dto.SmsVerifyDto;
import kr.or.kosa.cmsplusmain.domain.messaging.repository.SmsRepository;
import kr.or.kosa.cmsplusmain.util.SmsUtil;
import lombok.RequiredArgsConstructor;

@Service
@Transactional
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {

private final SmsUtil smsUtil;
private final SmsRepository smsRepository;

public void sendSmsCode(SmsVerifyDto smsVerifyDto) {
String to = smsVerifyDto.getPhone();
int randomNumber = (int)(Math.random() * 9000) + 1000;
String certificationNumber = String.valueOf(randomNumber);
smsUtil.sendSms(to, certificationNumber);
smsRepository.createSmsVerification(to, certificationNumber);
}

public void verifySmsCode(SmsVerifyDto smsVerifyDto) {
if (!isVerify(smsVerifyDto)) {
throw new IllegalArgumentException("[SMS] 인증번호 불일치");
}
smsRepository.removeSmsCertification(smsVerifyDto.getPhone());
}

public boolean isVerify(SmsVerifyDto smsVerifyDto) {
return smsRepository.hasKey(smsVerifyDto.getPhone()) &&
smsRepository.getSmsVerification(smsVerifyDto.getPhone())
.equals(smsVerifyDto.getSmsVerifyCode());
}

}
//package kr.or.kosa.cmsplusmain.domain.messaging.service;
//
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import kr.or.kosa.cmsplusmain.domain.messaging.dto.SmsVerifyDto;
//import kr.or.kosa.cmsplusmain.domain.messaging.repository.SmsRepository;
//import kr.or.kosa.cmsplusmain.util.SmsUtil;
//import lombok.RequiredArgsConstructor;
//
//@Service
//@Transactional
//@RequiredArgsConstructor
//public class SmsServiceImpl implements SmsService {
//
// private final SmsUtil smsUtil;
// private final SmsRepository smsRepository;
//
// public void sendSmsCode(SmsVerifyDto smsVerifyDto) {
// String to = smsVerifyDto.getPhone();
// int randomNumber = (int)(Math.random() * 9000) + 1000;
// String certificationNumber = String.valueOf(randomNumber);
// smsUtil.sendSms(to, certificationNumber);
// smsRepository.createSmsVerification(to, certificationNumber);
// }
//
// public void verifySmsCode(SmsVerifyDto smsVerifyDto) {
// if (!isVerify(smsVerifyDto)) {
// throw new IllegalArgumentException("[SMS] 인증번호 불일치");
// }
// smsRepository.removeSmsCertification(smsVerifyDto.getPhone());
// }
//
// public boolean isVerify(SmsVerifyDto smsVerifyDto) {
// return smsRepository.hasKey(smsVerifyDto.getPhone()) &&
// smsRepository.getSmsVerification(smsVerifyDto.getPhone())
// .equals(smsVerifyDto.getSmsVerifyCode());
// }
//
//}
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@ public class CardPaymentMethod extends PaymentMethodInfo {
private String cardNumber;

@Comment("카드 유효기간 월")
@Column(name = "card_info_validity_month", nullable = false)
@Column(name = "card_info_validity_month", nullable = true)
// @NotNull
private int cardMonth;

@Comment("카드 유효기간 년")
@Column(name = "card_info_validity_year", nullable = false)
@Column(name = "card_info_validity_year", nullable = true)
private int cardYear;

@Comment("카드 소유주명")
Expand Down
Loading

0 comments on commit b52b728

Please sign in to comment.