Skip to content

Commit

Permalink
order management
Browse files Browse the repository at this point in the history
  • Loading branch information
casyazmon committed Jul 22, 2023
1 parent 89169c8 commit a1bb683
Show file tree
Hide file tree
Showing 12 changed files with 298 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public ResponseEntity<List<Category>> getAllCategories() {

@GetMapping("/{id}")
public ResponseEntity<?> getCategoryById(@PathVariable Long id) {
Optional<Category> category = categoryService.getCategoryById(id);
Category category = categoryService.getCategoryById(id);
return new ResponseEntity<>(category, HttpStatus.OK);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<List<Order>> getOrdersByUser(@PathVariable Long userId) {
User user = userService.getUserById(userId);
List<Order> orders = orderService.getOrdersByUser(user);
return ResponseEntity.ok(orders);
}

@GetMapping("/{orderId}")
public ResponseEntity<Order> getOrderById(@PathVariable Long orderId) {
User currentUser = userService.getCurrentUser();
Order order = orderService.getOrderByIdAndUser(orderId, currentUser);
return ResponseEntity.ok(order);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,19 @@ public ResponseEntity<List<Product>> getAllProducts() {

@GetMapping("/{id}")
public ResponseEntity<?> getProductById(@PathVariable Long id) {
Optional<Product> 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<List<Product>> product = productService.getUserProducts(id);
return new ResponseEntity<>(product, HttpStatus.OK);
}

@GetMapping("/category/{id}")
public ResponseEntity<?> getProductByCategory(@PathVariable Long id) {
Optional<List<Product>> product = productService.findProductByCategory(id);
return new ResponseEntity<>(product, HttpStatus.OK);
}

Expand All @@ -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<Void> 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");
}

}
17 changes: 17 additions & 0 deletions src/main/java/com/kasina/automobileapi/dto/OrderItemRequest.java
Original file line number Diff line number Diff line change
@@ -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;


}
18 changes: 18 additions & 0 deletions src/main/java/com/kasina/automobileapi/dto/OrderRequest.java
Original file line number Diff line number Diff line change
@@ -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<OrderItemRequest> items;
private BigDecimal price;
private String status;
private String shippingAddress;
// Add more fields for payment details, etc.
}
49 changes: 49 additions & 0 deletions src/main/java/com/kasina/automobileapi/model/Order.java
Original file line number Diff line number Diff line change
@@ -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<OrderItem> 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);
}


}
33 changes: 33 additions & 0 deletions src/main/java/com/kasina/automobileapi/model/OrderItem.java
Original file line number Diff line number Diff line change
@@ -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;



}
Original file line number Diff line number Diff line change
@@ -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<Order, Long> {
List<Order> findByUser(User user);
Optional<Order> findByIdAndUser(Long orderId, User user);
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -10,8 +11,9 @@
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

Optional<List<Product>> findByUser(User user);
// List<Product> findProductByCategory(Long catId);

Optional<List<Product>> findProductByUser(User user);
Optional<List<Product>> findByCategories(Category category);


}
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -27,8 +29,10 @@ public List<Category> getAllCategories() {
}

// Get a Category by ID
public Optional<Category> 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<Category> getCategoryByName(String name) {
Expand Down
65 changes: 65 additions & 0 deletions src/main/java/com/kasina/automobileapi/service/OrderService.java
Original file line number Diff line number Diff line change
@@ -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<Order> 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"));
}


}
Loading

0 comments on commit a1bb683

Please sign in to comment.