Skip to content

Commit

Permalink
fix: fix error save order items
Browse files Browse the repository at this point in the history
  • Loading branch information
ngntu10 committed Oct 15, 2024
1 parent 0696dd5 commit af37b70
Show file tree
Hide file tree
Showing 13 changed files with 130 additions and 32 deletions.
3 changes: 2 additions & 1 deletion src/main/java/com/Optimart/controllers/OrderController.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.Optimart.dto.Order.CreateOrderDTO;
import com.Optimart.models.Order;
import com.Optimart.responses.APIResponse;
import com.Optimart.responses.Order.OrderResponse;
import com.Optimart.responses.User.UserResponse;
import com.Optimart.services.Order.OrderService;
import io.swagger.v3.oas.annotations.media.ArraySchema;
Expand All @@ -29,7 +30,7 @@ public class OrderController {
@ApiResponse(responseCode = "201", description = "CREATED", content = @Content(schema = @Schema(implementation = Object.class), mediaType = "application/json"))
@SecuredSwaggerOperation(summary = "Create a new order")
@PostMapping
public ResponseEntity<APIResponse<Order>> createOrder(@RequestBody CreateOrderDTO createOrderDTO){
public ResponseEntity<APIResponse<OrderResponse>> createOrder(@RequestBody CreateOrderDTO createOrderDTO){
return ResponseEntity.ok(orderService.createOrder(createOrderDTO));
}

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/Optimart/dto/Order/CreateOrderDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.Optimart.dto.OrderItem.OrderItemsDTO;
import com.Optimart.dto.ShippingAddress.ShippingAddressDTO;
import com.Optimart.models.City;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
Expand All @@ -18,7 +19,7 @@
@NoArgsConstructor
public class CreateOrderDTO {
private String address;
private String city;
private City city;
private String deliveryMethod;
private String fullName;
private Long itemsPrice;
Expand Down
11 changes: 6 additions & 5 deletions src/main/java/com/Optimart/models/Order.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.Optimart.models;

import com.Optimart.enums.OrderStatus;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;

Expand All @@ -21,7 +22,7 @@ public class Order extends BaseEntity {
@Column(name = "id")
private UUID id;

@OneToMany(mappedBy = "order")
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderItem> orderItemList;

@ManyToOne
Expand All @@ -32,7 +33,7 @@ public class Order extends BaseEntity {
@JoinColumn(name = "deliveryType_id", nullable = false)
private DeliveryType deliveryMethod;

@Column(name = "itemsPrice" , nullable = false)
@Column(name = "itemsPrice")
private Long itemsPrice;

@Column(name = "shippingPrice", nullable = false)
Expand All @@ -41,6 +42,7 @@ public class Order extends BaseEntity {
@Column(name = "totalPrice", nullable = false)
private Long totalPrice;

@JsonIgnore
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
Expand All @@ -57,9 +59,8 @@ public class Order extends BaseEntity {
@Column(name = "deliveryAt")
private Date deliveryAt = new Date();

@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private OrderStatus orderStatus = OrderStatus.WAIT_DELIVERY;
@Column(name = "status")
private int orderStatus = 0;

@ManyToOne
@JoinColumn(name = "shippingAddress_id")
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/com/Optimart/models/OrderItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public class OrderItem extends BaseEntity {
@JoinColumn(name = "order_id")
private Order order;

@ManyToOne
@JsonIgnore
@JoinColumn(name = "product_id")
private Product product;
// @ManyToOne
// @JsonIgnore
// @JoinColumn(name = "product_id")
// private Product product;
}
2 changes: 0 additions & 2 deletions src/main/java/com/Optimart/models/Paymenttype.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,4 @@ public class Paymenttype extends BaseEntity {
private String type;




}
2 changes: 2 additions & 0 deletions src/main/java/com/Optimart/models/ShippingAddress.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.Optimart.models;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;

Expand Down Expand Up @@ -32,6 +33,7 @@ public class ShippingAddress extends BaseEntity {
@JoinColumn(name = "city_id", nullable = false)
private City city;

@JsonIgnore
@OneToMany(mappedBy = "shippingAddress")
private List<Order> orderList;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.Optimart.repositories;

import com.Optimart.models.OrderItem;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.UUID;

public interface OrderItemRepository extends JpaRepository<OrderItem, UUID> {
}
5 changes: 5 additions & 0 deletions src/main/java/com/Optimart/repositories/OrderRepository.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package com.Optimart.repositories;

import com.Optimart.models.Order;
import com.Optimart.models.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.UUID;

public interface OrderRepository extends JpaRepository<Order, UUID> {
Page<Order> findAll(Specification<Order> specification, Pageable pageable);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.Optimart.repositories;

import com.Optimart.models.Paymenttype;
import com.Optimart.models.ShippingAddress;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.UUID;

public interface ShippingAddressRepository extends JpaRepository<ShippingAddress, UUID> {
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,41 @@
package com.Optimart.repositories.Specification;

import com.Optimart.models.Order;
import jakarta.persistence.criteria.JoinType;
import org.springframework.data.jpa.domain.Specification;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class OrderSpecification {
public static Specification<Order> byStatus(String status){
return (root, query, criteriaBuilder) -> {
if (status == null || status.isEmpty()) {
return criteriaBuilder.conjunction();
}
List<String> statusList = Arrays.asList(status.split("-"));
return root.get("orderStatus").in(statusList);
};
}

public static Specification<Order> hasUserId(UUID userId) {
return (root, query, criteriaBuilder) -> {
if (userId == null) {
return criteriaBuilder.conjunction();
}
return criteriaBuilder.equal(root.get("user").get("id"), userId);
};
}


public static Specification<Order> filterOrderByUser(String statuses, UUID userId) {
return (root, query, criteriaBuilder) -> {
root.fetch("orderItemList", JoinType.LEFT);
query.distinct(true);
return Specification.where(byStatus(statuses))
.and(hasUserId(userId))
.toPredicate(root, query, criteriaBuilder);
};
}
}
14 changes: 14 additions & 0 deletions src/main/java/com/Optimart/responses/Order/OrderResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.Optimart.responses.Order;

import lombok.*;

import java.util.UUID;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class OrderResponse {
private UUID id;
}
3 changes: 2 additions & 1 deletion src/main/java/com/Optimart/services/Order/IOrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import com.Optimart.dto.Order.CreateOrderDTO;
import com.Optimart.models.Order;
import com.Optimart.responses.APIResponse;
import com.Optimart.responses.Order.OrderResponse;
import com.Optimart.responses.PagingResponse;

import java.util.List;
import java.util.Map;

public interface IOrderService {
APIResponse<Order> createOrder(CreateOrderDTO createOrderDTO);
APIResponse<OrderResponse> createOrder(CreateOrderDTO createOrderDTO);
PagingResponse<List<Order>> getAllOrderByMe(Map<Object, String> filters, String token);
PagingResponse<List<Order>> getAllOrder(Map<Object, String> filters);
}
55 changes: 37 additions & 18 deletions src/main/java/com/Optimart/services/Order/OrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

import com.Optimart.constants.MessageKeys;
import com.Optimart.dto.Order.CreateOrderDTO;
import com.Optimart.dto.OrderItem.OrderItemsDTO;
import com.Optimart.exceptions.DataNotFoundException;
import com.Optimart.models.*;
import com.Optimart.repositories.*;
import com.Optimart.repositories.Specification.ProductSpecification;
import com.Optimart.repositories.Specification.OrderSpecification;
import com.Optimart.responses.APIResponse;
import com.Optimart.responses.Order.OrderResponse;
import com.Optimart.responses.PagingResponse;
import com.Optimart.responses.Product.ProductResponse;
import com.Optimart.utils.JwtTokenUtil;
import com.Optimart.utils.LocalizationUtils;
import lombok.RequiredArgsConstructor;
Expand All @@ -21,7 +20,6 @@
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.List;
import java.util.Map;
Expand All @@ -38,34 +36,58 @@ public class OrderService implements IOrderService{
private final DeliveryTypeRepository deliveryTypeRepository;
private final UserRepository userRepository;
private final AuthRepository authRepository;
private final ShippingAddressRepository shippingAddressRepository;
private final OrderItemRepository orderItemRepository;
private final JwtTokenUtil jwtTokenUtil;
private final LocalizationUtils localizationUtils;
@Override
public APIResponse<Order> createOrder(CreateOrderDTO createOrderDTO) {
public APIResponse<OrderResponse> createOrder(CreateOrderDTO createOrderDTO) {
Order order = modelMapper.map(createOrderDTO, Order.class);
User user = userRepository.findById(UUID.fromString(createOrderDTO.getUserId())).get();
order.setUser(user);
List<OrderItem> orderItems = createOrderDTO.getOrderItems().stream()
.map(item -> {
OrderItem orderItem = modelMapper.map(item, OrderItem.class);
return orderItem;
}).toList();
order.setOrderItemList(orderItems);
ShippingAddress shippingAddress = modelMapper.map(createOrderDTO, ShippingAddress.class);
shippingAddressRepository.save(shippingAddress);
Paymenttype paymenttype = paymentTypeRepository.findById(UUID.fromString(createOrderDTO.getPaymentMethod())).get();
DeliveryType deliveryType = deliveryTypeRepository.findById(UUID.fromString(createOrderDTO.getDeliveryMethod())).get();
order.setShippingAddress(shippingAddress);
order.setPaymentMethod(paymenttype);
order.setDeliveryMethod(deliveryType);
// user.getOrderList().add(order);
order.setOrderStatus(1);
order.setUser(user);
order = orderRepository.save(order);
Order finalOrder = order;
List<OrderItem> orderItems = createOrderDTO.getOrderItems().stream()
.map(item -> {
OrderItem orderItem = modelMapper.map(item, OrderItem.class);
orderItem.setOrder(finalOrder);
return orderItem;
}).collect(Collectors.toList());
orderItemRepository.saveAll(orderItems);
order.setOrderItemList(orderItems);
orderRepository.save(order);
return new APIResponse<>(order, localizationUtils.getLocalizedMessage(MessageKeys.ORDER_CREATE_SUCCESS));
List<Order> orders = user.getOrderList();
orders.add(order);
user.setOrderList(orders);
userRepository.save(user);
return new APIResponse<>(new OrderResponse(order.getId()), localizationUtils.getLocalizedMessage(MessageKeys.ORDER_CREATE_SUCCESS));
}

@Override
public PagingResponse<List<Order>> getAllOrderByMe(Map<Object, String> filters, String token) {
User user = getUser(token);
List<Order> orderList = user.getOrderList();
return null;
int page = Integer.parseInt(filters.getOrDefault("page", "-1"));
int limit = Integer.parseInt(filters.getOrDefault("limit", "-1"));
String order = filters.get("order");
if (page == -1 && limit == -1 ) {
return new PagingResponse<>(orderList, localizationUtils.getLocalizedMessage(MessageKeys.ORDER_LIST_GET_SUCCESS), 1, (long) orderList.size());
}
page = Math.max(Integer.parseInt(filters.getOrDefault("page", "-1")), 1) - 1;
Pageable pageable = PageRequest.of(page, limit, Sort.by("createdAt").descending());
pageable = getPageable(pageable, page, limit, order);
Specification<Order> specification = OrderSpecification.filterOrderByUser(filters.get("status"), user.getId());
Page<Order> orderPage = orderRepository.findAll(specification, pageable);
return new PagingResponse<>(orderPage.getContent(), localizationUtils.getLocalizedMessage(MessageKeys.ORDER_LIST_GET_SUCCESS), orderPage.getTotalPages(), orderPage.getTotalElements());
}

private Pageable getPageable(Pageable pageable, int page, int limit, String order) {
Expand All @@ -86,16 +108,13 @@ public PagingResponse<List<Order>> getAllOrder(Map<Object, String> filters ) {
String order = filters.get("order");
if (page == -1 && limit == -1 ) {
List<Order> orderList = orderRepository.findAll();
// List<Order> productResponseList = orderList.stream()
// .map(product -> modelMapper.map(product, ProductResponse.class))
// .toList();
return new PagingResponse<>(orderList, localizationUtils.getLocalizedMessage(MessageKeys.ORDER_LIST_GET_SUCCESS), 1, (long) orderList.size());
}
page = Math.max(Integer.parseInt(filters.getOrDefault("page", "-1")), 1) - 1;
Pageable pageable = PageRequest.of(page, limit, Sort.by("createdAt").descending());
pageable = getPageable(pageable, page, limit, order);
Page<Order> orderPage = orderRepository.findAll(pageable);
// Specification<Product> specification = ProductSpecification.filterProducts(filters.get("productType"), filters.get("status"), filters.get("search"));;
// Specification<Product> specification = ProductSpecification.filterProducts(filters.get("productType"), filters.get("status"), filters.get("search"));
return new PagingResponse<>(orderPage.getContent(), localizationUtils.getLocalizedMessage(MessageKeys.ORDER_LIST_GET_SUCCESS), orderPage.getTotalPages(), orderPage.getTotalElements());
}

Expand Down

0 comments on commit af37b70

Please sign in to comment.