Skip to content

Commit

Permalink
Merge pull request #129 from in27sung/category_09
Browse files Browse the repository at this point in the history
진짜 끝 데이터 잘 담기도록 수정했습니다.
  • Loading branch information
mingming-01 authored Dec 11, 2024
2 parents 70109e6 + 887dd16 commit 881d14e
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ public class CategoryController {
private static final Logger logger = LoggerFactory.getLogger(CategoryController.class);

@Inject
private CategoryService cService;
private CategoryService categoryService;

@Inject
private UserService uService;
private UserService userService;

// http://localhost:8088/category/register
// 카테고리 등록 페이지 호출 (GET)
Expand All @@ -43,12 +43,12 @@ public String registerCategoryGET(Model model, HttpServletRequest request) throw
logger.info("session: {}", userId);

// userId로 사용자 정보 조회
UserVO user = uService.getUserById(userId);
UserVO user = userService.getUserById(userId);
int businessId = user.getBusinessId();
logger.info("businessId: {}", businessId);

// 필요한 데이터 (예: 상위 카테고리 목록 등) 전달
List<CategoryVO> categoryList = cService.getCategoriesByBusinessId(businessId);
List<CategoryVO> categoryList = categoryService.getCategoriesByBusinessId(businessId);
model.addAttribute("categoryList", categoryList);
logger.info("Category List: {}", categoryList);

Expand All @@ -58,19 +58,21 @@ public String registerCategoryGET(Model model, HttpServletRequest request) throw

// 카테고리 등록 처리 (POST)
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerCategoryPOST(CategoryVO vo, HttpServletRequest request) throws Exception {
logger.info("registerCategoryPOST(CategoryVO vo, HttpServletRequest request) 실행");
public String registerCategoryPOST(CategoryVO category, HttpServletRequest request) throws Exception {
logger.info("registerCategoryPOST(CategoryVO category, HttpServletRequest request) 실행");

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

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

// 서비스 호출: 부모 카테고리 체크와 카테고리 등록을 서비스에서 처리
cService.registerCategoryWithParentCheck(vo);
categoryService.registerCategoryWithParentCheck(category);

// 등록 후 목록 페이지로 리다이렉트
return "redirect:/category/list";
Expand All @@ -82,7 +84,7 @@ public String registerCategoryPOST(CategoryVO vo, HttpServletRequest request) th
public String listCategoryGET(Model model) throws Exception {
logger.info("listCategoryGET(Model model) 호출");
// 카테고리 목록 조회
List<CategoryVO> categories = cService.getAllCategories();
List<CategoryVO> categories = categoryService.getAllCategories();

// JSP로 데이터 전달
model.addAttribute("categories", categories);
Expand All @@ -95,29 +97,29 @@ public String editCategoryGET(@RequestParam("categoryId") int categoryId, Model
logger.info("editCategoryGET(@RequestParam(\"categoryId\") int categoryId, Model model) 호출");

// 카테고리와 상위 카테고리 정보 가져오기
CategoryVO vo = cService.getCategoryWithParents(categoryId);
CategoryVO vo = categoryService.getCategoryWithParents(categoryId);
model.addAttribute("category", vo);

// 상위 카테고리 정보 (부모 카테고리 리스트 가져오기)
List<CategoryVO> parentCategories = cService.getParentCategories(); // 부모 카테고리 리스트를 가져오기
List<CategoryVO> parentCategories = categoryService.getParentCategories(); // 부모 카테고리 리스트를 가져오기
model.addAttribute("parentCategories", parentCategories);

return "category/edit";
}

// 카테고리 수정 처리 (POST)
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String editCategoryPOST(@ModelAttribute CategoryVO vo) throws Exception {
public String editCategoryPOST(@ModelAttribute CategoryVO category) throws Exception {
logger.info("editCategoryPOST(@ModelAttribute CategoryVO vo) 실행");

// 부모 카테고리가 비어 있으면 null로 처리
if (vo.getParentId() != null && vo.getParentId().equals("")) {
vo.setParentId(null);
logger.info("부모 카테고리가 비어있어 null로 설정됨, categoryId: {}", vo.getCategoryId());
if (category.getParentId() != null && category.getParentId().equals("")) {
category.setParentId(null);
logger.info("부모 카테고리가 비어있어 null로 설정됨, categoryId: {}", category.getCategoryId());
}
// 카테고리 수정
cService.updateCategory(vo);
logger.info("카테고리 수정 완료, categoryId: {}", vo.getCategoryId());
categoryService.updateCategory(category);
logger.info("카테고리 수정 완료, categoryId: {}", category.getCategoryId());

return "redirect:/category/list"; // 수정 후 목록 페이지로 리다이렉트
}
Expand All @@ -126,7 +128,7 @@ public String editCategoryPOST(@ModelAttribute CategoryVO vo) throws Exception {
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String deleteCategoryGET(@RequestParam("categoryId") int categoryId, Model model) throws Exception {
// 삭제할 카테고리 정보 가져오기
CategoryVO category = cService.getCategoryWithParents(categoryId);
CategoryVO category = categoryService.getCategoryWithParents(categoryId);
model.addAttribute("category", category);

return "category/delete";
Expand All @@ -136,7 +138,7 @@ public String deleteCategoryGET(@RequestParam("categoryId") int categoryId, Mode
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String deleteCategoryPOST(@RequestParam("categoryId") int categoryId) throws Exception {
// 카테고리 삭제 처리
cService.deleteCategory(categoryId);
categoryService.deleteCategory(categoryId);

return "redirect:/category/list";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ public boolean existsById(int categoryId, int businessId) {
return count != null && count > 0;
}


// 카테고리 수정
@Override
public void updateCategory(CategoryVO category) throws Exception {
Expand All @@ -89,7 +88,7 @@ public void deleteCategory(int categoryId) throws Exception {
sqlSession.update(NAMESPACE + "deleteCategory", categoryId);
}

// 부모 카테고리만 조회
// 부모 카테고리만 조회
@Override
public List<CategoryVO> selectParentCategories() throws Exception {
return sqlSession.selectList(NAMESPACE + "selectParentCategories");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
public interface CategoryService {

// 카테고리 등록
public void addCategory(CategoryVO vo) throws Exception;
public void addCategory(CategoryVO category) throws Exception;

// 부모 카테고리 체크 후 카테고리 등록 (새 부모 카테고리 추가 여부 확인)
public void registerCategoryWithParentCheck(CategoryVO vo) throws Exception;
public void registerCategoryWithParentCheck(CategoryVO category) throws Exception;

// 카테고리와 상위 카테고리 목록 조회
public CategoryVO getCategoryWithParents(int categoryId) throws Exception;
Expand All @@ -31,7 +31,7 @@ public interface CategoryService {
public void getCategoryNameById(int categoryId) throws Exception;

// 카테고리 수정
public void updateCategory(CategoryVO vo) throws Exception;
public void updateCategory(CategoryVO category) throws Exception;

// 카테고리 삭제
public void deleteCategory(int categoryId) throws Exception;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,51 +20,49 @@ public class CategoryServiceImpl implements CategoryService {
@Inject
private CategoryDAO categoryDAO;


// 카테고리 등록
@Override
public void addCategory(CategoryVO vo) throws Exception {
logger.info("CategoryVO 내용: {}", vo);
// vo가 null이면 예외 처리
if (vo == null) {
public void addCategory(CategoryVO category) throws Exception {
logger.info("CategoryVO 내용: {}", category);

// category가 null일 경우 예외 처리
if (category == null) {
throw new IllegalArgumentException("CategoryVO 객체는 null일 수 없습니다.");
}

logger.info("카테고리 등록 실행");

// 카테고리 이름 중복 체크
if (checkCategoryNameExists(vo.getCategoryName())) {
if (checkCategoryNameExists(category.getCategoryName())) {
throw new IllegalArgumentException("이미 존재하는 카테고리 이름입니다.");
}

// businessId가 null이거나 0이면 기본값 1로 설정
if (vo.getBusinessId() == null || vo.getBusinessId() == 0) {
vo.setBusinessId(1); // businessId가 null이거나 0일 경우 기본값 설정
// businessId가 null이라면 예외 처리 (필수 값)
if (category.getBusinessId() == null) {
throw new IllegalArgumentException("businessId는 null일 수 없습니다.");
}

// 상위 카테고리가 없으면 대분류, 있으면 소분류로 설정
if (vo.getParentId() == null || vo.getParentId() == 0) {
vo.setParentId(null); // 부모 카테고리가 없는 경우 대분류
vo.setLevel(1); // 대분류
// parentId에 따라 레벨 지정
if (category.getParentId() == null) {
// 상위 카테고리가 없으므로 대분류로 설정
category.setLevel(1);
} else {
vo.setLevel(2); // 부모 카테고리가 있는 경우 소분류
// 상위 카테고리가 존재하면 해당 상위 카테고리의 레벨을 기반으로 설정
CategoryVO parentCategory = categoryDAO.selectCategoryById(category.getParentId());
if (parentCategory == null) {
throw new IllegalArgumentException("존재하지 않는 상위 카테고리 ID입니다.");
}
category.setLevel(parentCategory.getLevel() + 1); // 상위 레벨 + 1
}

// createdAt이 null이라면 현재 시간을 생성 시간으로 설정
if (vo.getCreatedAt() == null) {
vo.setCreatedAt(new Timestamp(System.currentTimeMillis()));
// createdAt 설정
if (category.getCreatedAt() == null) {
category.setCreatedAt(new Timestamp(System.currentTimeMillis()));
}

logger.info("DAO의 카테고리 등록 메서드 호출");

// 카테고리 등록
categoryDAO.insertCategory(vo); // 카테고리 등록 후 categoryId가 설정됨

logger.info("카테고리 등록 후 Category ID: " + vo.getCategoryId()); // 추가 로그로 categoryId 확인

// 부모 카테고리가 있는 경우, 하위 카테고리들의 부모 ID를 동일하게 갱신
if (vo.getParentId() != null) {
// 부모 카테고리 ID를 기준으로 해당 하위 카테고리들의 parentId를 갱신
categoryDAO.updateSubCategoryParentId(vo.getParentId(), vo.getCategoryId());
}
// DAO의 insertCategory 호출
categoryDAO.insertCategory(category); // 카테고리 등록 후 categoryId가 설정됨
logger.info("카테고리 등록 후 Category ID: " + category.getCategoryId()); // 추가 로그로 categoryId 확인
}

// 카테고리 목록 조회
Expand All @@ -84,25 +82,27 @@ public boolean checkCategoryNameExists(String categoryName) throws Exception {

// 카테고리 수정
@Override
public void updateCategory(CategoryVO vo) throws Exception {
vo.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
categoryDAO.updateCategory(vo);
public void updateCategory(CategoryVO category) throws Exception {
category.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
categoryDAO.updateCategory(category);
}

// 카테고리 및 상위 카테고리 정보 조회
@Override
public CategoryVO getCategoryWithParents(int categoryId) throws Exception {
// 카테고리 정보 조회
CategoryVO vo = categoryDAO.selectCategoryById(categoryId);
CategoryVO category = categoryDAO.selectCategoryById(categoryId);

// parentId가 null이면 부모 카테고리로 처리
if (vo.getParentId() == null) {
vo.setLevel(1); // 부모 카테고리로 설정
if (category.getParentId() != null) {
CategoryVO parentCategory = categoryDAO.selectCategoryById(category.getParentId());
if (parentCategory != null) {
category.setLevel(parentCategory.getLevel() + 1); // 부모 레벨 + 1
}
} else {
vo.setLevel(2); // 자식 카테고리로 설정
category.setLevel(1); // 부모가 없으면 레벨 1
}

return vo; // 부모 카테고리와 상관없이 카테고리 정보만 반환
return category; // 부모 카테고리와 상관없이 카테고리 정보만 반환
}

// 특정 사업자(businessId) 소속의 카테고리 목록을 조회(삭제하지 마세요)
Expand All @@ -127,18 +127,22 @@ public void deleteCategory(int categoryId) throws Exception {
}

@Override
public void registerCategoryWithParentCheck(CategoryVO vo) throws Exception {
public void registerCategoryWithParentCheck(CategoryVO category) throws Exception {
// 부모 카테고리 없을 경우 대분류 처리
if (vo.getParentId() == null || vo.getParentId() == 0) {
vo.setParentId(null); // 부모 카테고리 설정되지 않음
vo.setLevel(1); // 대분류
if (category.getParentId() == null || category.getParentId() == 0) {
category.setParentId(null); // 부모 카테고리 설정되지 않음
category.setLevel(1); // 대분류
} else {
// 부모 카테고리 설정된 경우 소분류 처리
vo.setLevel(2); // 소분류
// 부모 카테고리 설정된 경우
CategoryVO parentCategory = categoryDAO.selectCategoryById(category.getParentId());
if (parentCategory == null) {
throw new IllegalArgumentException("존재하지 않는 상위 카테고리 ID입니다.");
}
category.setLevel(parentCategory.getLevel() + 1); // 부모 레벨 + 1
}

// 카테고리 등록 처리
addCategory(vo);
addCategory(category);
}

@Override
Expand Down
2 changes: 1 addition & 1 deletion stockMate/src/main/resources/mappers/categoryMapper.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
is_deleted
FROM test_categories
WHERE is_deleted = 0
ORDER BY level ASC, category_name ASC
ORDER BY level ASC, category_id ASC
</select>

<!-- 카테고리 이름 중복 체크 -->
Expand Down
77 changes: 38 additions & 39 deletions stockMate/src/main/webapp/WEB-INF/views/category/list.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -13,44 +13,43 @@

<h2>카테고리 목록 정보 출력</h2>

<table border="1">
<thead>
<tr>
<th>카테고리 ID</th>
<th>상위 카테고리 ID</th>
<th>카테고리 이름</th>
<th>레벨</th>
<th>생성 날짜</th>
<th>액션</th>
</tr>
</thead>
<tbody>
<!-- categories 리스트를 반복하여 테이블로 출력 -->
<c:forEach var="category" items="${categories}">
<tr>
<td>${category.categoryId}</td>
<td>${category.parentId != null ? category.parentId : '없음'}</td>
<td>${category.categoryName}</td>
<td>${category.level == 1 ? '대분류' : '소분류'}</td>
<td>${category.createdAt}</td>
<td>
<!-- 수정 버튼 -->
<form action="/category/edit" method="get" style="display: inline;">
<input type="hidden" name="categoryId" value="${category.categoryId}" />
<button type="submit">수정</button>
</form>
<!-- 삭제 버튼 -->
<form action="/category/delete" method="post" style="display: inline;" onsubmit="return confirm('정말 삭제하시겠습니까?');">
<input type="hidden" name="categoryId" value="${category.categoryId}" />
<button type="submit">삭제</button>
</form>
</td>
</tr>
</c:forEach>
</tbody>
</table>

<!-- 카테고리 등록 링크 -->
<a href="/category/register">카테고리 등록</a>
<table border="1">
<thead>
<tr>
<th>카테고리 ID</th>
<th>상위 카테고리 ID</th>
<th>카테고리 이름</th>
<th>레벨</th>
<th>생성 날짜</th>
<th>액션</th>
</tr>
</thead>
<tbody>
<!-- 계층별로 카테고리를 표시 -->
<c:forEach var="category" items="${categories}">
<tr>
<td>${category.categoryId}</td>
<td>${category.parentId != null ? category.parentId : '없음'}</td>
<td style="padding-left: ${category.level * 20}px;">
${category.categoryName}
</td>
<td>${category.level}</td>
<td>${category.createdAt}</td>
<td>
<form action="/category/edit" method="get" style="display: inline;">
<input type="hidden" name="categoryId" value="${category.categoryId}" />
<button type="submit">수정</button>
</form>
<form action="/category/delete" method="post" style="display: inline;" onsubmit="return confirm('정말 삭제하시겠습니까?');">
<input type="hidden" name="categoryId" value="${category.categoryId}" />
<button type="submit">삭제</button>
</form>
</td>
</tr>
</c:forEach>
</tbody>
</table>

<a href="/category/register">카테고리 등록</a>
</body>
</html>

0 comments on commit 881d14e

Please sign in to comment.