in google console I have this problem
POST http://localhost:8080/api/customer/cart 409 (Conflict)
dashboard.component.ts:54 ERROR HttpErrorResponse {headers: _HttpHeaders, status: 409, statusText: ‘OK’, url: ‘http://localhost:8080/api/customer/cart’, ok: false, …}
And then when i click add to cart in other product i have this problem
dashboard.component.ts:54
POST http://localhost:8080/api/customer/cart 403 (Forbidden)
dashboard.component.ts:54 ERROR HttpErrorResponse {headers: _HttpHeaders, status: 403, statusText: ‘OK’, url: ‘http://localhost:8080/api/customer/cart’, ok: false, …}
and in the backend and in the backend this error appears:
WARN 24432 : SQL Error: 1062, SQLState: 23000
ERROR 24432 : Duplicate entry ‘1’ for key ‘cart_items.UKshvxaq4vg05f3q75fnnel0klb’
ERROR 24432 : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.DataIntegrityViolationException: could not execute statement [Duplicate entry ‘1’ for key ‘cart_items.UKshvxaq4vg05f3q75fnnel0klb’] [insert into cart_items (order_id,price,product_id,quantity,user_id) values (?,?,?,?,?)]; SQL [insert into cart_items (order_id,price,product_id,quantity,user_id) values (?,?,?,?,?)]; constraint [cart_items.UKshvxaq4vg05f3q75fnnel0klb]] with root cause
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry ‘1’ for key ‘cart_items.UKshvxaq4vg05f3q75fnnel0klb’
CartItems.java
@Entity
@Data
public class CartItems {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long price;
private Long quantity;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "product_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Product product;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private User user;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id")
private Order order;
public CartItemsDto getCartDto() {
CartItemsDto cartItemsDto = new CartItemsDto();
cartItemsDto.setId(id);
cartItemsDto.setPrice(price);
cartItemsDto.setProductId(product.getId());
cartItemsDto.setQuantity(quantity);
cartItemsDto.setUserId(user.getId());
cartItemsDto.setProductName(product.getName());
cartItemsDto.setReturnedImg(product.getImg());
return cartItemsDto;
}
}
AddProductToCartDto
@Data
public class AddProductInCartDto {
private Long userId;
private Long productId;
}
CartItemsRepository
@Repository
public interface CartItemsRepository extends JpaRepository<CartItems, Long> {
Optional<CartItems> findByProductIdAndOrderIdAndUserId (Long productId, Long orderId, Long userId);
}
CartService
public interface CartService {
ResponseEntity<?> addProductToCart(AddProductInCartDto addProductInCartDto);
OrderDto getCardByUserId(Long userId);
}
CartServiceImpl
@Service
public class CartServiceImpl implements CartService{
@Autowired
private OrderRepository orderRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private CartItemsRepository cartItemsRepository;
@Autowired
private ProductRepository productRepository;
public ResponseEntity<?> addProductToCart(AddProductInCartDto addProductInCartDto){
Order activeOrder = orderRepository.findByUserIdAndOrderStatus(addProductInCartDto.getUserId(), OrderStatus.Pending);
Optional<CartItems> optionalCartItems = cartItemsRepository.findByProductIdAndOrderIdAndUserId
(addProductInCartDto.getProductId(), activeOrder.getId(), addProductInCartDto.getUserId());
if(optionalCartItems.isPresent()) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(null);
}else {
Optional<Product> optionalProduct = productRepository.findById(addProductInCartDto.getProductId());
Optional<User> optionalUser = userRepository.findById(addProductInCartDto.getUserId());
if(optionalProduct.isPresent() && optionalUser.isPresent()) {
CartItems cart = new CartItems();
cart.setProduct(optionalProduct.get());
cart.setPrice(optionalProduct.get().getPrice());
cart.setQuantity(1L);
cart.setUser(optionalUser.get());
cart.setOrder(activeOrder);
CartItems updatedCart = cartItemsRepository.save(cart);
activeOrder.setTotalAmount(activeOrder.getTotalAmount() + cart.getPrice());
activeOrder.setAmount(activeOrder.getAmount() + cart.getPrice());
activeOrder.getCartItems().add(cart);
orderRepository.save(activeOrder);
return ResponseEntity.status(HttpStatus.CREATED).body(cart.getId());
}else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User or product not found");
}
}
}
public OrderDto getCardByUserId(Long userId) {
Order activeOrder = orderRepository.findByUserIdAndOrderStatus(userId, OrderStatus.Pending);
List<CartItemsDto> cartItemsDtoList = activeOrder.getCartItems().stream().map(CartItems::getCartDto).collect(Collectors.toList());
OrderDto orderDto = new OrderDto();
orderDto.setAmount(activeOrder.getAmount());
orderDto.setId(activeOrder.getId());
orderDto.setOrderStatus(activeOrder.getOrderStatus());
orderDto.setDiscount(activeOrder.getDiscount());
orderDto.setTotalAmount(activeOrder.getTotalAmount());
orderDto.setCartItems(cartItemsDtoList);
return orderDto;
}
}
CartController
@RestController
@RequestMapping("/api/customer")
@RequiredArgsConstructor
public class CartController {
private final CartService cartService;
@PostMapping("/cart")
public ResponseEntity<?> addProductToCart(@RequestBody AddProductInCartDto addProductInCartDto){
return cartService.addProductToCart(addProductInCartDto);
}
@GetMapping("/cart/{userId}")
public ResponseEntity<?> getCartByUserId(@PathVariable Long userId){
OrderDto orderDto = cartService.getCardByUserId(userId);
return ResponseEntity.status(HttpStatus.OK).body(orderDto);
}
}
WebSecurityConfiguration
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfiguration {
private final JwtRequestFilter authFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf
.disable())
.authorizeHttpRequests(requests -> requests
.requestMatchers("/authenticate", "/sign-up", "/order/**", "/api/admin/category",
"/api/admin", "/api/admin/product", "/api/admin/products", "/api/admin/search/{name}",
"/api/admin/product/{productId}", "/api/customer/search/{name}", "/api/customer/products",
"/api/customer/cart")
.permitAll())
.authorizeHttpRequests(requests -> requests
.requestMatchers("/api/**")
.authenticated())
.sessionManagement(management -> management
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
return config.getAuthenticationManager();
}
}
AND THAT’S WHAT I CALLED IT IN ANGULAR
customer.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { UserStorageService } from '../../services/storage/user-storage.service';
const BASIC_URL = "http://localhost:8080/"
@Injectable({
providedIn: 'root'
})
export class CustomerService {
constructor(private http: HttpClient) { }
getAllProducts(): Observable<any>{
return this.http.get(BASIC_URL + 'api/customer/products', {
headers: this.createAuthorizationHeader(),
})
}
getAllProductsByName(name:any): Observable<any>{
return this.http.get(BASIC_URL + `api/customer/search/${name}`, {
headers: this.createAuthorizationHeader(),
})
}
addToCart(productId:any): Observable<any>{
const cartDto = {
productId : productId,
userId: UserStorageService.getUserId()
}
return this.http.post(BASIC_URL + 'api/customer/cart', cartDto ,{
headers: this.createAuthorizationHeader(),
})
}
private createAuthorizationHeader(): HttpHeaders{
return new HttpHeaders().set(
'Authorization', 'Bearer ' + UserStorageService.getToken()
)
}
}
dashboard.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomerService } from '../../services/customer.service';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.scss'
})
export class DashboardComponent {
products: any[] = [];
searchProductForm!: FormGroup;
constructor(
private customerService: CustomerService,
private fb:FormBuilder,
private snackBar: MatSnackBar)
{}
ngOnInit(){
this.getAllProducts();
this.searchProductForm = this.fb.group({
title: [null, [Validators.required]]
})
}
getAllProducts(){
this.products = [];
this.customerService.getAllProducts().subscribe(res =>{
res.forEach(element => {
element.processedImg = 'data:/image/jpeg;base64,' + element.byteImg
this.products.push(element);
});
console.log(this.products)
})
}
submitForm(){
this.products = [];
const title = this.searchProductForm.get('title')!.value;
this.customerService.getAllProductsByName(title).subscribe(res =>{
res.forEach(element => {
element.processedImg = 'data:/image/jpeg;base64,' + element.byteImg
this.products.push(element);
});
console.log(this.products)
})
}
addToCart(id:any){
this.customerService.addToCart(id).subscribe(res =>{
this.snackBar.open('Product added to the cart successfully', 'Close', { duration: 5000 })
})
}
}
Julian Delgado is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.