Commit 9cc1b0fb authored by Nikitha Moosapet's avatar Nikitha Moosapet

[nmoosapet]Implememted the Cart functionality and pushing the changes to Branch

parent 6d9c18bb
package com.nisum.ecomservice.controller;
import com.nisum.ecomservice.dto.CartDTO;
import com.nisum.ecomservice.model.CartItemEntity;
import com.nisum.ecomservice.repository.CartRepository;
import com.nisum.ecomservice.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@CrossOrigin(origins = "*")
public class CartController {
@Autowired
private CartService cartService;
@Autowired
private CartRepository cartRepository;
@GetMapping("/api/carts")
public ResponseEntity<Flux<CartDTO>>getAllUserCarts(){
return ResponseEntity.ok(cartService.getAllUsersCartItems());
}
@GetMapping("/api/carts/{userId}")
public ResponseEntity<Mono<CartDTO>>getCartByUserId(@PathVariable String userId) {
Mono<CartDTO> cartDto= cartService.getUserIdCartItems(userId);
HttpStatus status = cartDto != null ? HttpStatus.OK : HttpStatus.NOT_FOUND;
return new ResponseEntity<>(cartDto, status);
}
@PostMapping("/api/carts")
@ResponseStatus(HttpStatus.CREATED)
public Mono<CartDTO>addToCartByUserId(@RequestBody CartDTO cartDTO) {
return cartService.addUserIdItemsToCart(cartDTO);
}
@PutMapping("/api/carts/{userId}")
public Mono<ResponseEntity<CartDTO>>updateCartByUserId(@PathVariable String userId, @RequestBody CartDTO cartDTO){
return cartService.updateUserIdCartItems(userId, cartDTO)
.map(updatedItem->ResponseEntity.ok(updatedItem))
.defaultIfEmpty(ResponseEntity.badRequest().build());
}
@DeleteMapping("/api/carts/{userId}")
public Mono<ResponseEntity<Void>>deleteCartByUserId(@PathVariable String userId){
return cartService.deleteUserIdCartItems(userId)
.map(res-> ResponseEntity.ok().<Void>build())
.defaultIfEmpty(ResponseEntity.notFound().build());
}
}
\ No newline at end of file
package com.nisum.ecomservice.controller; package com.nisum.ecomservice.controller;
import com.nisum.ecomservice.model.CartItem;
import com.nisum.ecomservice.model.Product;
import com.nisum.ecomservice.model.User; import com.nisum.ecomservice.model.User;
import com.nisum.ecomservice.repository.UserRepository; import com.nisum.ecomservice.repository.UserRepository;
import com.nisum.ecomservice.service.UserService; import com.nisum.ecomservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController @RestController
@RequestMapping("/api/users") @RequestMapping("/api/users")
......
package com.nisum.ecomservice.dto;
import lombok.*;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Data
public class CartDTO {
private String userId;
private List<CartItemDTO> cartItems;
}
package com.nisum.ecomservice.dto;
import com.nisum.ecomservice.model.ProductRef;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@Data
@NoArgsConstructor
public class CartItemDTO {
private ProductRef productRef;
private Integer quantity;
}
package com.nisum.ecomservice.dto; package com.nisum.ecomservice.dto;
import com.nisum.ecomservice.model.Address; import com.nisum.ecomservice.model.Address;
import com.nisum.ecomservice.model.Cart; import com.nisum.ecomservice.model.CartEntity;
import com.nisum.ecomservice.model.User; import com.nisum.ecomservice.model.User;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
...@@ -13,5 +13,5 @@ import lombok.Setter; ...@@ -13,5 +13,5 @@ import lombok.Setter;
public class OrderRequest { public class OrderRequest {
private User user; private User user;
private Address address; private Address address;
private Cart cart; private CartEntity cartEntity;
} }
package com.nisum.ecomservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE)
public class ResourceAlreadyExistsException extends RuntimeException {
public ResourceAlreadyExistsException() {
super("A User with the provided userId already exists");
}
}
package com.nisum.ecomservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends Exception{
HttpStatus status;
public ResourceNotFoundException(HttpStatus status, String message) {
super(message);
this.status = status;
}
}
package com.nisum.ecomservice.model; package com.nisum.ecomservice.model;
import lombok.AllArgsConstructor; import lombok.*;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List; import java.util.List;
@Document(collection = "carts")
@Getter @Getter
@Setter @Setter
@AllArgsConstructor @AllArgsConstructor
public class Cart { @NoArgsConstructor
@Data
@Document(collection = "carts")
public class CartEntity {
@Id @Id
private String id;
private String userId; private String userId;
private List<CartItem> cartItems; private List<CartItemEntity> cartItems;
} }
package com.nisum.ecomservice.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@AllArgsConstructor
@ToString
@Data
public class CartItem {
private ProductRef productRef;
private Integer quantity;
@Override
public String toString() {
return "CartItem{" +
"productRef = " + productRef + '\'' +
", quantity = " + quantity +
'}';
}
}
package com.nisum.ecomservice.model;
import lombok.*;
import org.springframework.data.mongodb.core.mapping.Document;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Data
public class CartItemEntity {
private ProductRef productRef;
private Integer quantity;
}
package com.nisum.ecomservice.repository;
import com.nisum.ecomservice.model.CartEntity;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
public interface CartRepository extends ReactiveMongoRepository<CartEntity, String> {
}
package com.nisum.ecomservice.repository; package com.nisum.ecomservice.repository;
import com.nisum.ecomservice.model.CartItem;
import com.nisum.ecomservice.model.User; import com.nisum.ecomservice.model.User;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Repository
public interface UserRepository extends ReactiveMongoRepository<User, String> { public interface UserRepository extends ReactiveMongoRepository<User, String> {
} }
package com.nisum.ecomservice.service;
import com.nisum.ecomservice.dto.CartDTO;
import com.nisum.ecomservice.dto.CartItemDTO;
import com.nisum.ecomservice.exception.ResourceNotFoundException;
import com.nisum.ecomservice.model.CartEntity;
import com.nisum.ecomservice.model.CartItemEntity;
import com.nisum.ecomservice.repository.CartRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class CartService {
@Autowired
private CartRepository cartRepository;
public Flux<CartDTO> getAllUsersCartItems() {
return cartRepository.findAll().map(cartItems->convertEntitytoDTO(cartItems));
}
public Mono<CartDTO> getUserIdCartItems(String userId){
return cartRepository.findById(userId)
.map(existingItems->convertEntitytoDTO(existingItems))
.switchIfEmpty(Mono.error(new ResourceNotFoundException(HttpStatus.NOT_FOUND,
"CartItem for UserId" + userId + "not found")));
}
public Mono<CartDTO>addUserIdItemsToCart(CartDTO cartDTO) {
cartRepository.deleteById(cartDTO.getUserId());
Mono<CartEntity> cartEntityDB= cartRepository.save(convertDTOtoEntity(cartDTO));
return cartEntityDB.map(newItem->convertEntitytoDTO(newItem));
}
public Mono<CartDTO>updateUserIdCartItems(String userId, CartDTO cartDTO) {
Mono<CartEntity> cartEntityDB= cartRepository.save(convertDTOtoEntity(cartDTO));
return cartEntityDB.map(updatedItem->convertEntitytoDTO(updatedItem));
}
public Mono<CartEntity> deleteUserIdCartItems(String userId) {
return cartRepository.findById(userId)
.flatMap(existingCartItem->
cartRepository.delete(existingCartItem)
.then(Mono.just(existingCartItem)))
.switchIfEmpty(Mono.error(new ResourceNotFoundException(HttpStatus.NOT_FOUND,
"CartItem for UserId" + userId + "not found")));
}
private CartDTO convertEntitytoDTO(CartEntity cartEntity){
CartDTO cartDTO=new CartDTO();
cartDTO.setUserId(cartEntity.getUserId());
List<CartItemDTO> cartItemDtos= Optional.ofNullable(cartEntity.getCartItems()).orElse(new ArrayList<>())
.stream().map(entity->{
CartItemDTO cartItemDTO=new CartItemDTO();
cartItemDTO.setProductRef(entity.getProductRef());
cartItemDTO.setQuantity(entity.getQuantity());
return cartItemDTO;})
.collect(Collectors.toList());
cartDTO.setCartItems(cartItemDtos);
return cartDTO;
}
private CartEntity convertDTOtoEntity(CartDTO cartDTO){
CartEntity cartEntity=new CartEntity();
cartEntity.setUserId(cartDTO.getUserId());
List<CartItemEntity> cartItemEntities= Optional.ofNullable(cartDTO.getCartItems()).orElse(new ArrayList<>()).stream().map(dto->{
CartItemEntity cartItemEntity=new com.nisum.ecomservice.model.CartItemEntity();
cartItemEntity.setProductRef(dto.getProductRef());
cartItemEntity.setQuantity(dto.getQuantity());
return cartItemEntity;})
.collect(Collectors.toList());
cartEntity.setCartItems(cartItemEntities);
return cartEntity;
}
}
\ No newline at end of file
...@@ -26,10 +26,10 @@ public class OrderService { ...@@ -26,10 +26,10 @@ public class OrderService {
//create user object from user object details //create user object from user object details
User user = orderRequest.getUser(); User user = orderRequest.getUser();
Address address = orderRequest.getAddress(); Address address = orderRequest.getAddress();
Cart cart = orderRequest.getCart(); CartEntity cartEntity = orderRequest.getCartEntity();
//for each item grab product details from products API //for each item grab product details from products API
List<Mono<Product>> productsToOrder = cart.getCartItems().stream() List<Mono<Product>> productsToOrder = cartEntity.getCartItems().stream()
.map(cartItem -> cartItem.getProductRef().getSku()) .map(cartItem -> cartItem.getProductRef().getSku())
.map(sku -> productService.getProductBySku(sku)) .map(sku -> productService.getProductBySku(sku))
...@@ -44,7 +44,7 @@ public class OrderService { ...@@ -44,7 +44,7 @@ public class OrderService {
orderItem.setItemSku(product.getSku()); orderItem.setItemSku(product.getSku());
orderItem.setItemPrice(product.getPrice()); orderItem.setItemPrice(product.getPrice());
List<CartItem> items = cart.getCartItems().stream().filter(cartItem -> cartItem.getProductRef().getSku() List<CartItemEntity> items = cartEntity.getCartItems().stream().filter(cartItem -> cartItem.getProductRef().getSku()
.equals(product.getSku())) .equals(product.getSku()))
.collect(Collectors.toList()); .collect(Collectors.toList());
......
package com.nisum.ecomservice.service; package com.nisum.ecomservice.service;
import com.nisum.ecomservice.model.CartItem;
import com.nisum.ecomservice.model.User; import com.nisum.ecomservice.model.User;
import com.nisum.ecomservice.repository.UserRepository; import com.nisum.ecomservice.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service @Service
public class UserService { public class UserService {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment