Skip to content

feat: 출고 시 내역 저장#34

Merged
vivivim merged 36 commits intodevfrom
SPM-376
Nov 4, 2025
Merged

feat: 출고 시 내역 저장#34
vivivim merged 36 commits intodevfrom
SPM-376

Conversation

@vivivim
Copy link
Contributor

@vivivim vivivim commented Nov 4, 2025

📝 Summary

🙏 Question & PR point

📬 Reference

Summary by CodeRabbit

  • 새로운 기능

    • 출고(Out) 이력 추적 도입으로 재고 변동이 상세히 기록됩니다.
    • 입고(스톡킹) 및 출고(배송) 처리 흐름이 분리·개선되어 재고 업데이트가 일관되게 처리됩니다.
    • 재고 조회를 사전 구성된 매핑으로 처리해 성능 및 일관성 개선.
  • 버그 수정 / 안정성

    • 재고 유효성 검증 강화로 누락된 재고에 대한 오류 처리가 명확해졌습니다.
    • 변화량(증감) 관련 오류 상태가 추가되어 잘못된 입력에 대한 응답이 개선되었습니다.

vivivim and others added 30 commits November 1, 2025 19:43
거리가 같으면 짧은순으로
notnull 추가
입고 / 출고 나눔
그리고 이벤트 박스 페이로드 스트링 형식으로
이미 스트링으로 해놔서 인코딩 없이 보내는 것으로 수정
직렬화, 아웃박스 저장 함수 따로 뺌
출고 요청을 보낼 때 해당 주문 아이디를 함게 보내야 합니다.
@coderabbitai
Copy link

coderabbitai bot commented Nov 4, 2025

Walkthrough

InventoryService가 OrderService 사용을 중단하고 OutHistoryRepository로 대체되었으며, delivery 및 신규 stocking 흐름이 재구성되어 사전 계산된 inventoryMap으로 재고를 검증·갱신하고 변경 내역을 out_history에 일괄 저장합니다. InventoryController는 호출을 해당 신규 흐름으로 전환했습니다. (≤50 words)

Changes

Cohort / File(s) 변경 요약
Inventory 서비스 로직 및 out_history 도입
src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java
OrderService 대신 OutHistoryRepository 주입 추가; deliveryProcess 재작성하여 사전 계산된 inventoryMap 사용; saveOutHistory(List<PartDeltaDto>, Map<Long, Inventory>) 추가로 out_history 일괄 저장; stockingProcess(PartUpdateReqDto) 신규 추가; updateParts 시그니처 변경(Map<Long, Inventory> 파라미터 사용); getInventoryMap 헬퍼 추가; 맵 기반 검증/예외 처리로 전환
컨트롤러 호출 전환
src/main/java/com/sampoom/backend/api/inventory/controller/InventoryController.java
stockingParts에서 서비스 호출을 updateParts(partUpdateReqDto) -> stockingProcess(partUpdateReqDto)로 변경
에러 상태 추가
src/main/java/com/sampoom/backend/common/response/ErrorStatus.java
재고 변화량 검증을 위한 POSITIVE_DELTANEGATIVE_DELTA 에러 코드 추가

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant InventoryController
    participant InventoryService
    participant OutHistoryRepository
    participant DB as Database

    Client->>InventoryController: POST /inventory/stocking (PartUpdateReqDto)
    InventoryController->>InventoryService: stockingProcess(partUpdateReqDto)
    InventoryService->>InventoryService: getInventoryMap(warehouseId, items)
    InventoryService->>InventoryService: updateParts(partUpdateReqDto, inventoryMap)
    alt delivery (출고) 흐름
        InventoryService->>InventoryService: validate deltas & build outEntries
        InventoryService->>OutHistoryRepository: saveOutHistory(outEntries)
        OutHistoryRepository->>DB: bulk INSERT out_history
        DB-->>OutHistoryRepository: OK
    else 입고 흐름
        InventoryService->>InventoryService: validate inbound deltas & update quantities
    end
    InventoryService-->>InventoryController: OK
    InventoryController-->>Client: 200 OK
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • 추가 검토 포인트:
    • saveOutHistory의 트랜잭션 경계 및 배치 삽입 성능
    • getInventoryMap의 예외 처리 및 동시성(재고 갱신 시 일관성) 고려
    • updateParts 시그니처 변경에 따른 호출부 및 테스트 영향

