diff --git a/README.md b/README.md index 0fafa17..55cd57c 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderRequest.java new file mode 100644 index 0000000..afd684e --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderRequest.java @@ -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). + *

+ * 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) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderResponse.java new file mode 100644 index 0000000..74d9174 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderResponse.java @@ -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). + *

+ * 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) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/Order.java b/src/main/java/com/edgareldy/quarkustutorial/entity/Order.java new file mode 100644 index 0000000..1f83339 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/Order.java @@ -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. + *

+ * 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; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/OrderRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderRepository.java new file mode 100644 index 0000000..14a1af1 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderRepository.java @@ -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. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class OrderRepository implements PanacheRepository { + + /** + * 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 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); + } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java new file mode 100644 index 0000000..af35818 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java @@ -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. + *

+ * 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> 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 get(@PathParam("id") Long id) { + return ApiResponse.success(orderService.findById(id), "Order"); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("ORDER:WRITE") + @ResponseStatus(201) + public ApiResponse create(@Valid OrderRequest request) { + return ApiResponse.success(orderService.create(request), "Order created"); + } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/OrderService.java b/src/main/java/com/edgareldy/quarkustutorial/service/OrderService.java new file mode 100644 index 0000000..56f9e53 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/OrderService.java @@ -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). + *

+ * 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 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); +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java index a5b8f7e..a19c036 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java @@ -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; @@ -28,6 +30,9 @@ public class CustomerServiceImpl implements CustomerService { @Inject CustomerRepository customerRepository; + @Inject + OrderRepository orderRepository; + @Override @Transactional public PageResponse list(int page, int size) { @@ -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) { diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java new file mode 100644 index 0000000..099e3de --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java @@ -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. + *

+ * 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 list(int page, int size, Long customerId, Long productId) { + List 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()); + } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java index 6e37ef8..897f0b3 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java @@ -8,6 +8,7 @@ import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; import com.edgareldy.quarkustutorial.repository.ProductRepository; import com.edgareldy.quarkustutorial.service.ProductService; import io.quarkus.cache.CacheInvalidate; @@ -36,6 +37,9 @@ public class ProductServiceImpl implements ProductService { @Inject CategoryRepository categoryRepository; + @Inject + OrderRepository orderRepository; + @Override @Transactional public PageResponse list(int page, int size, Long categoryId) { @@ -83,7 +87,11 @@ public ProductResponse update(@CacheKey Long id, ProductRequest request) { @Transactional @CacheInvalidate(cacheName = "product-cache") public void delete(@CacheKey Long id) { - productRepository.delete(find(id)); + Product product = find(id); + if (orderRepository.countByProductId(id) > 0) { + throw new BusinessRuleException("Product " + id + " is still referenced by orders and cannot be deleted"); + } + productRepository.delete(product); } private Product find(Long id) { diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java new file mode 100644 index 0000000..f0410ab --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java @@ -0,0 +1,181 @@ +package com.edgareldy.quarkustutorial.repository; + +import static org.junit.jupiter.api.Assertions.*; + +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.entity.Order; +import com.edgareldy.quarkustutorial.entity.Product; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Repository tests of OrderRepository against the Dev Services PostgreSQL, including the HQL entity name. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Real PostgreSQL through Dev Services (see CategoryRepositoryTest). This is the runtime proof that the +// "CustomerOrder" entity name works: Panache generates HQL such as "FROM CustomerOrder" for count() and +// findAll(), which would not parse with the reserved word "Order". +@QuarkusTest +class OrderRepositoryTest { + + @Inject + OrderRepository repository; + + @Inject + CustomerRepository customerRepository; + + @Inject + ProductRepository productRepository; + + @Inject + CategoryRepository categoryRepository; + + @Inject + EntityManager em; + + private Long categoryId; + private Long customerA; + private Long customerB; + private Long productA; + private Long productB; + + @BeforeEach + void setUp() { + QuarkusTransaction.requiringNew().run(() -> { + Category cat = new Category(); + cat.setCategoryName("order-repo-" + System.nanoTime()); + categoryRepository.persist(cat); + categoryId = cat.getId(); + customerA = customer(); + customerB = customer(); + productA = product(cat); + productB = product(cat); + }); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + for (Long id : List.of(customerA, customerB)) { + em.createNativeQuery("delete from orders where customer_id = ?1").setParameter(1, id) + .executeUpdate(); + em.createNativeQuery("delete from customers where id = ?1").setParameter(1, id).executeUpdate(); + } + em.createNativeQuery("delete from products where category_id = ?1").setParameter(1, categoryId) + .executeUpdate(); + em.createNativeQuery("delete from categories where id = ?1").setParameter(1, categoryId) + .executeUpdate(); + }); + } + + private Long customer() { + Customer c = new Customer(); + c.setFirstName("Ada"); + c.setLastName("Lovelace"); + customerRepository.persist(c); + return c.getId(); + } + + private Long product(Category category) { + Product p = new Product(); + p.setCategory(category); + p.setProductName("P" + System.nanoTime()); + p.setUnitPrice(new BigDecimal("2.50")); + productRepository.persist(p); + return p.getId(); + } + + private Long order(Long customerId, Long productId, int quantity, String total) { + return QuarkusTransaction.requiringNew().call(() -> { + Order o = new Order(); + o.setCustomer(customerRepository.findById(customerId)); + o.setProduct(productRepository.findById(productId)); + o.setQuantity(quantity); + o.setTotal(new BigDecimal(total)); + repository.persist(o); + return o.getId(); + }); + } + + private List ids(Long customerId, Long productId) { + return QuarkusTransaction.requiringNew() + .call(() -> repository.search(customerId, productId).list().stream().map(Order::getId).toList()); + } + + @Test + void persistAndFindRoundTripOnTheCustomerOrderEntity() { + Long id = order(customerA, productA, 3, "7.50"); + + Order found = QuarkusTransaction.requiringNew().call(() -> { + Order o = repository.findById(id); + // Touch the lazy associations inside the transaction. + assertEquals(customerA, o.getCustomer().getId()); + assertEquals(productA, o.getProduct().getId()); + return o; + }); + + assertEquals(3, found.getQuantity()); + assertEquals(new BigDecimal("7.50"), found.getTotal()); + } + + @Test + void searchAndCountWorkWithEveryFilterCombination() { + Long o1 = order(customerA, productA, 1, "2.50"); + Long o2 = order(customerA, productB, 2, "5.00"); + Long o3 = order(customerB, productA, 3, "7.50"); + + assertEquals(List.of(o1, o2), ids(customerA, null)); + assertEquals(List.of(o3), ids(customerB, null)); + assertEquals(List.of(o1, o3), ids(null, productA)); + assertEquals(List.of(o2), ids(customerA, productB)); + assertTrue(ids(customerB, productB).isEmpty()); + List all = ids(null, null); + assertTrue(all.containsAll(List.of(o1, o2, o3))); + assertEquals(all.stream().sorted().toList(), all); + + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(customerA, null))); + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(null, productA))); + assertEquals(1L, + QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(customerA, productB))); + assertEquals(0L, + QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(customerB, productB))); + assertTrue(QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(null, null)) >= 3L); + } + + @Test + void countByCustomerAndProductCountOnlyReferencingOrders() { + order(customerA, productA, 1, "2.50"); + order(customerA, productB, 1, "2.50"); + order(customerB, productA, 1, "2.50"); + + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countByCustomerId(customerA))); + assertEquals(1L, QuarkusTransaction.requiringNew().call(() -> repository.countByCustomerId(customerB))); + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countByProductId(productA))); + assertEquals(1L, QuarkusTransaction.requiringNew().call(() -> repository.countByProductId(productB))); + assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> repository.countByCustomerId(999999999L))); + assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> repository.countByProductId(999999999L))); + } + + @Test + void foreignKeysAndChecksAreEnforced() { + assertThrows(RuntimeException.class, () -> QuarkusTransaction.requiringNew().run(() -> em + .createNativeQuery("insert into orders (customer_id, product_id, quantity, total) " + + "values (999999999, " + productA + ", 1, 1.00)").executeUpdate())); + assertThrows(RuntimeException.class, () -> QuarkusTransaction.requiringNew().run(() -> em + .createNativeQuery("insert into orders (customer_id, product_id, quantity, total) " + + "values (" + customerA + ", " + productA + ", 0, 1.00)").executeUpdate())); + } +} diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java new file mode 100644 index 0000000..b026414 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java @@ -0,0 +1,318 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the order endpoints: creation with computed total, reads, paging, filters, + * validation, business refusals, permission denial and the customer/product deletion rules. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same approach as ProductResourceTest: real HTTP against Dev Services, users from RbacTestSupport. The +// API has no order deletion, so tearDown() removes orders (then customers, products, categories) with +// native SQL, in foreign key order. +@QuarkusTest +class OrderResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/orders"; + private static final String JSON = "application/json"; + + @Inject + RbacTestSupport support; + + @Inject + EntityManager em; + + private final List categories = new ArrayList<>(); + private final List products = new ArrayList<>(); + private final List customers = new ArrayList<>(); + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + customers.forEach(id -> em.createNativeQuery("delete from orders where customer_id = ?1") + .setParameter(1, id).executeUpdate()); + products.forEach(id -> em.createNativeQuery("delete from orders where product_id = ?1") + .setParameter(1, id).executeUpdate()); + customers.forEach(id -> em.createNativeQuery("delete from customers where id = ?1") + .setParameter(1, id).executeUpdate()); + products.forEach(id -> em.createNativeQuery("delete from products where id = ?1") + .setParameter(1, id).executeUpdate()); + categories.forEach(id -> em.createNativeQuery("delete from categories where id = ?1") + .setParameter(1, id).executeUpdate()); + }); + categories.clear(); + products.clear(); + customers.clear(); + support.cleanup(); + } + + private Long category() { + Long id = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryName\":\"" + RbacTestSupport.unique("cat") + "\"}").when() + .post("/api/v1/categories").then().statusCode(201).extract().jsonPath().getLong("data.id"); + categories.add(id); + return id; + } + + private Long product(Long categoryId, String price) { + Long id = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryId\":" + categoryId + ",\"productName\":\"P\",\"unitPrice\":" + price + "}") + .when().post("/api/v1/products").then().statusCode(201).extract().jsonPath().getLong("data.id"); + products.add(id); + return id; + } + + private Long customer() { + Long id = given().auth().oauth2(admin).contentType(JSON) + .body("{\"firstName\":\"Ada\",\"lastName\":\"Lovelace\"}").when().post("/api/v1/customers") + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + customers.add(id); + return id; + } + + private static String body(Object customerId, Object productId, Object quantity) { + return "{\"customerId\":" + customerId + ",\"productId\":" + productId + ",\"quantity\":" + quantity + "}"; + } + + private Long order(Long customerId, Long productId, int quantity) { + return given().auth().oauth2(admin).contentType(JSON).body(body(customerId, productId, quantity)) + .when().post(BASE).then().statusCode(201).extract().jsonPath().getLong("data.id"); + } + + private String tokenWith(String... permissions) { + Long role = support.createRole(RbacTestSupport.unique("order-role"), permissions); + RbacTestSupport.TestUser user = support.createUser(); + support.grantRole(user.id(), role); + return support.token(user); + } + + @Test + void createReturns201WithComputedTotalAndDetailRoundTrips() { + Long cust = customer(); + Long prod = product(category(), "2.50"); + + String json = given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 3)) + .when().post(BASE) + .then().statusCode(201).contentType("application/json") + .body("success", is(true)) + .body("data.id", notNullValue()) + .body("data.customerId", is(cust.intValue())) + .body("data.productId", is(prod.intValue())) + .body("data.quantity", is(3)) + .extract().asString(); + io.restassured.path.json.JsonPath created = io.restassured.path.json.JsonPath.from(json); + BigDecimal total = new BigDecimal(created.getString("data.total")); + assertEquals(new BigDecimal("7.50"), total.setScale(2)); + + String read = given().auth().oauth2(admin).when().get(BASE + "/" + created.getLong("data.id")) + .then().statusCode(200).body("success", is(true)) + .body("data.customerId", is(cust.intValue())) + .body("data.quantity", is(3)) + .extract().jsonPath().getString("data.total"); + assertEquals(0, new BigDecimal("7.50").compareTo(new BigDecimal(read))); + } + + @Test + void totalIsFrozenWhenTheProductPriceChangesLater() { + Long cat = category(); + Long cust = customer(); + Long prod = product(cat, "4.00"); + Long id = order(cust, prod, 2); + given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryId\":" + cat + ",\"productName\":\"P\",\"unitPrice\":10.00}") + .when().put("/api/v1/products/" + prod).then().statusCode(200); + + String old = given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).extract().jsonPath().getString("data.total"); + assertEquals(0, new BigDecimal("8.00").compareTo(new BigDecimal(old))); + // A new order uses the fresh price (not a stale cached product). + String fresh = given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 2)) + .when().post(BASE).then().statusCode(201).extract().jsonPath().getString("data.total"); + assertEquals(0, new BigDecimal("20.00").compareTo(new BigDecimal(fresh))); + } + + @Test + void unknownOrderIs404Problem() { + given().auth().oauth2(admin).when().get(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) + .body("$", not(hasKey("success"))); + } + + @Test + void listIsPaginatedAndFilteredByCustomerProductOrBoth() { + Long cat = category(); + Long custA = customer(); + Long custB = customer(); + Long prodA = product(cat, "1.00"); + Long prodB = product(cat, "2.00"); + Long o1 = order(custA, prodA, 1); + Long o2 = order(custA, prodB, 2); + Long o3 = order(custB, prodA, 3); + + List ids = given().auth().oauth2(admin).queryParam("size", 100).when().get(BASE) + .then().statusCode(200).body("success", is(true)) + .body("data.content.id", hasItems(o1.intValue(), o2.intValue(), o3.intValue())) + .extract().jsonPath().getList("data.content.id"); + assertEquals(ids.stream().sorted().toList(), ids); + + given().auth().oauth2(admin).queryParam("customerId", custA).when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o1.intValue(), o2.intValue())) + .body("data.totalElements", is(2)); + given().auth().oauth2(admin).queryParam("productId", prodA).when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o1.intValue(), o3.intValue())) + .body("data.totalElements", is(2)); + given().auth().oauth2(admin).queryParam("customerId", custA).queryParam("productId", prodB).when() + .get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o2.intValue())) + .body("data.totalElements", is(1)); + given().auth().oauth2(admin).queryParam("customerId", custB).queryParam("productId", prodB).when() + .get(BASE) + .then().statusCode(200).body("data.content", empty()).body("data.totalElements", is(0)); + given().auth().oauth2(admin).queryParam("customerId", custA).queryParam("page", 1).queryParam("size", 1) + .when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o2.intValue())) + .body("data.page", is(1)).body("data.size", is(1)) + .body("data.totalElements", is(2)).body("data.totalPages", is(2)); + } + + @Test + void invalidPageSizeIs400Problem() { + given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); + } + + @Test + void invalidBodyIs400ProblemWithViolations() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + List bodies = List.of( + body("null", prod, 1), + body(cust, "null", 1), + body(cust, prod, "null"), + body(cust, prod, 0), + body(cust, prod, -2), + "{}"); + for (String json : bodies) { + given().auth().oauth2(admin).contentType(JSON).body(json).when().post(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("violations", not(empty())) + .body("$", not(hasKey("success"))); + } + } + + @Test + void unknownCustomerOrProductIs422Problem() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + given().auth().oauth2(admin).contentType(JSON).body(body(999999999, prod, 1)).when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, 999999999, 1)).when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)); + } + + @Test + void totalBeyondNumeric14Is422ProblemAndLargestFittingTotalIsAccepted() { + Long cust = customer(); + Long prod = product(category(), "9999999999.99"); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 100)).when().post(BASE) + .then().statusCode(201); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 101)).when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, Integer.MAX_VALUE)).when() + .post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON); + } + + @Test + void readerCanReadButNotCreateAndWriterCanCreate() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + Long id = order(cust, prod, 1); + String reader = tokenWith("ORDER:READ"); + given().auth().oauth2(reader).when().get(BASE).then().statusCode(200); + given().auth().oauth2(reader).when().get(BASE + "/" + id).then().statusCode(200); + given().auth().oauth2(reader).contentType(JSON).body(body(cust, prod, 1)).when().post(BASE) + .then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + + String writer = tokenWith("ORDER:WRITE"); + given().auth().oauth2(writer).contentType(JSON).body(body(cust, prod, 1)).when().post(BASE) + .then().statusCode(201); + given().auth().oauth2(writer).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + } + + @Test + void userWithoutPermissionIs403AndNoTokenIs401() { + String nobody = support.token(support.createUser()); + given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(nobody).contentType(JSON).body(body(1, 1, 1)).when().post(BASE) + .then().statusCode(403).contentType(PROBLEM_JSON); + given().when().get(BASE).then().statusCode(401); + given().contentType(JSON).body(body(1, 1, 1)).when().post(BASE).then().statusCode(401); + } + + @Test + void productWithOrdersCannotBeDeletedUntilOrdersAreGone() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + order(cust, prod, 1); + given().auth().oauth2(admin).when().delete("/api/v1/products/" + prod) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).when().get("/api/v1/products/" + prod).then().statusCode(200); + + removeOrders(cust); + given().auth().oauth2(admin).when().delete("/api/v1/products/" + prod).then().statusCode(200); + } + + @Test + void customerWithOrdersCannotBeDeletedUntilOrdersAreGone() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + order(cust, prod, 1); + given().auth().oauth2(admin).when().delete("/api/v1/customers/" + cust) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).when().get("/api/v1/customers/" + cust).then().statusCode(200); + + removeOrders(cust); + given().auth().oauth2(admin).when().delete("/api/v1/customers/" + cust).then().statusCode(200); + } + + private void removeOrders(Long customerId) { + QuarkusTransaction.requiringNew().run(() -> em.createNativeQuery("delete from orders where customer_id = ?1") + .setParameter(1, customerId).executeUpdate()); + } +} diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java index c4893f5..efe59a5 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java @@ -8,8 +8,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 io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; @@ -31,13 +33,16 @@ class CustomerServiceImplTest { private CustomerRepository repository; + private OrderRepository orderRepository; private CustomerServiceImpl service; @BeforeEach void setUp() { repository = mock(CustomerRepository.class); service = new CustomerServiceImpl(); + orderRepository = mock(OrderRepository.class); service.customerRepository = repository; + service.orderRepository = orderRepository; } private static Customer customer(Long id, String first) { @@ -115,6 +120,16 @@ void deleteRemovesCustomer() { verify(repository).delete(c); } + @Test + void deleteIsRefusedWhileOrdersReferenceTheCustomer() { + Customer c = customer(1L, "Ada"); + when(repository.findById(1L)).thenReturn(c); + when(orderRepository.countByCustomerId(1L)).thenReturn(2L); + + assertThrows(BusinessRuleException.class, () -> service.delete(1L)); + verify(repository, never()).delete(any(Customer.class)); + } + @Test void deleteMissingIsNotFound() { when(repository.findById(9L)).thenReturn(null); diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java new file mode 100644 index 0000000..efebf54 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java @@ -0,0 +1,164 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +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 io.quarkus.hibernate.orm.panache.PanacheQuery; +import io.quarkus.panache.common.Page; +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** + * Isolated unit tests of OrderServiceImpl with its three repositories mocked. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Plain Mockito with the package-private injected fields assigned directly (same approach as the other +// service tests): the total computation and the refusal rules need no container. +class OrderServiceImplTest { + + private OrderRepository orderRepository; + private CustomerRepository customerRepository; + private ProductRepository productRepository; + private OrderServiceImpl service; + + @BeforeEach + void setUp() { + orderRepository = mock(OrderRepository.class); + customerRepository = mock(CustomerRepository.class); + productRepository = mock(ProductRepository.class); + service = new OrderServiceImpl(); + service.orderRepository = orderRepository; + service.customerRepository = customerRepository; + service.productRepository = productRepository; + } + + private static Customer customer(Long id) { + Customer c = new Customer(); + c.setId(id); + return c; + } + + private static Product product(Long id, String price) { + Product p = new Product(); + p.setId(id); + p.setUnitPrice(new BigDecimal(price)); + return p; + } + + private static Order order(Long id, Customer c, Product p, int quantity, String total) { + Order o = new Order(); + o.setId(id); + o.setCustomer(c); + o.setProduct(p); + o.setQuantity(quantity); + o.setTotal(new BigDecimal(total)); + return o; + } + + @Test + void createComputesTotalFromCurrentUnitPriceWithScale2() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(product(2L, "2.50")); + + OrderResponse response = service.create(new OrderRequest(1L, 2L, 3)); + + assertEquals(new BigDecimal("7.50"), response.total()); + assertEquals(1L, response.customerId()); + assertEquals(2L, response.productId()); + assertEquals(3, response.quantity()); + ArgumentCaptor captor = ArgumentCaptor.forClass(Order.class); + verify(orderRepository).persist(captor.capture()); + assertEquals(new BigDecimal("7.50"), captor.getValue().getTotal()); + // The price is read fresh from the repository, never from the cached ProductService. + verify(productRepository).findById(2L); + } + + @Test + void createWithUnknownCustomerIsRefused() { + when(customerRepository.findById(1L)).thenReturn(null); + + assertThrows(BusinessRuleException.class, () -> service.create(new OrderRequest(1L, 2L, 1))); + verify(orderRepository, never()).persist(any(Order.class)); + } + + @Test + void createWithUnknownProductIsRefused() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(null); + + assertThrows(BusinessRuleException.class, () -> service.create(new OrderRequest(1L, 2L, 1))); + verify(orderRepository, never()).persist(any(Order.class)); + } + + @Test + void createWithTotalBeyondNumeric14IsRefused() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(product(2L, "9999999999.99")); + + assertThrows(BusinessRuleException.class, () -> service.create(new OrderRequest(1L, 2L, 101))); + verify(orderRepository, never()).persist(any(Order.class)); + } + + @Test + void createAcceptsTheLargestTotalThatFits() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(product(2L, "9999999999.99")); + + OrderResponse response = service.create(new OrderRequest(1L, 2L, 100)); + + // 14 significant digits: the widest value NUMERIC(14, 2) accepts. + assertEquals(new BigDecimal("999999999999.00"), response.total()); + } + + @Test + void findByIdMapsAndMissingIsNotFound() { + when(orderRepository.findById(5L)).thenReturn(order(5L, customer(1L), product(2L, "1.00"), 2, "2.00")); + when(orderRepository.findById(9L)).thenReturn(null); + + OrderResponse response = service.findById(5L); + + assertEquals(5L, response.id()); + assertEquals(new BigDecimal("2.00"), response.total()); + assertThrows(ResourceNotFoundException.class, () -> service.findById(9L)); + } + + @Test + @SuppressWarnings("unchecked") + void listBuildsPageResponseFromFilteredQueryAndCount() { + PanacheQuery query = mock(PanacheQuery.class); + PanacheQuery paged = mock(PanacheQuery.class); + when(orderRepository.search(1L, null)).thenReturn(query); + when(query.page(any(Page.class))).thenReturn(paged); + Customer c = customer(1L); + Product p = product(2L, "1.00"); + when(paged.list()).thenReturn(List.of(order(1L, c, p, 1, "1.00"), order(2L, c, p, 2, "2.00"))); + when(orderRepository.countFiltered(1L, null)).thenReturn(5L); + + PageResponse page = service.list(1, 2, 1L, null); + + assertEquals(2, page.content().size()); + assertEquals(1, page.page()); + assertEquals(2, page.size()); + assertEquals(5L, page.totalElements()); + assertEquals(3, page.totalPages()); + } +} diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java index cd5f6cc..2b04b3e 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java @@ -12,6 +12,7 @@ import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; import com.edgareldy.quarkustutorial.repository.ProductRepository; import io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.panache.common.Page; @@ -34,6 +35,7 @@ class ProductServiceImplTest { private ProductRepository productRepository; private CategoryRepository categoryRepository; + private OrderRepository orderRepository; private ProductServiceImpl service; @BeforeEach @@ -43,6 +45,8 @@ void setUp() { service = new ProductServiceImpl(); service.productRepository = productRepository; service.categoryRepository = categoryRepository; + orderRepository = mock(OrderRepository.class); + service.orderRepository = orderRepository; } private static Category category(Long id) { @@ -136,6 +140,16 @@ void deleteRemovesProduct() { verify(productRepository).delete(existing); } + @Test + void deleteIsRefusedWhileOrdersReferenceTheProduct() { + Product existing = product(3L, category(1L), "Old", "1.00"); + when(productRepository.findById(3L)).thenReturn(existing); + when(orderRepository.countByProductId(3L)).thenReturn(1L); + + assertThrows(BusinessRuleException.class, () -> service.delete(3L)); + verify(productRepository, never()).delete(any(Product.class)); + } + @Test @SuppressWarnings("unchecked") void listWithoutFilterUsesGlobalCount() {