Skip to content

Commit

Permalink
Update Stock
Browse files Browse the repository at this point in the history
  • Loading branch information
in27sung committed Dec 17, 2024
1 parent fc00541 commit b9561e6
Show file tree
Hide file tree
Showing 19 changed files with 803 additions and 450 deletions.
251 changes: 124 additions & 127 deletions stockMate/src/main/java/com/stockm8/controller/ProductController.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ public class ProductController {

@Autowired
private ProductService productService;

@Autowired
private UserService userService;

@Autowired
private CategoryService categoryService;

Expand All @@ -51,161 +51,158 @@ public class ProductController {
@GetMapping("/register")
public String productRegistGET(Model model, HttpServletRequest request) throws Exception {
logger.info("productRegistGET() 호출");
// 세션에서 userId 가져오기
HttpSession session = request.getSession(false);
Long userId = (session != null) ? (Long)session.getAttribute("userId") : null;
// userId로 사용자 정보 조회
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();
// DB에서 카테고리 정보 가져오기
List<CategoryVO> categoryList = categoryService.getCategoriesByBusinessId(businessId);

// 모델에 데이터 추가
model.addAttribute("categoryList", categoryList);

// 창고 정보와 카테고리 정보가 없으면 추가 버튼 표시를 위한 플래그 설정
model.addAttribute("hasCategories", !categoryList.isEmpty());

// 세션에서 userId 가져오기
HttpSession session = request.getSession(false);
Long userId = (session != null) ? (Long) session.getAttribute("userId") : null;

// userId로 사용자 정보 조회
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();

// DB에서 카테고리 정보 가져오기
List<CategoryVO> categoryList = categoryService.getCategoriesByBusinessId(businessId);

// 모델에 데이터 추가
model.addAttribute("categoryList", categoryList);

// 창고 정보와 카테고리 정보가 없으면 추가 버튼 표시를 위한 플래그 설정
model.addAttribute("hasCategories", !categoryList.isEmpty());

logger.info("연결된 뷰페이지(/product/register.jsp) 이동");
return "product/register"; // 상품 등록 페이지로 이동
}

// 상품 등록 처리
@PostMapping("/register")
public String productRegistPOST(ProductVO product,
@SessionAttribute("userId") Long userId,
HttpServletRequest request,
RedirectAttributes rttr) throws Exception {
public String productRegistPOST(ProductVO product, @SessionAttribute("userId") Long userId,
HttpServletRequest request, RedirectAttributes rttr) throws Exception {
logger.info("productRegistPOST() 호출");

// 전달정보(파라미터) 확인
logger.info("product: {}", product);
// 사용자 정보 및 회사정보 가져오기
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();
logger.info("Business ID for user: {}", businessId);
// user의 businessId 설정
product.setBusinessId(user.getBusinessId());
// DB등록처리 / Service -> DAO -> mapper(sql 호출)

// 사용자 정보 및 회사정보 가져오기
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();
logger.info("Business ID for user: {}", businessId);

// user의 businessId 설정
product.setBusinessId(user.getBusinessId());

// DB등록처리 / Service -> DAO -> mapper(sql 호출)
productService.registerProduct(product);

// DB insert 후 생성된 productId PK
int productId = product.getProductId();

logger.info("연결된 뷰페이지(/product/detail.jsp) 이동");
return "redirect:/product/detail?productId=" + productId;
}

// QR코드 등록 처리
@GetMapping("/generateQR")
public String generateQRGET(@RequestParam("productId") int productId, RedirectAttributes rttr) throws Exception {
logger.info("generateQR() 호출");
logger.info("전송된 productId: {}", productId);

if (productId == 0) {
rttr.addFlashAttribute("errorMessage", "유효한 상품 ID가 필요합니다.");
return "redirect:/product/detail?productId=" + productId;
}
// 상품 정보 가져오기
ProductVO product = productService.getProductByID(productId);
if (product == null) {
rttr.addFlashAttribute("errorMessage", "상품 정보를 찾을 수 없습니다.");
return "redirect:/product/detail?productId=" + productId;
}

// QR 코드 생성 (예외 발생 시 @ControllerAdvice에서 처리)
productService.generateQRCode(productId);
rttr.addFlashAttribute("successMessage", "QR 코드가 성공적으로 생성되었습니다. (상품 ID: " + productId + ")");
return "redirect:/product/detail?productId=" + productId;
logger.info("generateQR() 호출");
logger.info("전송된 productId: {}", productId);

if (productId == 0) {
rttr.addFlashAttribute("errorMessage", "유효한 상품 ID가 필요합니다.");
return "redirect:/product/detail?productId=" + productId;
}

// 상품 정보 가져오기
ProductVO product = productService.getProductByID(productId);
if (product == null) {
rttr.addFlashAttribute("errorMessage", "상품 정보를 찾을 수 없습니다.");
return "redirect:/product/detail?productId=" + productId;
}

// QR 코드 생성 (예외 발생 시 @ControllerAdvice에서 처리)
productService.generateQRCode(productId);
rttr.addFlashAttribute("successMessage", "QR 코드가 성공적으로 생성되었습니다. (상품 ID: " + productId + ")");
return "redirect:/product/detail?productId=" + productId;
}

// http://localhost:8088/product/downloadQr
// QR코드 다운로드 처리
@GetMapping("/downloadQr")
public void downloadQrCodeGET(
@RequestParam("productId") int productId,
HttpServletResponse response) throws Exception {

// 상품 정보 가져오기
ProductVO product = productService.getProductByID(productId);
if (product == null || product.getProductQrCodePath() == null) {
throw new IllegalArgumentException("QR 코드가 존재하지 않습니다.");
}

// QR 코드 파일 경로
File qrCodeFile = new File(product.getProductQrCodePath());
if (!qrCodeFile.exists()) {
throw new IllegalArgumentException("QR 코드 파일이 존재하지 않습니다.");
}

// 파일명 인코딩 (한글 처리 포함)
String encodedFileName = URLEncoder.encode(qrCodeFile.getName(), "UTF-8").replaceAll("\\+", "%20");

// 파일 다운로드 설정
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
response.setContentLengthLong(qrCodeFile.length());

// 파일 데이터 출력
try (FileInputStream fileInputStream = new FileInputStream(qrCodeFile);
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
}
public void downloadQrCodeGET(@RequestParam("productId") int productId, HttpServletResponse response)
throws Exception {

// 상품 정보 가져오기
ProductVO product = productService.getProductByID(productId);
if (product == null || product.getProductQrCodePath() == null) {
throw new IllegalArgumentException("QR 코드가 존재하지 않습니다.");
}

// QR 코드 파일 경로
File qrCodeFile = new File(product.getProductQrCodePath());
if (!qrCodeFile.exists()) {
throw new IllegalArgumentException("QR 코드 파일이 존재하지 않습니다.");
}

// 파일명 인코딩 (한글 처리 포함)
String encodedFileName = URLEncoder.encode(qrCodeFile.getName(), "UTF-8").replaceAll("\\+", "%20");

// 파일 다운로드 설정
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
response.setContentLengthLong(qrCodeFile.length());

// 파일 데이터 출력
try (FileInputStream fileInputStream = new FileInputStream(qrCodeFile);
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
}
}

// http://localhost:8088/product/detail
// 상품 상세 정보 페이지
@GetMapping("/detail")
public String detailGET(@RequestParam("productId") int productId, Model model) throws Exception {
// 상품 상세 정보 조회
ProductVO product = productService.getProductByID(productId);
if (product == null) {
throw new IllegalArgumentException("상품 정보를 찾을 수 없습니다. productId: " + productId);
}

// 카테고리명 조회
String categoryName = categoryService.getCategoryNameById(product.getCategoryId());
if (categoryName == null) {
categoryName = "알 수 없음"; // 카테고리가 없을 경우 기본값 설정
}

// 뷰(JSP)에서 EL로 접근할 수 있도록 Model에 상품 및 카테고리 정보 등록
model.addAttribute("product", product);
model.addAttribute("categoryName", categoryName);

logger.info("연결된 뷰페이지(/product/detail.jsp) 이동");
return "product/detail"; // JSP 파일 경로
// 상품 상세 정보 조회
ProductVO product = productService.getProductByID(productId);
if (product == null) {
throw new IllegalArgumentException("상품 정보를 찾을 수 없습니다. productId: " + productId);
}

// 카테고리명 조회
String categoryName = categoryService.getCategoryNameById(product.getCategoryId());
if (categoryName == null) {
categoryName = "알 수 없음"; // 카테고리가 없을 경우 기본값 설정
}

// 뷰(JSP)에서 EL로 접근할 수 있도록 Model에 상품 및 카테고리 정보 등록
model.addAttribute("product", product);
model.addAttribute("categoryName", categoryName);

logger.info("연결된 뷰페이지(/product/detail.jsp) 이동");
return "product/detail"; // JSP 파일 경로
}

// http://localhost:8088/product/list
@GetMapping("/list")
public String listProductsGET(HttpServletRequest request, Model model) throws Exception{
// 세션에서 userId 가져오기
HttpSession session = request.getSession(false);
Long userId = (session != null) ? (Long)session.getAttribute("userId") : null;
// userId로 사용자 정보 조회
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();

// 비즈니스 ID로 상품 리스트 조회
List<ProductVO> products = productService.getProductsWithQRCode(businessId);

// 모델에 데이터 추가
model.addAttribute("products", products);

return "product/list"; // /WEB-INF/views/product/list.jsp로 매핑
}
@GetMapping("/list")
public String listProductsGET(HttpServletRequest request, Model model) throws Exception {
// 세션에서 userId 가져오기
HttpSession session = request.getSession(false);
Long userId = (session != null) ? (Long) session.getAttribute("userId") : null;

// userId로 사용자 정보 조회
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();

// 비즈니스 ID로 상품 리스트 조회
List<ProductVO> products = productService.getProductsWithQRCode(businessId);

// 모델에 데이터 추가
model.addAttribute("products", products);

return "product/list"; // /WEB-INF/views/product/list.jsp로 매핑
}
}
67 changes: 32 additions & 35 deletions stockMate/src/main/java/com/stockm8/controller/StockController.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.stockm8.domain.dto.StockDTO;
import com.stockm8.domain.vo.StockVO;
import com.stockm8.domain.vo.UserVO;
import com.stockm8.domain.vo.WarehouseVO;
Expand Down Expand Up @@ -79,39 +81,34 @@ public String registerStockPost(@ModelAttribute StockVO stock,

// 재고 목록 조회
// http://localhost:8088/stock/list
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String getStockList(@SessionAttribute("userId") Long userId, Model model,
@RequestParam(required = false) Integer warehouseId,
@RequestParam(required = false) String categoryName,
@RequestParam(required = false) Integer minStock,
@RequestParam(required = false) Integer maxStock,
@RequestParam(required = false, defaultValue = "desc") String sortOrder) throws Exception {
logger.info("getStockList 호출");

// 사용자 정보 조회
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();

// 창고 목록 조회
List<WarehouseVO> warehouseList = warehouseService.getWarehousesByBusinessId(businessId);
logger.info("조회된 창고 목록: {}", warehouseList.size());

// 창고명과 카테고리명 정보 제공
model.addAttribute("warehouseList", warehouseList);
model.addAttribute("categoryList", stockService.getCategoryList());

// 재고 리스트 조회
FilterCriteria criteria = new FilterCriteria(warehouseId, categoryName, minStock, maxStock, sortOrder, businessId);
List<StockVO> stockList = stockService.getStockList(criteria, sortOrder);
model.addAttribute("stockList", stockList);

// 필터링된 파라미터들을 모델에 추가
model.addAttribute("warehouseId", warehouseId);
model.addAttribute("categoryName", categoryName);
model.addAttribute("minStock", minStock);
model.addAttribute("maxStock", maxStock);
model.addAttribute("sortOrder", sortOrder);

return "/stock/list";
}
@GetMapping("/list")
public String getStockList(
@SessionAttribute("userId") Long userId,
@RequestParam(required = false, defaultValue = "updated_at") String sortColumn,
@RequestParam(required = false, defaultValue = "desc") String sortOrder,
Model model) throws Exception {

logger.info(">>> 재고 리스트 요청 sortColumn: {}, sortOrder: {}", sortColumn, sortOrder);

// 사용자 정보 조회
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();

// 창고 및 카테고리 리스트 추가
List<WarehouseVO> warehouseList = warehouseService.getWarehousesByBusinessId(businessId);
model.addAttribute("warehouseList", warehouseList);
model.addAttribute("categoryList", stockService.getCategoryList());

// 재고 리스트 조회
List<StockDTO> stockList = stockService.getStockList(businessId, sortColumn, sortOrder);
model.addAttribute("stockList", stockList);

// 정렬 정보 추가
model.addAttribute("sortColumn", sortColumn);
model.addAttribute("sortOrder", sortOrder);

logger.info("조회된 재고 수: {}", stockList.size());

return "/stock/list";
}
}
Loading

0 comments on commit b9561e6

Please sign in to comment.