Possibly related PRs

  • Spm 371 #33-Auto/Sampoom-Management-Backend-warehouse#33 — InventoryService의 update/stocking 흐름과 PartUpdateReqDto/PartDeltaDto 사용 변경 관련으로 직접 연관됨.
  • Spm 371 #33-Auto/Sampoom-Management-Backend-warehouse#28 — OutHistory 엔티티/레포지토리 추가 및 out_history 저장 로직과 중복/충돌 가능성 있음.
  • Spm 371 #33-Auto/Sampoom-Management-Backend-warehouse#29 — OutHistory 기반 흐름 전환 및 컨트롤러/서비스 연동 변경과 코드 레벨 연관성 높음.

Suggested labels

ready-to-merge

Suggested reviewers

  • Sangyoon98
  • Lee-Jong-Jin
  • CHOOSLA
  • yangjiseonn

Poem

토끼가 뛴다, 창고 맵을 들고,
출고 기록은 조용히 쌓여가고,
델타를 확인해 숫자를 맞추니,
삽입 한 번에 흔적이 남네 🐇,
짧은 발걸음, 안정된 창고.

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR 제목이 변경사항의 핵심을 정확하게 반영합니다. 출고 시 내역 저장이라는 주요 기능이 명확하게 드러나 있습니다.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch SPM-376

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java (1)

134-167: JPA 리포지토리 활용 고려

네이티브 SQL을 사용한 배치 INSERT 구현이 동작하지만, JPA 리포지토리의 saveAll을 사용하면 코드가 더 간결해지고 유지보수성이 향상될 수 있습니다. 다만 대량 데이터 처리 시 네이티브 SQL이 성능상 유리할 수 있으므로 성능 요구사항에 따라 판단하시기 바랍니다.

JPA 리포지토리 방식의 예시:

