-
Notifications
You must be signed in to change notification settings - Fork 454
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
#1099 Move add cart item API to cart module #1141
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
980e5c6
setup base classes for new cart APIs & implement add to cart API
mochacr0 71a5377
refactor & update tests
mochacr0 7f8c316
fix checkstyle
mochacr0 a8b45e8
refactor product validation in add cart item API
mochacr0 3b154d9
change bad request exception to not found when validating product
mochacr0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
23 changes: 23 additions & 0 deletions
23
cart/src/main/java/com/yas/cart/controller/CartItemV2Controller.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package com.yas.cart.controller; | ||
|
||
import com.yas.cart.service.CartItemV2Service; | ||
import com.yas.cart.viewmodel.CartItemV2GetVm; | ||
import com.yas.cart.viewmodel.CartItemV2PostVm; | ||
import jakarta.validation.Valid; | ||
import lombok.RequiredArgsConstructor; | ||
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.RestController; | ||
|
||
@RestController | ||
@RequiredArgsConstructor | ||
public class CartItemV2Controller { | ||
private final CartItemV2Service cartItemService; | ||
|
||
@PostMapping("/storefront/cart/items") | ||
public ResponseEntity<CartItemV2GetVm> addCartItem(@Valid @RequestBody CartItemV2PostVm cartItemPostVm) { | ||
CartItemV2GetVm cartItemGetVm = cartItemService.addCartItem(cartItemPostVm); | ||
return ResponseEntity.ok(cartItemGetVm); | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
cart/src/main/java/com/yas/cart/mapper/CartItemV2Mapper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package com.yas.cart.mapper; | ||
|
||
import com.yas.cart.model.CartItemV2; | ||
import com.yas.cart.viewmodel.CartItemV2GetVm; | ||
import com.yas.cart.viewmodel.CartItemV2PostVm; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
public class CartItemV2Mapper { | ||
public CartItemV2GetVm toGetVm(CartItemV2 cartItem) { | ||
return CartItemV2GetVm | ||
.builder() | ||
.customerId(cartItem.getCustomerId()) | ||
.productId(cartItem.getProductId()) | ||
.quantity(cartItem.getQuantity()) | ||
.build(); | ||
} | ||
|
||
public CartItemV2 toCartItem(CartItemV2PostVm cartItemPostVm, String currentUserId) { | ||
return CartItemV2 | ||
.builder() | ||
.customerId(currentUserId) | ||
.productId(cartItemPostVm.productId()) | ||
.quantity(cartItemPostVm.quantity()) | ||
.build(); | ||
} | ||
|
||
public CartItemV2 toCartItem(String currentUserId, Long productId, int quantity) { | ||
return CartItemV2 | ||
.builder() | ||
.customerId(currentUserId) | ||
.productId(productId) | ||
.quantity(quantity) | ||
.build(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package com.yas.cart.model; | ||
|
||
import jakarta.persistence.Entity; | ||
import jakarta.persistence.Id; | ||
import jakarta.persistence.IdClass; | ||
import jakarta.persistence.Table; | ||
import lombok.AllArgsConstructor; | ||
import lombok.Builder; | ||
import lombok.NoArgsConstructor; | ||
|
||
@Entity | ||
@Table(name = "cart_item_v2") | ||
@IdClass(CartItemV2Id.class) | ||
@NoArgsConstructor | ||
@AllArgsConstructor | ||
@lombok.Getter | ||
@lombok.Setter | ||
@Builder | ||
public class CartItemV2 extends AbstractAuditEntity { | ||
@Id | ||
private String customerId; | ||
@Id | ||
private Long productId; | ||
private int quantity; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package com.yas.cart.model; | ||
|
||
import lombok.AllArgsConstructor; | ||
import lombok.EqualsAndHashCode; | ||
import lombok.NoArgsConstructor; | ||
|
||
@NoArgsConstructor | ||
@AllArgsConstructor | ||
@lombok.Getter | ||
@lombok.Setter | ||
@EqualsAndHashCode | ||
public class CartItemV2Id { | ||
private String customerId; | ||
private Long productId; | ||
} |
18 changes: 18 additions & 0 deletions
18
cart/src/main/java/com/yas/cart/repository/CartItemV2Repository.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package com.yas.cart.repository; | ||
|
||
import com.yas.cart.model.CartItemV2; | ||
import com.yas.cart.model.CartItemV2Id; | ||
import jakarta.persistence.LockModeType; | ||
import jakarta.persistence.QueryHint; | ||
import java.util.Optional; | ||
import org.springframework.data.jpa.repository.JpaRepository; | ||
import org.springframework.data.jpa.repository.Lock; | ||
import org.springframework.data.jpa.repository.Query; | ||
import org.springframework.data.jpa.repository.QueryHints; | ||
|
||
public interface CartItemV2Repository extends JpaRepository<CartItemV2, CartItemV2Id> { | ||
@Lock(LockModeType.PESSIMISTIC_WRITE) | ||
@QueryHints({@QueryHint(name = "jakarta.persistence.lock.timeout", value = "0")}) | ||
@Query("SELECT c FROM CartItemV2 c WHERE c.customerId = :customerId AND c.productId = :productId") | ||
Optional<CartItemV2> findWithLock(String customerId, Long productId); | ||
} |
62 changes: 62 additions & 0 deletions
62
cart/src/main/java/com/yas/cart/service/CartItemV2Service.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
package com.yas.cart.service; | ||
|
||
import com.yas.cart.mapper.CartItemV2Mapper; | ||
import com.yas.cart.model.CartItemV2; | ||
import com.yas.cart.repository.CartItemV2Repository; | ||
import com.yas.cart.utils.Constants; | ||
import com.yas.cart.viewmodel.CartItemV2GetVm; | ||
import com.yas.cart.viewmodel.CartItemV2PostVm; | ||
import com.yas.commonlibrary.exception.InternalServerErrorException; | ||
import com.yas.commonlibrary.exception.NotFoundException; | ||
import com.yas.commonlibrary.utils.AuthenticationUtils; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.dao.PessimisticLockingFailureException; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
@Slf4j | ||
public class CartItemV2Service { | ||
private final CartItemV2Repository cartItemRepository; | ||
private final ProductService productService; | ||
private final CartItemV2Mapper cartItemMapper; | ||
|
||
@Transactional | ||
public CartItemV2GetVm addCartItem(CartItemV2PostVm cartItemPostVm) { | ||
validateProduct(cartItemPostVm.productId()); | ||
|
||
String currentUserId = AuthenticationUtils.extractUserId(); | ||
CartItemV2 cartItem = performAddCartItem(cartItemPostVm, currentUserId); | ||
|
||
return cartItemMapper.toGetVm(cartItem); | ||
} | ||
|
||
private void validateProduct(Long productId) { | ||
if (!productService.existsById(productId)) { | ||
throw new NotFoundException(Constants.ErrorCode.NOT_FOUND_PRODUCT); | ||
} | ||
} | ||
|
||
private CartItemV2 performAddCartItem(CartItemV2PostVm cartItemPostVm, String currentUserId) { | ||
try { | ||
return cartItemRepository.findWithLock(currentUserId, cartItemPostVm.productId()) | ||
.map(existingCartItem -> updateExistingCartItem(cartItemPostVm, existingCartItem)) | ||
.orElseGet(() -> createNewCartItem(cartItemPostVm, currentUserId)); | ||
} catch (PessimisticLockingFailureException e) { | ||
log.error("Failed to acquire lock for adding cart item", e); | ||
throw new InternalServerErrorException(Constants.ErrorCode.ADD_CART_ITEM_FAILED); | ||
} | ||
} | ||
|
||
private CartItemV2 createNewCartItem(CartItemV2PostVm cartItemPostVm, String currentUserId) { | ||
CartItemV2 cartItem = cartItemMapper.toCartItem(cartItemPostVm, currentUserId); | ||
return cartItemRepository.save(cartItem); | ||
} | ||
|
||
private CartItemV2 updateExistingCartItem(CartItemV2PostVm cartItemPostVm, CartItemV2 existingCartItem) { | ||
existingCartItem.setQuantity(existingCartItem.getQuantity() + cartItemPostVm.quantity()); | ||
return cartItemRepository.save(existingCartItem); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
cart/src/main/java/com/yas/cart/viewmodel/CartItemV2GetVm.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package com.yas.cart.viewmodel; | ||
|
||
import lombok.Builder; | ||
|
||
@Builder | ||
public record CartItemV2GetVm( | ||
String customerId, | ||
Long productId, | ||
Integer quantity | ||
) {} |
10 changes: 10 additions & 0 deletions
10
cart/src/main/java/com/yas/cart/viewmodel/CartItemV2PostVm.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package com.yas.cart.viewmodel; | ||
|
||
import jakarta.validation.constraints.Min; | ||
import jakarta.validation.constraints.NotNull; | ||
import lombok.Builder; | ||
|
||
@Builder | ||
public record CartItemV2PostVm( | ||
@NotNull Long productId, | ||
@NotNull @Min(1) Integer quantity) {} |
11 changes: 11 additions & 0 deletions
11
cart/src/main/resources/db/changelog/ddl/changelog-0003.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
--changeset mochacr0:issue-1099-1 | ||
CREATE TABLE cart_item_v2 ( | ||
customer_id VARCHAR(255) NOT NULL, | ||
product_id BIGINT NOT NULL, | ||
quantity INTEGER NOT NULL, | ||
created_by VARCHAR(255), | ||
created_on TIMESTAMP(6), | ||
last_modified_by VARCHAR(255), | ||
last_modified_on TIMESTAMP(6), | ||
CONSTRAINT pk_cart_item PRIMARY KEY (customer_id, product_id) | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
cart/src/test/java/com/yas/cart/controller/CartItemV2ControllerTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
package com.yas.cart.controller; | ||
|
||
import static org.mockito.Mockito.verify; | ||
import static org.mockito.Mockito.when; | ||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; | ||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; | ||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | ||
|
||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.yas.cart.service.CartItemV2Service; | ||
import com.yas.cart.viewmodel.CartItemV2GetVm; | ||
import com.yas.cart.viewmodel.CartItemV2PostVm; | ||
import com.yas.commonlibrary.exception.ApiExceptionHandler; | ||
import javax.ws.rs.core.MediaType; | ||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.Nested; | ||
import org.junit.jupiter.api.Test; | ||
import org.junit.jupiter.api.extension.ExtendWith; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; | ||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; | ||
import org.springframework.boot.test.mock.mockito.MockBean; | ||
import org.springframework.test.context.ContextConfiguration; | ||
import org.springframework.test.context.junit.jupiter.SpringExtension; | ||
import org.springframework.test.web.servlet.MockMvc; | ||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; | ||
|
||
@ExtendWith(SpringExtension.class) | ||
@WebMvcTest | ||
@ContextConfiguration(classes = {CartItemV2Controller.class, ApiExceptionHandler.class}) | ||
@AutoConfigureMockMvc(addFilters = false) | ||
class CartItemV2ControllerTest { | ||
|
||
private static final String CART_ITEM_BASE_URL = "/storefront/cart/items"; | ||
private static final String ADD_CART_ITEM_URL = CART_ITEM_BASE_URL; | ||
|
||
@Autowired | ||
private MockMvc mockMvc; | ||
|
||
@Autowired | ||
private ObjectMapper objectMapper; | ||
|
||
@MockBean | ||
private CartItemV2Service cartItemService; | ||
|
||
@Nested | ||
class AddToCartTest { | ||
|
||
private CartItemV2PostVm.CartItemV2PostVmBuilder cartItemPostVmBuilder; | ||
|
||
@BeforeEach | ||
void setUp() { | ||
cartItemPostVmBuilder = CartItemV2PostVm.builder() | ||
.productId(1L) | ||
.quantity(1); | ||
} | ||
|
||
@Test | ||
void testAddToCart_whenProductIdIsNull_shouldReturnBadRequest() throws Exception { | ||
CartItemV2PostVm cartItemPostVm = cartItemPostVmBuilder.productId(null).build(); | ||
performAddCartItemAndExpectBadRequest(cartItemPostVm); | ||
} | ||
|
||
@Test | ||
void testAddToCart_whenQuantityIsNull_shouldReturnBadRequest() throws Exception { | ||
CartItemV2PostVm cartItemPostVm = cartItemPostVmBuilder.quantity(null).build(); | ||
performAddCartItemAndExpectBadRequest(cartItemPostVm); | ||
} | ||
|
||
@Test | ||
void testAddToCart_whenQuantityIsLessThanOne_shouldReturnBadRequest() throws Exception { | ||
CartItemV2PostVm cartItemPostVm = cartItemPostVmBuilder.quantity(0).build(); | ||
performAddCartItemAndExpectBadRequest(cartItemPostVm); | ||
} | ||
|
||
@Test | ||
void testAddToCart_whenRequestIsValid_shouldReturnCartItem() throws Exception { | ||
CartItemV2PostVm cartItemPostVm = cartItemPostVmBuilder.build(); | ||
CartItemV2GetVm expectedCartItem = CartItemV2GetVm.builder() | ||
.productId(cartItemPostVm.productId()) | ||
.quantity(cartItemPostVm.quantity()) | ||
.build(); | ||
|
||
when(cartItemService.addCartItem(cartItemPostVm)).thenReturn(expectedCartItem); | ||
|
||
mockMvc.perform(buildAddCartItemRequest(cartItemPostVm)) | ||
.andExpect(status().isOk()) | ||
.andExpect(jsonPath("$.productId").value(expectedCartItem.productId())) | ||
.andExpect(jsonPath("$.quantity").value(expectedCartItem.quantity())); | ||
|
||
verify(cartItemService).addCartItem(cartItemPostVm); | ||
} | ||
|
||
private void performAddCartItemAndExpectBadRequest(CartItemV2PostVm cartItemPostVm) | ||
throws Exception { | ||
mockMvc.perform(buildAddCartItemRequest(cartItemPostVm)) | ||
.andExpect(status().isBadRequest()); | ||
} | ||
|
||
private MockHttpServletRequestBuilder buildAddCartItemRequest(CartItemV2PostVm cartItemPostVm) | ||
throws Exception { | ||
return post(ADD_CART_ITEM_URL) | ||
.contentType(MediaType.APPLICATION_JSON) | ||
.content(objectMapper.writeValueAsString(cartItemPostVm)); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't need to create a new version of CartItemXXX classes, in my opinion. We will only refactor the code but keep the class names unchanged
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the feedback. The "V2" in the class name is a temporary measure to avoid conflicts during the refactoring process.
Since there’s another task related to the cart that might be developing, I want to avoid any issues. Once the refactoring is complete, I’ll remove the "V2" and revert the classes to their original names.