Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,9 @@ Depends on `feature/categories` existing, since every product references one.

### Tasks

- [ ] `Order` entity, repository, contract/implementation service: computes `total = quantity * product.unitPrice`
- [ ] `OrderResource`
- [ ] Tests, including the total computation
- [x] `Order` entity, repository, contract/implementation service: computes `total = quantity * product.unitPrice`
- [x] `OrderResource`
- [x] Tests, including the total computation

## feature/native-build (bonus)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.edgareldy.quarkustutorial.dto.ecommerce;

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;

/**
* Payload to place an order (the total is computed by the server, never sent by the client).
* <p>
* Created edgar.muhamyangabo on 9/19/26
* Author : edgar.muhamyangabo
* Date : 9/19/26
* Project : quarkus-tutorial
*/
public record OrderRequest(@NotNull Long customerId, @NotNull Long productId, @NotNull @Min(1) Integer quantity) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.edgareldy.quarkustutorial.dto.ecommerce;

import java.math.BigDecimal;

/**
* Order as returned by the API (flat: ids only, no customer or product names).
* <p>
* Created edgar.muhamyangabo on 9/19/26
* Author : edgar.muhamyangabo
* Date : 9/19/26
* Project : quarkus-tutorial
*/
public record OrderResponse(Long id, Long customerId, Long productId, Integer quantity, BigDecimal total) {
}
57 changes: 57 additions & 0 deletions src/main/java/com/edgareldy/quarkustutorial/entity/Order.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.edgareldy.quarkustutorial.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.math.BigDecimal;

/**
* A customer order for a quantity of one product, with the total frozen at creation time.
* <p>
* Created edgar.muhamyangabo on 9/19/26
* Author : edgar.muhamyangabo
* Date : 9/19/26
* Project : quarkus-tutorial
*/
// The JPA entity name is "CustomerOrder" (not the default "Order") because ORDER is an HQL keyword:
// Panache builds queries such as "FROM Order", which would collide with "ORDER BY". The table
// keeps its real name, "orders", through @Table.
@Entity(name = "CustomerOrder")
@Table(name = "orders")
public class Order {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "product_id", nullable = false)
private Product product;

@Column(nullable = false)
private Integer quantity;

@Column(nullable = false, precision = 14, scale = 2)
private BigDecimal total;

