From a1bb6831c29eebe5c797ba7676b7607480f4b58b Mon Sep 17 00:00:00 2001 From: casyazmon Date: Sun, 23 Jul 2023 00:48:14 +0100 Subject: [PATCH] order management --- .../controller/CategoryController.java | 2 +- .../controller/OrderController.java | 44 +++++++++++++ .../controller/ProductController.java | 24 ++++++- .../automobileapi/dto/OrderItemRequest.java | 17 +++++ .../automobileapi/dto/OrderRequest.java | 18 +++++ .../com/kasina/automobileapi/model/Order.java | 49 ++++++++++++++ .../kasina/automobileapi/model/OrderItem.java | 33 ++++++++++ .../repository/OrderRepository.java | 15 +++++ .../repository/ProductRepository.java | 6 +- .../service/CategoryService.java | 8 ++- .../automobileapi/service/OrderService.java | 65 +++++++++++++++++++ .../automobileapi/service/ProductService.java | 48 +++++++------- 12 files changed, 298 insertions(+), 31 deletions(-) create mode 100644 src/main/java/com/kasina/automobileapi/controller/OrderController.java create mode 100644 src/main/java/com/kasina/automobileapi/dto/OrderItemRequest.java create mode 100644 src/main/java/com/kasina/automobileapi/dto/OrderRequest.java create mode 100644 src/main/java/com/kasina/automobileapi/model/Order.java create mode 100644 src/main/java/com/kasina/automobileapi/model/OrderItem.java create mode 100644 src/main/java/com/kasina/automobileapi/repository/OrderRepository.java create mode 100644 src/main/java/com/kasina/automobileapi/service/OrderService.java diff --git a/src/main/java/com/kasina/automobileapi/controller/CategoryController.java b/src/main/java/com/kasina/automobileapi/controller/CategoryController.java index 3eaeea9..9d09395 100644 --- a/src/main/java/com/kasina/automobileapi/controller/CategoryController.java +++ b/src/main/java/com/kasina/automobileapi/controller/CategoryController.java @@ -25,7 +25,7 @@ public ResponseEntity> getAllCategories() { @GetMapping("/{id}") public ResponseEntity getCategoryById(@PathVariable Long id) { - Optional category = categoryService.getCategoryById(id); + Category category = categoryService.getCategoryById(id); return new ResponseEntity<>(category, HttpStatus.OK); } diff --git a/src/main/java/com/kasina/automobileapi/controller/OrderController.java b/src/main/java/com/kasina/automobileapi/controller/OrderController.java new file mode 100644 index 0000000..d52d3e2 --- /dev/null +++ b/src/main/java/com/kasina/automobileapi/controller/OrderController.java @@ -0,0 +1,44 @@ +package com.kasina.automobileapi.controller; + +import com.kasina.automobileapi.dto.OrderRequest; +import com.kasina.automobileapi.dto.ProductDto; +import com.kasina.automobileapi.model.Order; +import com.kasina.automobileapi.model.Product; +import com.kasina.automobileapi.model.User; +import com.kasina.automobileapi.service.OrderService; +import com.kasina.automobileapi.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.crossstore.ChangeSetPersister; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/categories") +@RequiredArgsConstructor +public class OrderController { + private final OrderService orderService; + private final UserService userService; + + + @PostMapping + public ResponseEntity createOrder(@RequestBody OrderRequest orderRequest){ + Order order = orderService.createOrder(orderRequest); + return ResponseEntity.ok(order); + } + + @GetMapping("/user/{userId}") + public ResponseEntity> getOrdersByUser(@PathVariable Long userId) { + User user = userService.getUserById(userId); + List orders = orderService.getOrdersByUser(user); + return ResponseEntity.ok(orders); + } + + @GetMapping("/{orderId}") + public ResponseEntity getOrderById(@PathVariable Long orderId) { + User currentUser = userService.getCurrentUser(); + Order order = orderService.getOrderByIdAndUser(orderId, currentUser); + return ResponseEntity.ok(order); + } +} diff --git a/src/main/java/com/kasina/automobileapi/controller/ProductController.java b/src/main/java/com/kasina/automobileapi/controller/ProductController.java index f9d36de..9e0f2cd 100644 --- a/src/main/java/com/kasina/automobileapi/controller/ProductController.java +++ b/src/main/java/com/kasina/automobileapi/controller/ProductController.java @@ -24,7 +24,19 @@ public ResponseEntity> getAllProducts() { @GetMapping("/{id}") public ResponseEntity getProductById(@PathVariable Long id) { - Optional product = productService.getProductById(id); + Product product = productService.getProductById(id); + return new ResponseEntity<>(product, HttpStatus.OK); + } + + @GetMapping("/user/{id}") + public ResponseEntity getProductByUser(@PathVariable Long id) { + Optional> product = productService.getUserProducts(id); + return new ResponseEntity<>(product, HttpStatus.OK); + } + + @GetMapping("/category/{id}") + public ResponseEntity getProductByCategory(@PathVariable Long id) { + Optional> product = productService.findProductByCategory(id); return new ResponseEntity<>(product, HttpStatus.OK); } @@ -35,10 +47,16 @@ public ResponseEntity addProduct(@RequestBody ProductDto productDto){ return ResponseEntity.ok(product); } + @PutMapping("/{productId}") + public ResponseEntity updateProduct(@RequestBody ProductDto productDto, @PathVariable Long productId){ + Product product = productService.updateProduct(productDto,productId); + return ResponseEntity.ok(product); + } + @DeleteMapping("/{id}") - public ResponseEntity deleteProduct(@PathVariable Long id) { + public ResponseEntity deleteProduct(@PathVariable Long id) { productService.deleteProductById(id); - return new ResponseEntity<>(HttpStatus.NO_CONTENT); + return ResponseEntity.ok("Product deleted successfully"); } } diff --git a/src/main/java/com/kasina/automobileapi/dto/OrderItemRequest.java b/src/main/java/com/kasina/automobileapi/dto/OrderItemRequest.java new file mode 100644 index 0000000..d52b2e3 --- /dev/null +++ b/src/main/java/com/kasina/automobileapi/dto/OrderItemRequest.java @@ -0,0 +1,17 @@ +package com.kasina.automobileapi.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.RequiredArgsConstructor; + +import java.math.BigDecimal; +@Data +@RequiredArgsConstructor +@AllArgsConstructor +public class OrderItemRequest { + private Long productId; + private int quantity; + private BigDecimal subTotal; + + +} diff --git a/src/main/java/com/kasina/automobileapi/dto/OrderRequest.java b/src/main/java/com/kasina/automobileapi/dto/OrderRequest.java new file mode 100644 index 0000000..546433c --- /dev/null +++ b/src/main/java/com/kasina/automobileapi/dto/OrderRequest.java @@ -0,0 +1,18 @@ +package com.kasina.automobileapi.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.RequiredArgsConstructor; + +import java.math.BigDecimal; +import java.util.List; +@Data +@RequiredArgsConstructor +@AllArgsConstructor +public class OrderRequest { + private List items; + private BigDecimal price; + private String status; + private String shippingAddress; + // Add more fields for payment details, etc. +} diff --git a/src/main/java/com/kasina/automobileapi/model/Order.java b/src/main/java/com/kasina/automobileapi/model/Order.java new file mode 100644 index 0000000..1b11dc8 --- /dev/null +++ b/src/main/java/com/kasina/automobileapi/model/Order.java @@ -0,0 +1,49 @@ +package com.kasina.automobileapi.model; + +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import org.springframework.data.annotation.CreatedDate; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Setter +@Getter +@Builder +@Entity +@Table(name = "orders") +@RequiredArgsConstructor +public class Order { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @CreatedDate + private LocalDateTime orderDate; + private String status; + private String shippingAddress; + private BigDecimal totalPrice; + + @ManyToOne + @JoinColumn(name = "user_id") + private User user; + + @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) + private List orderItems = new ArrayList<>(); + + public void addOrderItem(OrderItem orderItem) { + orderItems.add(orderItem); + orderItem.setOrder(this); + } + + public void removeOrderItem(OrderItem orderItem) { + orderItems.remove(orderItem); + orderItem.setOrder(null); + } + + +} diff --git a/src/main/java/com/kasina/automobileapi/model/OrderItem.java b/src/main/java/com/kasina/automobileapi/model/OrderItem.java new file mode 100644 index 0000000..8f9a8a7 --- /dev/null +++ b/src/main/java/com/kasina/automobileapi/model/OrderItem.java @@ -0,0 +1,33 @@ +package com.kasina.automobileapi.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.math.BigDecimal; + +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Entity +public class OrderItem { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @ManyToOne + @JoinColumn(name = "product_id") + private Product product; + private int quantity; + private BigDecimal subTotal; + + @ManyToOne + @JsonIgnore + private Order order; + + + +} diff --git a/src/main/java/com/kasina/automobileapi/repository/OrderRepository.java b/src/main/java/com/kasina/automobileapi/repository/OrderRepository.java new file mode 100644 index 0000000..83d8187 --- /dev/null +++ b/src/main/java/com/kasina/automobileapi/repository/OrderRepository.java @@ -0,0 +1,15 @@ +package com.kasina.automobileapi.repository; + +import com.kasina.automobileapi.model.Order; +import com.kasina.automobileapi.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface OrderRepository extends JpaRepository { + List findByUser(User user); + Optional findByIdAndUser(Long orderId, User user); +} diff --git a/src/main/java/com/kasina/automobileapi/repository/ProductRepository.java b/src/main/java/com/kasina/automobileapi/repository/ProductRepository.java index 43d4337..398ad55 100644 --- a/src/main/java/com/kasina/automobileapi/repository/ProductRepository.java +++ b/src/main/java/com/kasina/automobileapi/repository/ProductRepository.java @@ -1,5 +1,6 @@ package com.kasina.automobileapi.repository; +import com.kasina.automobileapi.model.Category; import com.kasina.automobileapi.model.Product; import com.kasina.automobileapi.model.User; import org.springframework.data.jpa.repository.JpaRepository; @@ -10,8 +11,9 @@ @Repository public interface ProductRepository extends JpaRepository { - Optional> findByUser(User user); -// List findProductByCategory(Long catId); + + Optional> findProductByUser(User user); + Optional> findByCategories(Category category); } diff --git a/src/main/java/com/kasina/automobileapi/service/CategoryService.java b/src/main/java/com/kasina/automobileapi/service/CategoryService.java index 7366259..f748934 100644 --- a/src/main/java/com/kasina/automobileapi/service/CategoryService.java +++ b/src/main/java/com/kasina/automobileapi/service/CategoryService.java @@ -1,12 +1,14 @@ package com.kasina.automobileapi.service; import com.kasina.automobileapi.model.Category; +import com.kasina.automobileapi.model.User; import com.kasina.automobileapi.repository.CategoryRepository; import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; +import java.util.NoSuchElementException; import java.util.Optional; @Service @@ -27,8 +29,10 @@ public List getAllCategories() { } // Get a Category by ID - public Optional getCategoryById(Long CategoryId) { - return categoryRepository.findById(CategoryId); + + public Category getCategoryById(Long userId) { + return categoryRepository.findById(userId) + .orElseThrow(() -> new NoSuchElementException("Category not found with ID: " + userId)); } public Optional getCategoryByName(String name) { diff --git a/src/main/java/com/kasina/automobileapi/service/OrderService.java b/src/main/java/com/kasina/automobileapi/service/OrderService.java new file mode 100644 index 0000000..440ff0a --- /dev/null +++ b/src/main/java/com/kasina/automobileapi/service/OrderService.java @@ -0,0 +1,65 @@ +package com.kasina.automobileapi.service; + +import com.kasina.automobileapi.dto.OrderItemRequest; +import com.kasina.automobileapi.dto.OrderRequest; +import com.kasina.automobileapi.model.Order; +import com.kasina.automobileapi.model.OrderItem; +import com.kasina.automobileapi.model.Product; +import com.kasina.automobileapi.model.User; +import com.kasina.automobileapi.repository.OrderRepository; +import com.kasina.automobileapi.repository.ProductRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.crossstore.ChangeSetPersister; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class OrderService { + private final OrderRepository orderRepository; + private final ProductRepository productRepository; + private final UserService userService; + + + public Order createOrder(OrderRequest orderRequest) { + User currentUser = userService.getCurrentUser(); + BigDecimal grandTotal = BigDecimal.ZERO; + + // Create the order entity + Order order = new Order(); + order.setUser(currentUser); + order.setStatus(orderRequest.getStatus()); + order.setShippingAddress(orderRequest.getShippingAddress()); + + + // Create order items and add them to the order + for (OrderItemRequest itemRequest : orderRequest.getItems()) { + OrderItem orderItem = new OrderItem(); + Product product = productRepository.findById(itemRequest.getProductId()) + .orElseThrow(() -> new IllegalArgumentException("Product not found")); + + orderItem.setProduct(product); + orderItem.setQuantity(itemRequest.getQuantity()); + orderItem.setSubTotal(product.getPrice().multiply(BigDecimal.valueOf(itemRequest.getQuantity()))); + + // Calculate and set other order item attributes if needed + + order.addOrderItem(orderItem); + } + + // Save the order in the database + return orderRepository.save(order); + } + + public List getOrdersByUser(User user) { + return orderRepository.findByUser(user); + } + public Order getOrderByIdAndUser(Long orderId, User user) { + return orderRepository.findByIdAndUser(orderId, user) + .orElseThrow(() -> new IllegalArgumentException("Order not found")); + } + + +} diff --git a/src/main/java/com/kasina/automobileapi/service/ProductService.java b/src/main/java/com/kasina/automobileapi/service/ProductService.java index b9720e4..7eb89e9 100644 --- a/src/main/java/com/kasina/automobileapi/service/ProductService.java +++ b/src/main/java/com/kasina/automobileapi/service/ProductService.java @@ -6,6 +6,7 @@ import com.kasina.automobileapi.dto.UrlErrorResponseDto; import com.kasina.automobileapi.model.User; import com.kasina.automobileapi.repository.ProductRepository; +import com.kasina.automobileapi.repository.UserRepository; import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; @@ -41,7 +42,6 @@ public Product createProduct(ProductDto productDto) { for (String categoryName : productDto.getCategories()) { Category category = categoryService.getDefaultCategory(categoryName); - System.out.println("******##*#**# CATEGORY NAME: " + category.getName() +"**********"); categories.add(category); } product.setCategories(categories); @@ -50,23 +50,28 @@ public Product createProduct(ProductDto productDto) { } public Product updateProduct(ProductDto productDto, Long id){ + Set categories = new HashSet<>(); User currentUser = userService.getCurrentUser(); - Product existingProduct = productRepository.findById(id) - .orElseThrow(() -> new IllegalArgumentException("Product not found")); - - - existingProduct = Product.builder() + Product product = getProductById(id); + product = Product.builder() .name(productDto.getName()) .description(productDto.getDescription()) .shortDescription(productDto.getShortDescription()) .price(productDto.getPrice()) .image(productDto.getImage()) - .user(currentUser) .build(); - return productRepository.save(existingProduct); - } + // Then, associate the product with the specified categories + for (String categoryName : productDto.getCategories()) { + Category category = categoryService.getDefaultCategory(categoryName); + categories.add(category); + } + product.setCategories(categories); + + return productRepository.save(product); + + } // Get all products public List getAllProducts() { @@ -74,14 +79,12 @@ public List getAllProducts() { } // Get a product by ID - public Optional getProductById(Long productId) { - return productRepository.findById(productId); + public Product getProductById(Long productId) { + return productRepository.findById(productId).orElseThrow(() -> new IllegalArgumentException("Product not found")); } // Update a product - public Product updateProduct(Product updatedProduct) { - return productRepository.save(updatedProduct); - } + // Delete a product by ID public void deleteProductById(Long productId) { @@ -89,14 +92,13 @@ public void deleteProductById(Long productId) { } - public Optional> getUserProducts() { - User currentUser = userService.getCurrentUser(); - if (currentUser == null){ - UrlErrorResponseDto urlErrorResponseDto = new UrlErrorResponseDto(); - urlErrorResponseDto.setStatus("User not found"); - urlErrorResponseDto.setError("422"); - return Optional.empty(); - } - return productRepository.findByUser(currentUser); + public Optional> getUserProducts(Long userId) { + User currentUser = userService.getUserById(userId); + return productRepository.findProductByUser(currentUser); + } + + public Optional> findProductByCategory(Long catId) { + Category category = categoryService.getCategoryById(catId); + return productRepository.findByCategories(category); } }