diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/cart/Cart.java b/kbazaar/src/main/java/com/kampus/kbazaar/cart/Cart.java index a63eca2..957e0e2 100644 --- a/kbazaar/src/main/java/com/kampus/kbazaar/cart/Cart.java +++ b/kbazaar/src/main/java/com/kampus/kbazaar/cart/Cart.java @@ -1,6 +1,7 @@ package com.kampus.kbazaar.cart; import jakarta.persistence.*; +import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.Setter; @@ -10,12 +11,9 @@ @Data @Getter @Setter +@AllArgsConstructor public class Cart { - // public Cart(int userID) { - // this.userID = userID; - // } - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "cart_id") @@ -24,14 +22,11 @@ public class Cart { @Column(name = "quantity") private int quantity; - @Column(name = "user_id") - private int userId; + @Column(name = "username") + private String username; @Column(name = "product_id") - private int productId; - - @Column(name = "promotion_id") - private Long promotionId; + private Long product_id; // private int userID; diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartController.java b/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartController.java index 7436988..014fd60 100644 --- a/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartController.java +++ b/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartController.java @@ -1,9 +1,5 @@ package com.kampus.kbazaar.cart; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @@ -16,28 +12,35 @@ public CartController(CartService cartService) { this.cartService = cartService; } - @GetMapping("/carts") - public ResponseEntity getCart() { // NOSONAR - return ResponseEntity.ok().build(); - } + // @GetMapping("/carts") + // public ResponseEntity getCart() { // NOSONAR + // return ResponseEntity.ok().build(); + // } + + // @ApiResponse( + // responseCode = "200", + // description = "add promotion to all products in cart", + // content = { + // @Content( + // mediaType = "application/json", + // schema = @Schema(implementation = Cart.class)) + // }) + // @PostMapping("/carts/{username}/promotions") + // public CartResponse appliedPromotionAll( + // @PathVariable String username, @RequestBody PromotionAllRequest cart) { // NOSONAR + // return cartService.addPromotionAll(username, cart); + // } - @ApiResponse( - responseCode = "200", - description = "add promotion to all products in cart", - content = { - @Content( - mediaType = "application/json", - schema = @Schema(implementation = Cart.class)) - }) - @PostMapping("/carts/{username}/promotions") - public CartResponse appliedPromotionAll( - @PathVariable String username, @RequestBody PromotionAllRequest cart) { // NOSONAR - return cartService.addPromotionAll(username, cart); + @PostMapping("/carts/{username}/items") + public CartResponse addItemToCart( + @PathVariable String username, @RequestBody ItemRequest itemRequest) { + return cartService.addItemToCart("Iphone", 1, username); } +} // @PostMapping("/carts/{username}/promotions") // public ResponseEntity createCartPromotions(@PathVariable String username) { // cartService.createCartPromotions30UpTo200(); // return ResponseEntity.ok().build(); // } -} +// } diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartRepository.java b/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartRepository.java index da3aaba..d62ec26 100644 --- a/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartRepository.java +++ b/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartRepository.java @@ -1,5 +1,6 @@ package com.kampus.kbazaar.cart; +import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @@ -8,4 +9,5 @@ public interface CartRepository extends JpaRepository { // @Query("SELECT FROM Cart c WHERE c.userId = ?1") // +Optional findByUserId(int userId); + Optional findByUsername(String username); } diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartService.java b/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartService.java index 842baf5..484ff2d 100644 --- a/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartService.java +++ b/kbazaar/src/main/java/com/kampus/kbazaar/cart/CartService.java @@ -1,10 +1,12 @@ package com.kampus.kbazaar.cart; +import com.kampus.kbazaar.product.ProductRepository; import com.kampus.kbazaar.promotion.PromotionRepository; -import com.kampus.kbazaar.promotion.PromotionResponse; import com.kampus.kbazaar.promotion.PromotionService; import com.kampus.kbazaar.shopper.ShopperRepository; import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; import org.springframework.stereotype.Service; @Service @@ -12,46 +14,90 @@ public class CartService { private final PromotionRepository promotionRepository; private final PromotionService promotionService; private final ShopperRepository ShopperRepository; + private final ProductRepository productRepository; + private final CartRepository cartRepository; public CartService( PromotionRepository promotionRepository, PromotionService promotionService, - ShopperRepository ShopperRepository) { + ShopperRepository ShopperRepository, + ProductRepository productRepository, + CartRepository cartRepository) { this.promotionRepository = promotionRepository; this.promotionService = promotionService; this.ShopperRepository = ShopperRepository; + this.productRepository = productRepository; + this.cartRepository = cartRepository; } - // Story 5 : Add promotion to all products - public CartResponse addPromotionAll(String username, PromotionAllRequest promotion) { - - if (ShopperRepository.findByUsername(username).isEmpty()) { - throw new RuntimeException("Shopper not found"); - } - - if (promotion.getCode().equals("FIXEDAMOUNT10")) { - PromotionResponse newPromotion = - promotionService.getPromotionByCode(promotion.getCode()); - // if (isDateBetween(newPromotion.startDate(), - // newPromotion.endDate(), - // LocalDateTime.now())) - // { - return new CartResponse(username, null, 0, 0); - } else { - throw new RuntimeException("Promotion not found"); - } - } + // Story 4 : Add specific product to my cart + public CartResponse addItemToCart(String productSku, int quantity, String username) { + + // Optional product = productRepository.findBySku(productSku); - // public boolean isDateBetween( - // LocalDateTime startDate, LocalDateTime endDate, LocalDateTime dateToCheck) { - // return !dateToCheck.isBefore(startDate) && !dateToCheck.isAfter(endDate); - // } + // if (product.isEmpty()) { + // throw new NotFoundException("Product not found"); + // } - public void createCartPromotions30UpTo200() { - // List carts = cartRepository.findByUserId(1L); - // if (cartRepository.findByUserId(1L).isEmpty()) - // throw new NotFoundException("Cart not found"); + // Find the cart by username + Optional cart = cartRepository.findByUsername(username); + // Product mockProduct = productRepository.findBySku(productSku); + Item mockItem = + new Item( + "MOBILE-APPLE-IPHONE-12-PRO", + "IPHONE12", + 1, + new BigDecimal("10000.00"), + new BigDecimal("10.00"), + new BigDecimal("10.00")); - BigDecimal TotalPrice = new BigDecimal(0); + return new CartResponse(username, List.of(mockItem), 0, 0); } + + // if (cart.isEmpty()) { + // // Create a new cart + // Cart newCart = new Cart(1, 1, username, product.get().getId()); + // cartRepository.save(newCart); + // } + // else { + // // Add the product to the cart + // Cart existingCart = cart.get(); + // Product[] products = existingCart.getProducts(); + // Product[] newProducts = new Product[products.length + 1]; + // for (int i = 0; i < products.length; i++) { + // newProducts[i] = products[i]; + // } + // newProducts[products.length] = product.get(); + // existingCart.setProducts(newProducts); + // cartRepository.save(existingCart); + // } + // + // return new Cart(username, new Product[]{product.get()}); } +// } + + // Story 5 : Add promotion to all products +// public CartResponse addPromotionAll(String username, PromotionAllRequest promotion) { +// +// if (ShopperRepository.findByUsername(username).isEmpty()) { +// throw new RuntimeException("Shopper not found"); +// } +// +// if (promotion.getCode().equals("FIXEDAMOUNT10")) { +// PromotionResponse newPromotion = +// promotionService.getPromotionByCode(promotion.getCode()); +// return new CartResponse(username, null, 0, 0); +// } else { +// throw new RuntimeException("Promotion not found"); +// } +// } +// +// +// +// public void createCartPromotions30UpTo200() { +// // List carts = cartRepository.findByUserId(1L); +// // if (cartRepository.findByUserId(1L).isEmpty()) +// // throw new NotFoundException("Cart not found"); +// +// BigDecimal TotalPrice = new BigDecimal(0); +// } diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/cart/Item.java b/kbazaar/src/main/java/com/kampus/kbazaar/cart/Item.java index 26b1d99..03c9ce2 100644 --- a/kbazaar/src/main/java/com/kampus/kbazaar/cart/Item.java +++ b/kbazaar/src/main/java/com/kampus/kbazaar/cart/Item.java @@ -1,10 +1,18 @@ package com.kampus.kbazaar.cart; +import java.math.BigDecimal; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@AllArgsConstructor +@Setter public class Item { private String sku; private String name; private Integer quantity; - private Integer price; - private Integer discount; - private Integer finalPrice; + private BigDecimal price; + private BigDecimal discount; + private BigDecimal finalPrice; } diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/cart/ItemRequest.java b/kbazaar/src/main/java/com/kampus/kbazaar/cart/ItemRequest.java new file mode 100644 index 0000000..f4a9267 --- /dev/null +++ b/kbazaar/src/main/java/com/kampus/kbazaar/cart/ItemRequest.java @@ -0,0 +1,19 @@ +package com.kampus.kbazaar.cart; + +public class ItemRequest { + private String sku; + private Integer quantity; + + public ItemRequest(String sku, Integer quantity) { + this.sku = sku; + this.quantity = quantity; + } + + public String getSku() { + return sku; + } + + public Integer getQuantity() { + return quantity; + } +} diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductRepository.java b/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductRepository.java index 6fdfa9f..495fc7c 100644 --- a/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductRepository.java +++ b/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductRepository.java @@ -1,12 +1,11 @@ package com.kampus.kbazaar.product; -import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ProductRepository extends JpaRepository { - Optional findBySku(String sku); + Product findBySku(String sku); // @Query("SELECT p FROM Product p WHERE p.name = ?1") } diff --git a/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductService.java b/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductService.java index e4c7daa..198747e 100644 --- a/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductService.java +++ b/kbazaar/src/main/java/com/kampus/kbazaar/product/ProductService.java @@ -2,7 +2,6 @@ import com.kampus.kbazaar.exceptions.NotFoundException; import java.util.List; -import java.util.Optional; import org.springframework.stereotype.Service; @Service @@ -19,11 +18,11 @@ public List getAll() { } public ProductResponse getBySku(String sku) { - Optional product = productRepository.findBySku(sku); - if (product.isEmpty()) { + Product product = productRepository.findBySku(sku); + if (product == null) { throw new NotFoundException("Product not found"); } - return product.get().toResponse(); + return product.toResponse(); } } diff --git a/kbazaar/src/main/resources/sql/schema/cart.sql b/kbazaar/src/main/resources/sql/schema/cart.sql index 5e6bf2e..960629b 100644 --- a/kbazaar/src/main/resources/sql/schema/cart.sql +++ b/kbazaar/src/main/resources/sql/schema/cart.sql @@ -8,14 +8,12 @@ CREATE TABLE IF NOT EXISTS cart INT NOT NULL, - user_id - INT + username + VARCHAR(255) NOT NULL, product_id INT NOT - NULL, - promotion_id - INT + NULL ); \ No newline at end of file diff --git a/kbazaar/src/test/java/com/kampus/kbazaar/cart/CartControllerTest.java b/kbazaar/src/test/java/com/kampus/kbazaar/cart/CartControllerTest.java index 2479871..93210be 100644 --- a/kbazaar/src/test/java/com/kampus/kbazaar/cart/CartControllerTest.java +++ b/kbazaar/src/test/java/com/kampus/kbazaar/cart/CartControllerTest.java @@ -1,6 +1,11 @@ package com.kampus.kbazaar.cart; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.kampus.kbazaar.security.JwtAuthFilter; +import org.junit.Test; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -9,6 +14,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; +import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -32,15 +38,11 @@ public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(cartController).build(); } - // @Test - // public void getCart_ReturnsOk() throws Exception { - // String token = - // "eyJhbGciOiJIUzI1NiJ9.eyJhdXRob3JpdGllcyI6WyJST0xFX1NIT1BQRVIiXSwic3ViIjoic2hvcHBlciIsImlhdCI6MTcxMTA4MTk1OSwiZXhwIjoxNzQyNjE3OTU5fQ.hwpc_6CL_ZENHurOaZEYg3tz9FVBgOYa7ILF063stxs"; - // mockMvc.perform(get("/api/v1/carts") - // .header("Authorization", "Bearer " + token) - // .contentType(MediaType.APPLICATION_JSON)) - // .andExpect(status().isOk()); - // } + @Test + public void getCart_ReturnsOk() throws Exception { + mockMvc.perform(get("/api/v1/carts").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } // @Test // public void getCart_ReturnsOk() throws Exception { @@ -48,14 +50,15 @@ public void setup() { // .andExpect(status().isForbidden()); // } - // @Test - // public void appliedPromotionAll_ReturnsOk() throws Exception { - // String username = "TechNinja"; - // String promotions = "FIXEDAMOUNT10"; - // - // mockMvc.perform(post("/cart/{username}/promotions", username) - // .contentType(MediaType.APPLICATION_JSON) - // .content(promotions)) - // .andExpect(status().isForbidden()); - // } + @Test + public void appliedPromotionAll_ReturnsOk() throws Exception { + String username = "TechNinja"; + String promotions = "FIXEDAMOUNT10"; + + mockMvc.perform( + post("/cart/{username}/promotions", username) + .contentType(MediaType.APPLICATION_JSON) + .content(promotions)) + .andExpect(status().isOk()); + } } diff --git a/kbazaar/src/test/java/com/kampus/kbazaar/product/ProductServiceTest.java b/kbazaar/src/test/java/com/kampus/kbazaar/product/ProductServiceTest.java index 99199e9..d9c91be 100644 --- a/kbazaar/src/test/java/com/kampus/kbazaar/product/ProductServiceTest.java +++ b/kbazaar/src/test/java/com/kampus/kbazaar/product/ProductServiceTest.java @@ -8,7 +8,6 @@ import java.math.BigDecimal; import java.util.Arrays; import java.util.List; -import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -75,8 +74,8 @@ void shouldBeAbleToGetProductBySku() { new Product(1L, "Pens", "STATIONERY-PEN-BIC-BALLPOINT", new BigDecimal(14.99), 100); // Mock repository method - when(productRepository.findBySku("STATIONERY-PEN-BIC-BALLPOINT")) - .thenReturn(Optional.of(product)); + when(productRepository.findBySku("STATIONERY-PEN-BIC-BALLPOINT")).thenReturn(product); + // .thenReturn(Optional.of(product)); // Call service method ProductResponse result = productService.getBySku("STATIONERY-PEN-BIC-BALLPOINT"); @@ -90,7 +89,8 @@ void shouldBeAbleToGetProductBySku() { @DisplayName("should return null when get product non-existing SKU") void shouldReturnNullWhenGetProductNonExistingSKU() { // Mock repository method returning empty optional - when(productRepository.findBySku(anyString())).thenReturn(Optional.empty()); + when(productRepository.findBySku(anyString())).thenReturn(null); + // when(productRepository.findBySku(anyString())).thenReturn(Optional.empty()); // Assertions assertThrows(NotFoundException.class, () -> productService.getBySku("NonExistingSKU"));