public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Customer getCustomer() { return customer; }
public void setCustomer(Customer customer) { this.customer = customer; }
public Product getProduct() { return product; }
public void setProduct(Product product) { this.product = product; }
public Integer getQuantity() { return quantity; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
public BigDecimal getTotal() { return total; }
public void setTotal(BigDecimal total) { this.total = total; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.edgareldy.quarkustutorial.repository;

import com.edgareldy.quarkustutorial.entity.Order;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import io.quarkus.panache.common.Sort;
import jakarta.enterprise.context.ApplicationScoped;

/**
* Panache repository for orders, with optional customer and product filters and counts.
* <p>
* Created edgar.muhamyangabo on 9/19/26
* Author : edgar.muhamyangabo
* Date : 9/19/26
* Project : quarkus-tutorial
*/
@ApplicationScoped
public class OrderRepository implements PanacheRepository<Order> {

/**
* Orders ordered by id, optionally restricted by customer and/or product (filters combine with AND).
*
* @param customerId the customer to filter on, or null
* @param productId the product to filter on, or null
* @return a query the caller can page
*/
public PanacheQuery<Order> search(Long customerId, Long productId) {
if (customerId == null && productId == null) {
return findAll(Sort.by("id"));
}
if (productId == null) {
return find("customer.id = ?1", Sort.by("id"), customerId);
}
if (customerId == null) {
return find("product.id = ?1", Sort.by("id"), productId);
}
return find("customer.id = ?1 and product.id = ?2", Sort.by("id"), customerId, productId);
}

/**
* @param customerId the customer to filter on, or null
* @param productId the product to filter on, or null
* @return how many orders match the same filters as {@link #search}
*/
public long countFiltered(Long customerId, Long productId) {
if (customerId == null && productId == null) {
return count();
}
if (productId == null) {
return countByCustomerId(customerId);
}
if (customerId == null) {
return countByProductId(productId);
}
return count("customer.id = ?1 and product.id = ?2", customerId, productId);
}

/**
* @param customerId the customer id
* @return how many orders reference this customer
*/
public long countByCustomerId(Long customerId) {
return count("customer.id", customerId);
}

/**
* @param productId the product id
* @return how many orders reference this product
*/
public long countByProductId(Long productId) {
return count("product.id", productId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.edgareldy.quarkustutorial.resource;

import com.edgareldy.quarkustutorial.dto.common.ApiResponse;
import com.edgareldy.quarkustutorial.dto.common.PageResponse;
import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest;
import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse;
import com.edgareldy.quarkustutorial.service.OrderService;
import io.quarkus.security.PermissionsAllowed;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement;
import org.jboss.resteasy.reactive.ResponseStatus;

/**
* Endpoints to list, read and place orders, with optional customer and product filters on the list.
* <p>
* Created edgar.muhamyangabo on 9/19/26
* Author : edgar.muhamyangabo
* Date : 9/19/26
* Project : quarkus-tutorial
*/
@Path("/api/v1/orders")
@Produces(MediaType.APPLICATION_JSON)
@SecurityRequirement(name = "jwt")
public class OrderResource {

@Inject
OrderService orderService;

@GET
@PermissionsAllowed("ORDER:READ")
public ApiResponse<PageResponse<OrderResponse>> list(
@QueryParam("page") @DefaultValue("0") @Min(0) int page,
@QueryParam("size") @DefaultValue("20") @Min(1) @Max(100) int size,
@QueryParam("customerId") Long customerId,
@QueryParam("productId") Long productId) {
return ApiResponse.success(orderService.list(page, size, customerId, productId), "Orders");
}

@GET
@Path("/{id}")
@PermissionsAllowed("ORDER:READ")
public ApiResponse<OrderResponse> get(@PathParam("id") Long id) {
return ApiResponse.success(orderService.findById(id), "Order");
}

@POST
@Consumes(MediaType.APPLICATION_JSON)
@PermissionsAllowed("ORDER:WRITE")
@ResponseStatus(201)
public ApiResponse<OrderResponse> create(@Valid OrderRequest request) {
return ApiResponse.success(orderService.create(request), "Order created");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.edgareldy.quarkustutorial.service;

import com.edgareldy.quarkustutorial.dto.common.PageResponse;
import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest;
import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse;

/**
* Contract for order management (read and create only: an order is never edited or deleted).
* <p>
* Created edgar.muhamyangabo on 9/19/26
* Author : edgar.muhamyangabo
* Date : 9/19/26
* Project : quarkus-tutorial
*/
public interface OrderService {

/** @return one page of orders ordered by id, optionally filtered by customer and/or product (null means any) */
PageResponse<OrderResponse> list(int page, int size, Long customerId, Long productId);

/** @return the order, or throws ResourceNotFoundException (404) */
OrderResponse findById(Long id);

/** @return the created order with its computed total; BusinessRuleException (422) if the customer or product does not exist */
OrderResponse create(OrderRequest request);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerRequest;
import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerResponse;
import com.edgareldy.quarkustutorial.entity.Customer;
import com.edgareldy.quarkustutorial.exception.BusinessRuleException;
import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException;
import com.edgareldy.quarkustutorial.repository.CustomerRepository;
import com.edgareldy.quarkustutorial.repository.OrderRepository;
import com.edgareldy.quarkustutorial.service.CustomerService;
import io.quarkus.panache.common.Page;
import io.quarkus.panache.common.Sort;
Expand All @@ -28,6 +30,9 @@ public class CustomerServiceImpl implements CustomerService {
@Inject
CustomerRepository customerRepository;

@Inject
OrderRepository orderRepository;

@Override
@Transactional
public PageResponse<CustomerResponse> list(int page, int size) {
Expand Down Expand Up @@ -62,7 +67,11 @@ public CustomerResponse update(Long id, CustomerRequest request) {
@Override
@Transactional
public void delete(Long id) {
customerRepository.delete(find(id));
Customer customer = find(id);
if (orderRepository.countByCustomerId(id) > 0) {
throw new BusinessRuleException("Customer " + id + " still has orders and cannot be deleted");
}
customerRepository.delete(customer);
}

private Customer find(Long id) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.edgareldy.quarkustutorial.service.impl;

import com.edgareldy.quarkustutorial.dto.common.PageResponse;
import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest;
import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse;
import com.edgareldy.quarkustutorial.entity.Customer;
import com.edgareldy.quarkustutorial.entity.Order;
import com.edgareldy.quarkustutorial.entity.Product;
import com.edgareldy.quarkustutorial.exception.BusinessRuleException;
import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException;
import com.edgareldy.quarkustutorial.repository.CustomerRepository;
import com.edgareldy.quarkustutorial.repository.OrderRepository;
import com.edgareldy.quarkustutorial.repository.ProductRepository;
import com.edgareldy.quarkustutorial.service.OrderService;
import io.quarkus.panache.common.Page;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;

/**
* Default {@link OrderService} backed by Panache; the total is computed from the current product price.
* <p>
* Created edgar.muhamyangabo on 9/19/26
* Author : edgar.muhamyangabo
* Date : 9/19/26
* Project : quarkus-tutorial
*/
@ApplicationScoped
public class OrderServiceImpl implements OrderService {

// NUMERIC(14, 2) holds at most 14 significant digits.
private static final int MAX_TOTAL_PRECISION = 14;

@Inject
OrderRepository orderRepository;

@Inject
CustomerRepository customerRepository;

// The repository is used directly, not the cached ProductService.findById: an order must be priced
// from the row as it is now, never from a cached copy.
@Inject
ProductRepository productRepository;

@Override
@Transactional
public PageResponse<OrderResponse> list(int page, int size, Long customerId, Long productId) {
List<OrderResponse> content = orderRepository.search(customerId, productId).page(Page.of(page, size))
.list().stream().map(OrderServiceImpl::toResponse).toList();
return PageResponse.of(content, page, size, orderRepository.countFiltered(customerId, productId));
}

@Override
@Transactional
public OrderResponse findById(Long id) {
Order order = orderRepository.findById(id);
if (order == null) {
throw new ResourceNotFoundException("Order " + id + " not found");
}
return toResponse(order);
}

@Override
@Transactional
public OrderResponse create(OrderRequest request) {
Customer customer = customerRepository.findById(request.customerId());
if (customer == null) {
throw new BusinessRuleException("Customer " + request.customerId() + " does not exist");
}
Product product = productRepository.findById(request.productId());
if (product == null) {
throw new BusinessRuleException("Product " + request.productId() + " does not exist");
}
// unitPrice has scale 2 and the quantity is an integer, so the product keeps scale 2.
BigDecimal total = product.getUnitPrice().multiply(BigDecimal.valueOf(request.quantity())).setScale(2);
if (total.precision() > MAX_TOTAL_PRECISION) {
throw new BusinessRuleException("The order total is too large");
}
Order order = new Order();
order.setCustomer(customer);
order.setProduct(product);
order.setQuantity(request.quantity());
order.setTotal(total);
orderRepository.persist(order);
return toResponse(order);
}

private static OrderResponse toResponse(Order order) {
return new OrderResponse(order.getId(), order.getCustomer().getId(), order.getProduct().getId(),
order.getQuantity(), order.getTotal());
}
}
Loading
Loading