Skip to content
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 5 commits into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Copy link
Contributor

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

Copy link
Contributor Author

@mochacr0 mochacr0 Oct 9, 2024

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.

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 cart/src/main/java/com/yas/cart/mapper/CartItemV2Mapper.java
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();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.yas.cart.model;

import com.yas.cart.listener.CustomAuditingEntityListener;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import java.time.ZonedDateTime;
Expand All @@ -17,9 +18,11 @@
@EntityListeners(CustomAuditingEntityListener.class)
public class AbstractAuditEntity {
@CreationTimestamp
@Column(updatable = false)
private ZonedDateTime createdOn;

@CreatedBy
@Column(updatable = false)
private String createdBy;

@UpdateTimestamp
Expand Down
25 changes: 25 additions & 0 deletions cart/src/main/java/com/yas/cart/model/CartItemV2.java
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;
}
15 changes: 15 additions & 0 deletions cart/src/main/java/com/yas/cart/model/CartItemV2Id.java
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;
}
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 cart/src/main/java/com/yas/cart/service/CartItemV2Service.java
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);
}
}
13 changes: 13 additions & 0 deletions cart/src/main/java/com/yas/cart/service/ProductService.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.net.URI;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
Expand Down Expand Up @@ -35,6 +36,18 @@ public List<ProductThumbnailVm> getProducts(List<Long> ids) {
.getBody();
}

public ProductThumbnailVm getProductById(Long id) {
List<ProductThumbnailVm> products = getProducts(List.of(id));
if (CollectionUtils.isEmpty(products)) {
return null;
}
return products.getFirst();
}

public boolean existsById(Long id) {
return getProductById(id) != null;
}

protected List<ProductThumbnailVm> handleProductThumbnailFallback(Throwable throwable) throws Throwable {
return handleTypedFallback(throwable);
}
Expand Down
1 change: 1 addition & 0 deletions cart/src/main/java/com/yas/cart/utils/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ public static final class ErrorCode {
public static final String NOT_EXISTING_ITEM_IN_CART = "NOT_EXISTING_ITEM_IN_CART";
public static final String NOT_EXISTING_PRODUCT_IN_CART = "NOT_EXISTING_PRODUCT_IN_CART";
public static final String NON_EXISTING_CART_ITEM = "NON_EXISTING_CART_ITEM";
public static final String ADD_CART_ITEM_FAILED = "ADD_CART_ITEM_FAILED";
}
}
10 changes: 10 additions & 0 deletions cart/src/main/java/com/yas/cart/viewmodel/CartItemV2GetVm.java
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 cart/src/main/java/com/yas/cart/viewmodel/CartItemV2PostVm.java
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 cart/src/main/resources/db/changelog/ddl/changelog-0003.sql
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)
);
1 change: 1 addition & 0 deletions cart/src/main/resources/messages/messages.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ NOT_FOUND_CART=Not found cart {}
NOT_EXISTING_ITEM_IN_CART=There is no cart item in current cart to update!
NOT_EXISTING_PRODUCT_IN_CART=There is no product with ID: {} in the current cart
NON_EXISTING_CART_ITEM=Non exist cart item with ID: {}
ADD_CART_ITEM_FAILED=Add cart item failed
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));
}
}
}
Loading
Loading