@Transactional
protected void saveOutHistory(DeliveryReqDto deliveryReqDto) {
    Long warehouseId = deliveryReqDto.getWarehouseId();
    List<OutHistory> outHistories = new ArrayList<>();
    
    for (PartDeltaDto dto : deliveryReqDto.getItems()) {
        Inventory inventory = inventoryRepository
                .findByBranch_IdAndPart_Id(warehouseId, dto.getId())
                .orElseThrow(() -> new NotFoundException(ErrorStatus.INVENTORY_NOT_FOUND.getMessage()));
        
        OutHistory outHistory = OutHistory.builder()
                .inventory(inventory)
                .usedQuantity(Math.abs(dto.getDelta()))
                .build();
        outHistories.add(outHistory);
    }
    
    if (!outHistories.isEmpty()) {
        outHistoryRepository.saveAll(outHistories);
    }
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 597548d and 6173c5e.

📒 Files selected for processing (1)
  • src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (java-kotlin)
🔇 Additional comments (1)
src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java (1)

77-82: 출고 이력 저장 로직 추가 확인

deliveryProcess 메서드에 saveOutHistory 호출이 적절하게 추가되었습니다. 트랜잭션 경계 내에서 재고 업데이트 후 이력을 저장하고 ROP를 확인하는 흐름이 논리적으로 올바릅니다.

Copy link

@taemin3 taemin3 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확인했습니다

Admin added 2 commits November 4, 2025 16:29
한 트랜잭션 내에서 동일한 조회 한번으로 줄임
n+1도 없앰
입출고 시 각각 음수/양수만 받음
출고 내역 저장시 절대값
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java (1)

179-207: 출고 이력 저장 메서드 추가 - Math.abs 사용 불필요

출고 이력을 bulk insert로 효율적으로 저장하는 구조는 좋습니다.

개선 제안: Line 183의 Math.abs(item.getDelta())는 이제 불필요합니다. validateOutBound (lines 92-97)에서 이미 delta가 음수임을 보장하므로, 다음과 같이 변경할 수 있습니다:

 .map(item -> new Object[]{
-        inventoryMap.get(item.getId()).getId(), Math.abs(item.getDelta())
+        inventoryMap.get(item.getId()).getId(), -item.getDelta()
 })

이렇게 하면 검증 로직과의 관계가 더 명확해집니다.

참고: 이전 리뷰에서 지적된 order_id 누락 문제는 여전히 존재합니다 (DeliveryReqDto에 orderId가 있지만 저장되지 않음). 해당 이슈는 이전 리뷰 코멘트를 참조하세요.

🧹 Nitpick comments (1)
src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java (1)

100-115: 입고 프로세스 및 검증 로직 추가

입고(stockingProcess)와 출고(deliveryProcess)를 명확히 분리하고 각각에 대한 delta 부호 검증을 추가한 것은 좋은 설계입니다. 코드의 의도가 명확하고 오류 가능성이 줄어듭니다.

선택적 개선사항: validateInBoundvalidateOutBound의 로직이 유사하므로, 향후 validateDelta(boolean shouldBePositive) 같은 공통 메서드로 통합을 고려할 수 있습니다. 하지만 현재 구현도 충분히 명확합니다.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee5eb60 and cd31300.

📒 Files selected for processing (2)
  • src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java (4 hunks)
  • src/main/java/com/sampoom/backend/common/response/ErrorStatus.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (java-kotlin)
🔇 Additional comments (6)
src/main/java/com/sampoom/backend/common/response/ErrorStatus.java (1)

28-29: 코드 변경사항이 적절합니다.

검증 결과, 두 에러 상태의 메시지가 사용 컨텍스트에서 충분히 명확합니다:

  • POSITIVE_DELTA: validateOutBound()에서 델타가 0 이상일 때 발생 → "변화량이 양수입니다"는 출고 작업에서 음수 델타가 필요하다는 점을 적절히 나타냅니다.
  • NEGATIVE_DELTA: validateInBound()에서 델타가 0 이하일 때 발생 → "변화량이 음수입니다"는 입고 작업에서 양수 델타가 필요하다는 점을 적절히 나타냅니다.

메서드명과 검증 로직이 이미 작업 유형을 명확히 하고 있어, 추가적인 수정은 불필요합니다.

src/main/java/com/sampoom/backend/api/inventory/service/InventoryService.java (5)

12-14: 새로운 출고 이력 기능을 위한 깔끔한 import 추가

OutHistory 엔티티와 OutHistoryRepository를 추가하여 출고 이력 저장 기능을 지원합니다.


76-88: 배송 프로세스 리팩토링 개선 확인

좋은 개선사항들:

  • getInventoryMap으로 재고를 사전 조회하여 N+1 쿼리 문제 해결
  • validateOutBound로 출고 시 음수 delta 검증 추가
  • inventoryMap을 전달하여 중복 조회 제거
  • 출고 이력 저장 기능 추가

각 단계가 명확히 분리되어 있고, 이전 리뷰에서 지적된 N+1 쿼리 문제가 효과적으로 해결되었습니다.


92-97: 출고 시 음수 delta 검증 추가 - 훌륭합니다!

배송 프로세스에서 delta가 음수인지 검증하는 로직이 추가되어, 이전 리뷰에서 지적된 delta 부호 검증 문제가 해결되었습니다. 양수 delta가 전달되면 명확한 에러 메시지와 함께 예외가 발생합니다.


117-128: 재고 조회 헬퍼 메서드 - 효율적인 구현

getInventoryMap 메서드는 다음과 같은 이점을 제공합니다:

  • 재고를 한 번에 조회하여 N+1 쿼리 문제 해결
  • 필요한 모든 재고가 존재하는지 검증 (lines 122-124)
  • Map 구조로 O(1) 조회 성능 보장

이전 리뷰에서 지적된 성능 이슈를 효과적으로 해결한 구현입니다.


131-153: 재고 업데이트 로직 리팩토링 확인

메서드 시그니처를 변경하여 inventoryMap을 파라미터로 받도록 개선되었습니다:

  • Line 131: Map<Long, Inventory> inventoryMap 파라미터 추가
  • Line 148: 사전 조회된 map에서 재고를 가져와 중복 쿼리 제거

이전 코드에서 루프 내부에서 발생하던 반복적인 repository 조회가 제거되어 성능이 개선되었습니다.

@vivivim vivivim changed the base branch from main to dev November 4, 2025 07:55
@vivivim vivivim merged commit b2cd9e0 into dev Nov 4, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants