Skip to content

Commit 0006643

Browse files
authored
Merge pull request #2 from manirDev/shoppingCart
Shopping cart
2 parents 76735f3 + c6456ef commit 0006643

File tree

10 files changed

+331
-0
lines changed

10 files changed

+331
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.manir.springbootecommercerestapi.controller;
2+
3+
import com.manir.springbootecommercerestapi.dto.CartItemDto;
4+
import com.manir.springbootecommercerestapi.service.ShoppingCartService;
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.http.ResponseEntity;
7+
import org.springframework.web.bind.annotation.*;
8+
9+
import javax.annotation.Resource;
10+
import java.util.List;
11+
12+
@RestController
13+
@RequestMapping("api/v1/cart")
14+
public class ShoppingCartController {
15+
16+
@Resource
17+
private ShoppingCartService shoppingCartService;
18+
19+
//find by customer api
20+
@GetMapping("/findByCustomer/{customerId}")
21+
public List<CartItemDto> findByCustomerId(@PathVariable Long customerId){
22+
List<CartItemDto> responseCartItems = shoppingCartService.findByCustomerId(customerId);
23+
24+
return responseCartItems;
25+
}
26+
27+
//add item to the cart api
28+
@PostMapping("/addItem/{customerId}/{productId}/{quantity}")
29+
public ResponseEntity<CartItemDto> addCartItem(@PathVariable Long customerId,
30+
@PathVariable Long productId,
31+
@PathVariable Integer quantity){
32+
CartItemDto responseCartItem = shoppingCartService.addCartItem(customerId, productId, quantity);
33+
34+
return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED);
35+
}
36+
37+
//update item quantity api
38+
@PutMapping("/updateItemQuantity/{customerId}/{productId}/{quantity}")
39+
public ResponseEntity<CartItemDto> updateItemQuantity(@PathVariable Long customerId,
40+
@PathVariable Long productId,
41+
@PathVariable Integer quantity){
42+
43+
CartItemDto responseCartItem = shoppingCartService.updateItemQuantity(customerId, productId, quantity);
44+
45+
return new ResponseEntity<>(responseCartItem, HttpStatus.OK);
46+
}
47+
48+
//delete item product api
49+
@DeleteMapping("/deleteItemProduct/{customerId}/{productId}")
50+
public ResponseEntity<String> deleteItemProduct(@PathVariable Long customerId, @PathVariable Long productId){
51+
shoppingCartService.deleteItemProduct(customerId, productId);
52+
return ResponseEntity.ok("Product deleted successfully from cart item");
53+
}
54+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.manir.springbootecommercerestapi.dto;
2+
3+
import lombok.Data;
4+
5+
@Data
6+
public class CartItemDto {
7+
private Long id;
8+
private Integer quantity;
9+
private String status;
10+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.manir.springbootecommercerestapi.model;
2+
3+
import com.fasterxml.jackson.annotation.JsonIgnore;
4+
import lombok.AllArgsConstructor;
5+
import lombok.Data;
6+
import lombok.NoArgsConstructor;
7+
8+
import javax.persistence.*;
9+
import java.util.Set;
10+
11+
@AllArgsConstructor
12+
@NoArgsConstructor
13+
@Data
14+
@Entity
15+
@Table(name = "cart_item")
16+
public class CartItem {
17+
@Id
18+
@GeneratedValue(strategy = GenerationType.IDENTITY)
19+
private Long id;
20+
@Column(name = "quantity")
21+
private Integer quantity;
22+
@Column(name = "status")
23+
private String status; //pending, ordered
24+
25+
//relation with product
26+
@ManyToOne()
27+
@JoinColumn(name = "product_id")
28+
private Product product;
29+
30+
//relation with user
31+
@ManyToOne()
32+
@JoinColumn(name = "customer_id")
33+
private Customer customer;
34+
35+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.manir.springbootecommercerestapi.model;
2+
3+
import com.fasterxml.jackson.annotation.JsonIgnore;
4+
import lombok.Data;
5+
6+
import javax.persistence.*;
7+
import java.util.Set;
8+
9+
@Data
10+
@Entity
11+
@Table(name = "customers", uniqueConstraints = {@UniqueConstraint(columnNames = {"userName"}),
12+
@UniqueConstraint(columnNames = {"email"})
13+
})
14+
public class Customer {
15+
@Id
16+
@GeneratedValue(strategy = GenerationType.IDENTITY)
17+
private Long id;
18+
private String name;
19+
private String userName;
20+
private String email;
21+
private String password;
22+
23+
//relation with cart item
24+
@OneToMany(cascade = CascadeType.ALL,
25+
fetch = FetchType.LAZY, orphanRemoval = true,
26+
mappedBy = "customer")
27+
private Set<CartItem> cartItems;
28+
}

src/main/java/com/manir/springbootecommercerestapi/model/Product.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.manir.springbootecommercerestapi.model;
22

3+
import com.fasterxml.jackson.annotation.JsonIgnore;
34
import lombok.*;
45

56
import javax.persistence.*;
@@ -48,4 +49,9 @@ public class Product {
4849
//relation to product comment
4950
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
5051
private Set<Comment> comments;
52+
53+
54+
//relation to cart item
55+
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
56+
private Set<CartItem> cartItems;
5157
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.manir.springbootecommercerestapi.repository;
2+
3+
import com.manir.springbootecommercerestapi.model.CartItem;
4+
import org.springframework.data.jpa.repository.JpaRepository;
5+
import org.springframework.data.jpa.repository.Modifying;
6+
import org.springframework.data.jpa.repository.Query;
7+
8+
import java.util.List;
9+
10+
public interface CartItemRepository extends JpaRepository<CartItem, Long> {
11+
12+
List<CartItem> findByCustomerId(Long customerId);
13+
14+
//CartItem findByCustomerAndProduct(Customer customer, Product product);
15+
CartItem findByCustomerIdAndProductId(Long customerId, Long productId);
16+
17+
@Query("UPDATE CartItem c SET c.quantity = ?3 WHERE c.product.id = ?2 AND c.customer.id = ?1")
18+
void updateItemQuantity(Long customerId, Long productId, Integer quantity);
19+
20+
@Query("DELETE FROM CartItem c WHERE c.customer.id = ?1 AND c.product.id = ?2")
21+
@Modifying
22+
void deleteByCustomerIdAndProductId(Long customerId, Long productId);
23+
24+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.manir.springbootecommercerestapi.repository;
2+
3+
import com.manir.springbootecommercerestapi.model.Customer;
4+
import org.springframework.data.jpa.repository.JpaRepository;
5+
6+
public interface CustomerRepository extends JpaRepository<Customer, Long>{
7+
8+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.manir.springbootecommercerestapi.response;
2+
3+
4+
import com.manir.springbootecommercerestapi.dto.CartItemDto;
5+
import lombok.AllArgsConstructor;
6+
import lombok.Data;
7+
import lombok.NoArgsConstructor;
8+
9+
import java.util.List;
10+
11+
@Data
12+
@AllArgsConstructor
13+
@NoArgsConstructor
14+
public class CartItemResponse {
15+
private List<CartItemDto> content;
16+
private double totalCost;
17+
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
package com.manir.springbootecommercerestapi.service.Impl;
2+
3+
import com.manir.springbootecommercerestapi.dto.CartItemDto;
4+
import com.manir.springbootecommercerestapi.exception.EcommerceApiException;
5+
import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException;
6+
import com.manir.springbootecommercerestapi.model.CartItem;
7+
import com.manir.springbootecommercerestapi.model.Customer;
8+
import com.manir.springbootecommercerestapi.model.Product;
9+
import com.manir.springbootecommercerestapi.repository.CartItemRepository;
10+
import com.manir.springbootecommercerestapi.repository.CustomerRepository;
11+
import com.manir.springbootecommercerestapi.repository.ProductRepository;
12+
import com.manir.springbootecommercerestapi.service.ShoppingCartService;
13+
import lombok.extern.slf4j.Slf4j;
14+
import org.modelmapper.ModelMapper;
15+
import org.springframework.http.HttpStatus;
16+
import org.springframework.stereotype.Service;
17+
18+
import javax.annotation.Resource;
19+
import javax.transaction.Transactional;
20+
import java.util.List;
21+
import java.util.stream.Collectors;
22+
23+
@Service
24+
@Slf4j
25+
26+
public class ShoppingCartServiceImpl implements ShoppingCartService {
27+
28+
@Resource
29+
private CartItemRepository cartItemRepository;
30+
@Resource
31+
private ModelMapper modelMapper;
32+
@Resource
33+
private ProductRepository productRepository;
34+
@Resource
35+
private CustomerRepository customerRepository;
36+
37+
@Override
38+
public List<CartItemDto> findByCustomerId(Long customerId) {
39+
40+
List<CartItem> cartItems = cartItemRepository.findByCustomerId(customerId);
41+
42+
if (cartItems.size() == 0){
43+
throw new EcommerceApiException("Customer has no product in cart item", HttpStatus.BAD_REQUEST);
44+
}
45+
46+
List<CartItemDto> cartItemDtoList = cartItems.stream()
47+
.map(cartItem -> mapToDto(cartItem))
48+
.collect(Collectors.toList());
49+
50+
return cartItemDtoList;
51+
}
52+
53+
@Override
54+
public CartItemDto addCartItem(Long customerId, Long productId, Integer quantity) {
55+
Integer addedQuantity = quantity;
56+
Customer customer = customerRepository.findById(customerId)
57+
.orElseThrow(
58+
() -> new ResourceNotFoundException("Customer", customerId)
59+
);
60+
Product product = productRepository.findById(productId)
61+
.orElseThrow(
62+
() -> new ResourceNotFoundException("Product", productId)
63+
);
64+
65+
CartItem cartItem = cartItemRepository.findByCustomerIdAndProductId(customerId, productId);
66+
if(cartItem != null){
67+
addedQuantity = cartItem.getQuantity() + quantity;
68+
cartItem.setQuantity(addedQuantity);
69+
}else {
70+
cartItem = new CartItem();
71+
cartItem.setCustomer(customer);
72+
cartItem.setProduct(product);
73+
cartItem.setQuantity(quantity);
74+
}
75+
76+
CartItem addedCartItem = cartItemRepository.save(cartItem);
77+
78+
return mapToDto(addedCartItem);
79+
}
80+
81+
@Override
82+
public CartItemDto updateItemQuantity(Long customerId, Long productId, Integer quantity) {
83+
84+
Customer customer = customerRepository.findById(customerId)
85+
.orElseThrow(
86+
() -> new ResourceNotFoundException("Customer", customerId)
87+
);
88+
Product product = productRepository.findById(productId)
89+
.orElseThrow(
90+
() -> new ResourceNotFoundException("Product", productId)
91+
);
92+
93+
CartItem cartItem = cartItemRepository.findByCustomerIdAndProductId(customerId, productId);
94+
if (!cartItem.getCustomer().getId().equals(customer.getId()) || !cartItem.getProduct().getId().equals(product.getId())){
95+
throw new EcommerceApiException(" this cart item does not belong to Customer or Product ", HttpStatus.BAD_REQUEST);
96+
}
97+
cartItem.setQuantity(quantity);
98+
CartItem updatedItemQuantity = cartItemRepository.save(cartItem);
99+
return mapToDto(updatedItemQuantity);
100+
}
101+
102+
@Override
103+
@Transactional
104+
public void deleteItemProduct(Long customerId, Long productId) {
105+
Customer customer = customerRepository.findById(customerId)
106+
.orElseThrow(
107+
() -> new ResourceNotFoundException("Customer", customerId)
108+
);
109+
Product product = productRepository.findById(productId)
110+
.orElseThrow(
111+
() -> new ResourceNotFoundException("Product", productId)
112+
);
113+
CartItem cartItem = cartItemRepository.findByCustomerIdAndProductId(customerId, productId);
114+
if (cartItem != null){
115+
cartItemRepository.deleteByCustomerIdAndProductId(customerId, productId);
116+
}
117+
if (!cartItem.getCustomer().getId().equals(customer.getId()) || !cartItem.getProduct().getId().equals(product.getId())){
118+
throw new EcommerceApiException(" this cart item does not belong to Customer or Product ", HttpStatus.BAD_REQUEST);
119+
}
120+
}
121+
122+
//map to dto
123+
private CartItemDto mapToDto(CartItem cartItem){
124+
CartItemDto cartItemDto = modelMapper.map(cartItem, CartItemDto.class);
125+
return cartItemDto;
126+
}
127+
128+
//map to entity
129+
private CartItem mapToEntity(CartItemDto cartItemDto){
130+
CartItem cartItem = modelMapper.map(cartItemDto, CartItem.class);
131+
return cartItem;
132+
}
133+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.manir.springbootecommercerestapi.service;
2+
3+
import com.manir.springbootecommercerestapi.dto.CartItemDto;
4+
5+
import java.util.List;
6+
7+
public interface ShoppingCartService {
8+
9+
List<CartItemDto> findByCustomerId(Long customerId);
10+
11+
CartItemDto addCartItem(Long customerId, Long productId, Integer quantity);
12+
13+
CartItemDto updateItemQuantity(Long customerId, Long productId, Integer quantity);
14+
15+
void deleteItemProduct(Long customerId, Long productId);
16+
}

0 commit comments

Comments
 (0)