Skip to content

Commit

Permalink
Merge pull request #160 from MoonJongHyeon1095/feat/cart
Browse files Browse the repository at this point in the history
Feat/cart
  • Loading branch information
MoonJongHyeon1095 authored Oct 29, 2023
2 parents 9f9d76a + 208f0c1 commit bb0afe0
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class WebSecurityConfig {
private final JwtUtil jwtUtil;
private final UserDetailsServiceImpl userDetailsService;
private static final String[] PERMIT_URL_ARRAY = {
"/","/v1/api/user/**","/v1/api/product/**","/v1/api/coupon","/GuerrillaCommerce",
"/","/v1/api/user/**","/v1/api/product/**","/v1/api/coupon","/GuerrillaCommerce", "/v1/api/navi",
"/api/v2/**", "/swagger-ui.html", "/swagger/**","/swagger-resources/**", "/webjars/**", "/v2/api-docs"
};

Expand Down
55 changes: 27 additions & 28 deletions src/main/java/com/github/commerce/service/chat/ChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,10 @@ public ChatDto getChatRoom(String customRoomId){
Chat chatEntity = chatRepository.findByCustomRoomId(customRoomId).orElseThrow(()->new ChatException(ChatErrorCode.ROOM_NOT_FOUND));
Map<String, Map<String, String>> chats = chatEntity.getChats();

Map<String, Map<String, String>> sortedChats = chats.entrySet()
.stream()
.sorted((entry1, entry2) -> {
String key1DateTimeStr = entry1.getKey().substring(0, 19);
String key2DateTimeStr = entry2.getKey().substring(0, 19);
LocalDateTime date1 = LocalDateTime.parse(key1DateTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
LocalDateTime date2 = LocalDateTime.parse(key2DateTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
return date1.compareTo(date2);

})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

Map<String, Map<String, String>> sortedChats = sortChatsByDate(chats);
chatEntity.setChats(sortedChats);
return ChatDto.fromEntity(chatEntity);

return ChatDto.fromEntity(chatEntity);
};


Expand All @@ -63,7 +52,7 @@ public Map<String, Object> getSellerChatList(Long sellerId, Long productId) {
List<Chat> chatList = chatRepositoryCustom.getSellerChatList(sellerId, productId);
List<ChatDto> resultList = new ArrayList<>();
chatList.forEach(chat -> {
if(chat.getChats() == null){
if(chat.getChats() == null || chat.getChats().isEmpty()){
return;
}
Map<String,String> productInfo = getProductImageAndName(chat.getProductId());
Expand All @@ -85,7 +74,7 @@ public Map<String, Object> getUserChatList(Long userId, Long sellerId) {
List<Chat> chatList = chatRepositoryCustom.getUserChatList(userId, sellerId);
List<ChatDto> resultList = new ArrayList<>();
chatList.forEach(chat -> {
if(chat.getChats() == null){
if(chat.getChats() == null || chat.getChats().isEmpty()){
return;
}
Map<String,String> productInfo = getProductImageAndName(chat.getProductId());
Expand All @@ -105,29 +94,39 @@ public void cleanupOldChats() {
chatRepositoryCustom.cleanupOldChats();
}

private Map<String, String> getProductImageAndName(Long productId){
Optional<Product> productOptional = productRepository.findById(productId);
protected Map<String, String> getProductImageAndName(Long productId){
Product product = productRepository.findById(productId).orElseThrow(()-> new ChatException(ChatErrorCode.THIS_PRODUCT_DOES_NOT_EXIST));
Map<String, String> result = new HashMap<>();

if (productOptional.isPresent()) {
String urlList = productOptional.get().getThumbnailUrl();
String productName = productOptional.get().getName();
String[] urls = urlList.split(",");

if (urls.length > 0) {
result.put("url", urls[0]);
}

String url = product.getThumbnailUrl();
String productName = product.getName();
//String[] urls = urlList.split(",");
// if (urls.length > 0) {
// result.put("url", urls[0]);
// }
result.put("url", url);
result.put("name", productName);
}

return result.isEmpty() ? null : result;

return result;
}

private String getSellerImage(Long sellerId){
protected String getSellerImage(Long sellerId){
Seller seller = sellerRepository.findById(sellerId).orElseThrow(()-> new ChatException(ChatErrorCode.SELLER_NOT_FOUND));
return seller.getShopImageUrl();
}

protected Map<String, Map<String, String>> sortChatsByDate(Map<String, Map<String, String>> chats) {
return chats.entrySet()
.stream()
.sorted(Comparator.comparing(entry -> extractDateTimeFromKey(entry.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
//정렬된 순서대로 데이터를 유지하려면 LinkedHashMap이 필요합니다. 이렇게 하지 않으면, 정렬 순서가 Map에 저장될 때 무시될 수 있습니다.
}

private LocalDateTime extractDateTimeFromKey(String key) {
String dateTimeStr = key.substring(0, 19);
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -275,15 +275,12 @@ public List<GetProductDto> getProductsByCategory(Integer pageNumber, String prod
String inputGenderCategory = GenderCategoryEnum.switchCategory(genderCategory);

if (Objects.equals(sortBy, "createdAt")) {
System.out.println("111111111111");
return productRepositoryCustom.findByProductCategorySortByCreatedAt(inputProductCategory, inputAgeCategory, inputGenderCategory, pageable);

}else if(Objects.equals(sortBy, "price")){
System.out.println("222222222222222");
return productRepositoryCustom.findByProductCategorySortByPrice(inputProductCategory, inputAgeCategory, inputGenderCategory, pageable);

} else{
System.out.println("33333333333333");
return productRepositoryCustom.findByProductCategorySortById(inputProductCategory, inputAgeCategory, inputGenderCategory, pageable);

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
@RestController
public class ServerCheckController {

@GetMapping("v1/api/navi")
@GetMapping("/")
public ResponseEntity<String> getHealthCheck(){
return ResponseEntity.ok("살아있어요!!");
}
Expand Down
109 changes: 109 additions & 0 deletions src/test/java/com/github/commerce/service/chat/ChatServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package com.github.commerce.service.chat;

import com.github.commerce.entity.collection.Chat;
import com.github.commerce.repository.chat.ChatRepository;
import com.github.commerce.repository.chat.ChatRepositoryCustomImpl;
import com.github.commerce.repository.product.ProductRepository;
import com.github.commerce.repository.user.SellerRepository;
import com.github.commerce.service.chat.exception.ChatException;
import com.github.commerce.web.dto.chat.ChatDto;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.context.TestPropertySource;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@TestPropertySource(locations = "classpath:application-test.yml")
@RunWith(MockitoJUnitRunner.class) // @Mock 사용을 위해 설정
class ChatServiceTest {
@InjectMocks
private ChatService chatService;
@Mock
private ChatRepository chatRepository;
@Mock
private ChatRepositoryCustomImpl chatRepositoryCustom;
@Mock
private ProductRepository productRepository;
@Mock
private SellerRepository sellerRepository;

@BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.openMocks(this);
}


@Test
void getChatRoom() {
Chat mockChat = new Chat();
Map<String, Map<String, String>> chats = new HashMap<>();
Map<String, String> innerMap = new HashMap<>();
innerMap.put("test", "test");
chats.put("2023-09-28T20:15:30Z", innerMap); // 예를 들면 이런 ISO 형식의 문자열을 사용
chats.put("2023-09-28T19:15:30Z", innerMap); // 정렬을 확인하기 위해 두 개의 다른 날짜/시간 추가
mockChat.setChats(chats);

String customRoomId = "testRoom";
mockChat.setCustomRoomId(customRoomId);

when(chatRepository.findByCustomRoomId(customRoomId)).thenReturn(Optional.of(mockChat));
//when(chatService.sortChatsByDate(anyMap())).thenReturn(anyMap());

ChatDto chatRoom = chatService.getChatRoom(customRoomId);

assertNotNull(chatRoom);
verify(chatRepository).findByCustomRoomId(customRoomId);
//verify(chatService).sortChatsByDate(anyMap());

List<String> sortedKeys = new ArrayList<>(chatRoom.getChats().keySet());
assertTrue(sortedKeys.get(0).compareTo(sortedKeys.get(1)) < 0); // 키가 올바르게 정렬되었는지 확인


}

@Test
void getSellerChatListTest() {
Long sellerId = 1L;
Long productId = 1L;
String mockedShopImageUrl = "http://example.com/shop-image.jpg";
List<Chat> mockedChatList = new ArrayList<>();

when(chatService.getSellerImage(sellerId)).thenReturn(mockedShopImageUrl);
when(chatRepositoryCustom.getSellerChatList(sellerId, productId)).thenReturn(mockedChatList);
when(chatService.getProductImageAndName(anyLong())).thenReturn(createMockedProductInfo());

Map<String, Object> resultMap = chatService.getSellerChatList(sellerId, productId);

assertEquals(mockedShopImageUrl, resultMap.get("shopImage"));
assertNotNull(resultMap.get("chatList"));
}


private Map<String, String> createMockedProductInfo() {
Map<String, String> productInfo = new HashMap<>();
productInfo.put("name", "Test Product");
productInfo.put("url", "http://example.com/product-image.jpg");
return productInfo;
}

@Test
void getUserChatList() {
}

@Test
void cleanupOldChats() {
}
}

0 comments on commit bb0afe0

Please sign in to comment.