From c3635aaed1a0fa4d78216922256f81b0982ad99d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:53:30 +0400 Subject: [PATCH 001/175] feat(flyway): add V13 migration for product description, active flag and decimal price Adds two new columns to the products table: - description VARCHAR(500), nullable, for a short product text visible in the catalogue. - active BOOLEAN NOT NULL DEFAULT TRUE, so products can be deactivated without deletion (the shopping-cart will refuse to add inactive products to a cart). Also migrates unit_price from REAL to NUMERIC(12,2). REAL is a 32-bit IEEE 754 floating-point type that cannot represent most decimal fractions exactly, which causes rounding errors when accumulating line totals in an order. NUMERIC(12,2) stores the value as an exact decimal, the standard choice for monetary amounts in SQL. The USING clause converts existing rows. The old products_unit_price_check constraint is dropped and recreated to match the new type. Migration is numbered V13 to leave V5-V12 free for the existing pedagogical branches (feature/auth through feature/user-management) that will appear in the merge chain when this branch feeds into feature/shopping-cart. --- ...dd_product_description_active_decimal_price.sql | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/resources/db/migration/V13__add_product_description_active_decimal_price.sql diff --git a/src/main/resources/db/migration/V13__add_product_description_active_decimal_price.sql b/src/main/resources/db/migration/V13__add_product_description_active_decimal_price.sql new file mode 100644 index 0000000..3269ae0 --- /dev/null +++ b/src/main/resources/db/migration/V13__add_product_description_active_decimal_price.sql @@ -0,0 +1,14 @@ +-- Adds e-commerce fields to products: +-- description (nullable, up to 500 chars), +-- active flag (default true for all existing rows), +-- and migrates unit_price from REAL to NUMERIC(12,2) for exact monetary arithmetic. +ALTER TABLE products + ADD COLUMN description VARCHAR(500), + ADD COLUMN active BOOLEAN NOT NULL DEFAULT TRUE; + +ALTER TABLE products + ALTER COLUMN unit_price TYPE NUMERIC(12,2) USING unit_price::NUMERIC(12,2); + +-- Regenerate the check constraint with the correct type after the column type change. +ALTER TABLE products DROP CONSTRAINT IF EXISTS products_unit_price_check; +ALTER TABLE products ADD CONSTRAINT products_unit_price_check CHECK (unit_price > 0); From 584cab9e527867735b1249f46d552b5ba839926f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:53:49 +0400 Subject: [PATCH 002/175] feat(entity): add description, active and BigDecimal unitPrice to Product Replaces float unitPrice with BigDecimal (NUMERIC(12,2) in SQL via V13) to eliminate floating-point rounding when summing order line totals. Adds description (nullable VARCHAR(500)) for a short catalogue text, and active (boolean, default true) so an admin can deactivate a product without deleting it. Inactive products will be refused by the shopping-cart service when a user tries to add them to a cart. @Builder.Default ensures that new Product instances built with the Lombok builder start with active=true instead of false (the Java default for boolean), matching the SQL DEFAULT TRUE on the column. --- .../springboottutorial/entity/Product.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/Product.java b/src/main/java/com/edgareldy/springboottutorial/entity/Product.java index 53ff87e..8581f7c 100644 --- a/src/main/java/com/edgareldy/springboottutorial/entity/Product.java +++ b/src/main/java/com/edgareldy/springboottutorial/entity/Product.java @@ -10,6 +10,7 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.Version; +import java.math.BigDecimal; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -24,6 +25,10 @@ * {@code UPDATE} and throws {@code ObjectOptimisticLockingFailureException} * if the row was modified concurrently since it was read, instead of * silently overwriting the other change. + * {@code unitPrice} uses {@link BigDecimal} backed by SQL {@code NUMERIC(12,2)} + * (see V13 migration) for exact decimal arithmetic. {@code active} allows + * soft-deactivation of a product so it no longer appears as purchasable + * without removing its historical order references. *

* Created edgar.muhamyangabo on 7/4/26 * Author : edgar.muhamyangabo @@ -50,8 +55,15 @@ public class Product { @Column(name = "product_name", nullable = false) private String productName; + @Column(name = "description") + private String description; + @Column(name = "unit_price", nullable = false) - private float unitPrice; + private BigDecimal unitPrice; + + @Column(name = "active", nullable = false) + @Builder.Default + private boolean active = true; @Version private Long version; From 2d5d733ba1945c916fca19a663300b436f6c2d87 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:54:02 +0400 Subject: [PATCH 003/175] feat(dto): add description to ProductRequest and change unitPrice to BigDecimal Adds an optional description field (nullable, no @NotBlank) so callers can supply a short catalogue text when creating or updating a product. Changes unitPrice from Float to BigDecimal, consistent with the NUMERIC(12,2) column type introduced in V13. Using Float in a request DTO was already lossy: JSON deserialisation to Float can silently round a value like 9.99 before it even reaches the service layer. BigDecimal preserves the exact string "9.99" from JSON all the way to the SQL INSERT. --- .../springboottutorial/dto/product/ProductRequest.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductRequest.java b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductRequest.java index 43f4f71..1f3072a 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductRequest.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductRequest.java @@ -4,6 +4,7 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import java.math.BigDecimal; /** * Payload accepted by {@code POST}/{@code PUT} {@code /api/v1/products}. @@ -11,6 +12,8 @@ * layer, not this record, is responsible for checking that. The JSON * contract is snake_case, decoupled from the Java fields' own camelCase * names via explicit {@link JsonProperty} annotations. + * {@code description} is optional (nullable). {@code unitPrice} uses + * {@link BigDecimal} for exact decimal representation. *

* Created edgar.muhamyangabo on 7/4/26 * Author : edgar.muhamyangabo @@ -27,9 +30,12 @@ public record ProductRequest( @NotBlank(message = "Product name must not be blank") String productName, + @JsonProperty("description") + String description, + @JsonProperty("unit_price") @NotNull(message = "Unit price must not be null") @Positive(message = "Unit price must be greater than 0") - Float unitPrice + BigDecimal unitPrice ) { } From bfc73e761a1843fc0540c3833c1b7fd1ec8de93b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:54:19 +0400 Subject: [PATCH 004/175] feat(dto): add description, active and BigDecimal unitPrice to ProductResponse Adds description (nullable String) and active (boolean) to the response so API clients can display a product text and filter or badge inactive products in the UI. Changes unitPrice from float to BigDecimal, consistent with ProductRequest and the NUMERIC(12,2) column. The old float field could serialize 79.99 as 79.98999786376953 in JSON due to floating-point representation; BigDecimal serializes it as the exact string "79.99". --- .../springboottutorial/dto/product/ProductResponse.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java index d530555..20359f3 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java @@ -1,6 +1,7 @@ package com.edgareldy.springboottutorial.dto.product; import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; /** * Representation of a {@link com.edgareldy.springboottutorial.entity.Product} @@ -9,6 +10,8 @@ * {@code CategoryResponse}, matching the response shape documented in the * README. The JSON contract is snake_case, decoupled from the Java fields' * own camelCase names via explicit {@link JsonProperty} annotations. + * {@code unitPrice} uses {@link BigDecimal} to match the NUMERIC(12,2) column. + * {@code active} indicates whether the product is available for purchase. *

* Created edgar.muhamyangabo on 7/4/26 * Author : edgar.muhamyangabo @@ -22,7 +25,11 @@ public record ProductResponse( String productName, @JsonProperty("unit_price") - float unitPrice, + BigDecimal unitPrice, + + String description, + + boolean active, @JsonProperty("category_id") Long categoryId, From cac3fd165d6210d88cf087527b848596cfbc6138 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:54:34 +0400 Subject: [PATCH 005/175] feat(mapper): ignore active on ProductMapper write methods ProductRequest does not carry an active field: the activation state of a product is managed separately and must not be overwritten by a create or update call. Adding @Mapping(target="active", ignore=true) on toEntity and updateEntityFromRequest makes this intent explicit and prevents MapStruct from emitting an "unmapped target property" warning. toResponse needs no change: description and active are same-named fields on both Product and ProductResponse, so MapStruct maps them automatically. --- .../edgareldy/springboottutorial/mapper/ProductMapper.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java index ad5dd3a..3ec9317 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java @@ -13,7 +13,9 @@ * {@code category} association is looked up by the service layer (which needs * a repository lookup) and handed to the entity-building methods as a * parameter: this mapper only assigns it, so the service never calls a - * setter itself. + * setter itself. {@code active} is ignored on writes: the flag is managed + * via a dedicated activation endpoint, not through the product create/update + * payload, so it must never be overwritten by {@link ProductRequest}. *

* Created edgar.muhamyangabo on 7/4/26 * Author : edgar.muhamyangabo @@ -30,10 +32,12 @@ public interface ProductMapper { @Mapping(target = "id", ignore = true) @Mapping(target = "category", source = "category") @Mapping(target = "version", ignore = true) + @Mapping(target = "active", ignore = true) Product toEntity(ProductRequest request, Category category); @Mapping(target = "id", ignore = true) @Mapping(target = "category", source = "category") @Mapping(target = "version", ignore = true) + @Mapping(target = "active", ignore = true) void updateEntityFromRequest(ProductRequest request, Category category, @MappingTarget Product product); } From 8aad056d4eb04d18d76407a118ec9301207f90fa Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:54:48 +0400 Subject: [PATCH 006/175] refactor(specification): change priceBetween parameter types to BigDecimal Aligns the price filter with the entity and DTO change from Float to BigDecimal. Using Float here with a BigDecimal column would have forced Hibernate to cast at query time, which is correct but potentially confusing. Explicit BigDecimal parameters make the type contract consistent from the HTTP layer to the SQL predicate. --- .../repository/specification/ProductSpecifications.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/specification/ProductSpecifications.java b/src/main/java/com/edgareldy/springboottutorial/repository/specification/ProductSpecifications.java index 4135dfb..03e813c 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/specification/ProductSpecifications.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/specification/ProductSpecifications.java @@ -1,6 +1,7 @@ package com.edgareldy.springboottutorial.repository.specification; import com.edgareldy.springboottutorial.entity.Product; +import java.math.BigDecimal; import org.springframework.data.jpa.domain.Specification; /** @@ -34,7 +35,7 @@ public static Specification nameContains(String productName) { criteriaBuilder.lower(root.get("productName")), "%" + productName.toLowerCase() + "%"); } - public static Specification priceBetween(Float minPrice, Float maxPrice) { + public static Specification priceBetween(BigDecimal minPrice, BigDecimal maxPrice) { return (root, query, criteriaBuilder) -> { if (minPrice != null && maxPrice != null) { return criteriaBuilder.between(root.get("unitPrice"), minPrice, maxPrice); From ff62e341a6e990f9bd3998923b222f58737ba5e2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:55:01 +0400 Subject: [PATCH 007/175] refactor(service): change findAll price filter parameters to BigDecimal Aligns the ProductService contract with the entity and specification changes. Float was the original type for minPrice/maxPrice query parameters; BigDecimal makes the type consistent from HTTP deserialization down to the SQL predicate. --- .../edgareldy/springboottutorial/service/ProductService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/ProductService.java b/src/main/java/com/edgareldy/springboottutorial/service/ProductService.java index 501b1ab..f9a78ba 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/ProductService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/ProductService.java @@ -3,6 +3,7 @@ import com.edgareldy.springboottutorial.dto.common.PageResponse; import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import java.math.BigDecimal; import org.springframework.data.domain.Pageable; /** @@ -18,7 +19,7 @@ public interface ProductService { PageResponse findAll( - Long categoryId, String productName, Float minPrice, Float maxPrice, Pageable pageable); + Long categoryId, String productName, BigDecimal minPrice, BigDecimal maxPrice, Pageable pageable); ProductResponse findById(Long id); From 57855a8de5300655c56153327bef4de3d0695354 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:55:16 +0400 Subject: [PATCH 008/175] refactor(service): change findAll price filter parameters to BigDecimal in ProductServiceImpl Implements the updated ProductService contract. No logic change: the Specification path and the EntityGraph paths remain identical; only the parameter types change from Float to BigDecimal, consistent with the entity field and the SQL NUMERIC(12,2) column type. --- .../springboottutorial/service/impl/ProductServiceImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java index 4d3be73..fbc198d 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java @@ -11,6 +11,7 @@ import com.edgareldy.springboottutorial.repository.ProductRepository; import com.edgareldy.springboottutorial.repository.specification.ProductSpecifications; import com.edgareldy.springboottutorial.service.ProductService; +import java.math.BigDecimal; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; @@ -49,7 +50,7 @@ public class ProductServiceImpl implements ProductService { @Override public PageResponse findAll( - Long categoryId, String productName, Float minPrice, Float maxPrice, Pageable pageable) { + Long categoryId, String productName, BigDecimal minPrice, BigDecimal maxPrice, Pageable pageable) { Page page; if (productName != null || minPrice != null || maxPrice != null) { // Falls through to the Specification-based query, which does not From 9d469e0e01c2306d9332f2f30b35589a663ccc8b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:55:30 +0400 Subject: [PATCH 009/175] refactor(controller): change minPrice/maxPrice @RequestParam types to BigDecimal Spring MVC can deserialize a query parameter string like "79.99" directly into BigDecimal without loss. Using Float here would have caused rounding at the HTTP boundary before the value reached the service and the Specification predicate. --- .../springboottutorial/controller/ProductController.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java b/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java index 4837791..7d0a886 100644 --- a/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java +++ b/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java @@ -6,6 +6,7 @@ import com.edgareldy.springboottutorial.dto.product.ProductResponse; import com.edgareldy.springboottutorial.service.ProductService; import jakarta.validation.Valid; +import java.math.BigDecimal; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; @@ -40,8 +41,8 @@ public class ProductController { public ResponseEntity>> findAll( @RequestParam(required = false) Long categoryId, @RequestParam(required = false) String productName, - @RequestParam(required = false) Float minPrice, - @RequestParam(required = false) Float maxPrice, + @RequestParam(required = false) BigDecimal minPrice, + @RequestParam(required = false) BigDecimal maxPrice, Pageable pageable) { return ResponseEntity.ok(ApiResponse.success( productService.findAll(categoryId, productName, minPrice, maxPrice, pageable), From ccbc569396cc968afdcdbd5e769f90ccf338a15b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:55:57 +0400 Subject: [PATCH 010/175] test(service): update ProductServiceImplTest for BigDecimal price, description and active Replaces every float/Float literal (79.99f, 99.99f, 50f, 100f) with the equivalent BigDecimal constructor call (new BigDecimal("79.99"), etc.) to match the updated ProductRequest, ProductResponse and Product constructor signatures. Passes null for the new optional description field in ProductRequest. --- .../service/impl/ProductServiceImplTest.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java index b96be8f..d05bca8 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java @@ -17,6 +17,7 @@ import com.edgareldy.springboottutorial.mapper.ProductMapper; import com.edgareldy.springboottutorial.repository.CategoryRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; +import java.math.BigDecimal; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; @@ -61,8 +62,9 @@ class ProductServiceImplTest { @BeforeEach void setUp() { category = Category.builder().id(1L).categoryName("Electronics").build(); - product = Product.builder().id(1L).category(category).productName("Keyboard").unitPrice(79.99f).build(); - productResponse = new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics"); + product = Product.builder().id(1L).category(category).productName("Keyboard") + .unitPrice(new BigDecimal("79.99")).active(true).build(); + productResponse = new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); } @Test @@ -96,7 +98,8 @@ void _03_ShouldUseSpecification_WhenAdvancedFilterGiven() { .thenReturn(new PageImpl<>(List.of(product), pageable, 1)); when(productMapper.toResponse(product)).thenReturn(productResponse); - PageResponse result = productService.findAll(null, "key", 50f, 100f, pageable); + PageResponse result = + productService.findAll(null, "key", new BigDecimal("50"), new BigDecimal("100"), pageable); assertThat(result.content()).containsExactly(productResponse); verify(productRepository, never()).findAll(pageable); @@ -121,7 +124,7 @@ void _05_ShouldThrowNotFound_WhenProductMissing() { @Test void _06_ShouldResolveCategoryAndSave_WhenCreatingProduct() { - ProductRequest request = new ProductRequest(1L, "Keyboard", 79.99f); + ProductRequest request = new ProductRequest(1L, "Keyboard", null, new BigDecimal("79.99")); when(categoryRepository.findById(1L)).thenReturn(Optional.of(category)); when(productMapper.toEntity(request, category)).thenReturn(product); when(productRepository.save(product)).thenReturn(product); @@ -132,7 +135,7 @@ void _06_ShouldResolveCategoryAndSave_WhenCreatingProduct() { @Test void _07_ShouldThrowNotFound_WhenCategoryMissingOnCreate() { - ProductRequest request = new ProductRequest(99L, "Keyboard", 79.99f); + ProductRequest request = new ProductRequest(99L, "Keyboard", null, new BigDecimal("79.99")); when(categoryRepository.findById(99L)).thenReturn(Optional.empty()); assertThatThrownBy(() -> productService.create(request)) @@ -143,8 +146,9 @@ void _07_ShouldThrowNotFound_WhenCategoryMissingOnCreate() { @Test void _08_ShouldResolveCategoryAndSave_WhenUpdatingProduct() { - ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", 99.99f); - ProductResponse updatedResponse = new ProductResponse(1L, "Mechanical Keyboard", 99.99f, 1L, "Electronics"); + ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99")); + ProductResponse updatedResponse = + new ProductResponse(1L, "Mechanical Keyboard", new BigDecimal("99.99"), null, true, 1L, "Electronics"); when(productRepository.findById(1L)).thenReturn(Optional.of(product)); when(categoryRepository.findById(1L)).thenReturn(Optional.of(category)); when(productRepository.save(product)).thenReturn(product); @@ -157,7 +161,7 @@ void _08_ShouldResolveCategoryAndSave_WhenUpdatingProduct() { @Test void _09_ShouldThrowNotFound_WhenProductMissingOnUpdate() { - ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", 99.99f); + ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99")); when(productRepository.findById(99L)).thenReturn(Optional.empty()); assertThatThrownBy(() -> productService.update(99L, request)) @@ -168,7 +172,7 @@ void _09_ShouldThrowNotFound_WhenProductMissingOnUpdate() { @Test void _10_ShouldThrowNotFound_WhenCategoryMissingOnUpdate() { - ProductRequest request = new ProductRequest(99L, "Mechanical Keyboard", 99.99f); + ProductRequest request = new ProductRequest(99L, "Mechanical Keyboard", null, new BigDecimal("99.99")); when(productRepository.findById(1L)).thenReturn(Optional.of(product)); when(categoryRepository.findById(99L)).thenReturn(Optional.empty()); From ebc6f7f61f16365f3fb3ec511dfb3fe7d9cd942e Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:56:27 +0400 Subject: [PATCH 011/175] test(controller): update ProductControllerTest for BigDecimal price, description and active Replaces every float literal and Float wrapper with BigDecimal in all ProductRequest and ProductResponse constructor calls. Passes null for the new optional description field. The price filter assertions in _03_ now use eq(new BigDecimal("50")) and eq(new BigDecimal("100")) to match the updated controller parameter types. --- .../controller/ProductControllerTest.java | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java index e97c022..731efd0 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java @@ -18,6 +18,7 @@ import com.edgareldy.springboottutorial.dto.product.ProductResponse; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.service.ProductService; +import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -53,7 +54,8 @@ class ProductControllerTest { @Test void _01_ShouldPassNullCategoryId_WhenNoFilterGiven() throws Exception { - ProductResponse product = new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics"); + ProductResponse product = + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); when(productService.findAll(isNull(), isNull(), isNull(), isNull(), any())).thenReturn(page); @@ -64,7 +66,8 @@ void _01_ShouldPassNullCategoryId_WhenNoFilterGiven() throws Exception { @Test void _02_ShouldForwardCategoryFilter_WhenCategoryIdGiven() throws Exception { - ProductResponse product = new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics"); + ProductResponse product = + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); when(productService.findAll(eq(1L), isNull(), isNull(), isNull(), any())).thenReturn(page); @@ -75,9 +78,11 @@ void _02_ShouldForwardCategoryFilter_WhenCategoryIdGiven() throws Exception { @Test void _03_ShouldForwardNameAndPriceFilters_WhenAdvancedFiltersGiven() throws Exception { - ProductResponse product = new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics"); + ProductResponse product = + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); - when(productService.findAll(isNull(), eq("key"), eq(50f), eq(100f), any())).thenReturn(page); + when(productService.findAll(isNull(), eq("key"), eq(new BigDecimal("50")), eq(new BigDecimal("100")), any())) + .thenReturn(page); mockMvc.perform(get("/api/v1/products") .param("productName", "key") @@ -98,8 +103,9 @@ void _04_ShouldReturn404_WhenProductMissing() throws Exception { @Test void _05_ShouldReturn201_WhenCreateRequestValid() throws Exception { - ProductRequest request = new ProductRequest(1L, "Keyboard", 79.99f); - when(productService.create(any())).thenReturn(new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics")); + ProductRequest request = new ProductRequest(1L, "Keyboard", null, new BigDecimal("79.99")); + when(productService.create(any())) + .thenReturn(new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics")); mockMvc.perform(post("/api/v1/products") .contentType(MediaType.APPLICATION_JSON) @@ -110,7 +116,7 @@ void _05_ShouldReturn201_WhenCreateRequestValid() throws Exception { @Test void _06_ShouldReturn400_WhenUnitPriceNotPositive() throws Exception { - ProductRequest invalid = new ProductRequest(1L, "Keyboard", -5f); + ProductRequest invalid = new ProductRequest(1L, "Keyboard", null, new BigDecimal("-5")); mockMvc.perform(post("/api/v1/products") .contentType(MediaType.APPLICATION_JSON) @@ -121,7 +127,7 @@ void _06_ShouldReturn400_WhenUnitPriceNotPositive() throws Exception { @Test void _07_ShouldReturn404_WhenCategoryMissingOnCreate() throws Exception { - ProductRequest request = new ProductRequest(99L, "Keyboard", 79.99f); + ProductRequest request = new ProductRequest(99L, "Keyboard", null, new BigDecimal("79.99")); when(productService.create(any())).thenThrow(new ResourceNotFoundException("Category not found with id 99")); mockMvc.perform(post("/api/v1/products") @@ -132,9 +138,10 @@ void _07_ShouldReturn404_WhenCategoryMissingOnCreate() throws Exception { @Test void _08_ShouldReturn200_WhenUpdateRequestValid() throws Exception { - ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", 99.99f); + ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99")); when(productService.update(eq(1L), any())) - .thenReturn(new ProductResponse(1L, "Mechanical Keyboard", 99.99f, 1L, "Electronics")); + .thenReturn(new ProductResponse( + 1L, "Mechanical Keyboard", new BigDecimal("99.99"), null, true, 1L, "Electronics")); mockMvc.perform(put("/api/v1/products/1") .contentType(MediaType.APPLICATION_JSON) @@ -145,7 +152,7 @@ void _08_ShouldReturn200_WhenUpdateRequestValid() throws Exception { @Test void _09_ShouldReturn409_WhenProductIsStale() throws Exception { - ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", 99.99f); + ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99")); when(productService.update(eq(1L), any())) .thenThrow(new ObjectOptimisticLockingFailureException(Object.class, 1L)); @@ -158,7 +165,7 @@ void _09_ShouldReturn409_WhenProductIsStale() throws Exception { @Test void _10_ShouldReturn404_WhenProductMissingOnUpdate() throws Exception { - ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", 99.99f); + ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99")); when(productService.update(eq(99L), any())) .thenThrow(new ResourceNotFoundException("Product not found with id 99")); From 3bfdc6bf80f3eaf4e22d07ca4b7110b513805bcc Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:56:46 +0400 Subject: [PATCH 012/175] test(mapper): update ProductMapperTest for BigDecimal and verify active is not overwritten Changes float literals to BigDecimal, passes description in _01_ (non-null) and null in _02_ to cover both branches. _02_ also explicitly asserts that updateEntityFromRequest does not overwrite an existing active=false value, verifying the @Mapping(ignore=true) on that field in ProductMapper. --- .../mapper/ProductMapperTest.java | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/mapper/ProductMapperTest.java b/src/test/java/com/edgareldy/springboottutorial/mapper/ProductMapperTest.java index e8e296e..ac19238 100644 --- a/src/test/java/com/edgareldy/springboottutorial/mapper/ProductMapperTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/mapper/ProductMapperTest.java @@ -5,6 +5,7 @@ import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; +import java.math.BigDecimal; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -14,7 +15,8 @@ * the service tests mock the mapper, so only this class can prove that * {@link ProductMapper#toEntity} and {@link ProductMapper#updateEntityFromRequest} * really assign the category handed in by the service, and never the - * identity or the version. + * identity or the version. Also verifies that {@code active} is not overwritten + * by write mappings, since {@link ProductRequest} carries no active field. *

* Created edgar.muhamyangabo on 9/21/26 * Author : edgar.muhamyangabo @@ -30,7 +32,7 @@ class ProductMapperTest { @Test void _01_ShouldAssignRequestFieldsAndCategory_WhenBuildingNewProduct() { Category category = Category.builder().id(1L).categoryName("Electronics").build(); - ProductRequest request = new ProductRequest(1L, "Keyboard", 79.99f); + ProductRequest request = new ProductRequest(1L, "Keyboard", "A mechanical keyboard", new BigDecimal("79.99")); Product product = productMapper.toEntity(request, category); @@ -38,7 +40,10 @@ void _01_ShouldAssignRequestFieldsAndCategory_WhenBuildingNewProduct() { assertThat(product.getVersion()).isNull(); assertThat(product.getCategory()).isSameAs(category); assertThat(product.getProductName()).isEqualTo("Keyboard"); - assertThat(product.getUnitPrice()).isEqualTo(79.99f); + assertThat(product.getDescription()).isEqualTo("A mechanical keyboard"); + assertThat(product.getUnitPrice()).isEqualByComparingTo(new BigDecimal("79.99")); + // active is ignored on toEntity; the @Builder.Default gives it true + assertThat(product.isActive()).isTrue(); } @Test @@ -46,14 +51,18 @@ void _02_ShouldKeepIdentityAndReplaceCategory_WhenUpdatingExistingProduct() { Category oldCategory = Category.builder().id(1L).categoryName("Electronics").build(); Category newCategory = Category.builder().id(2L).categoryName("Office").build(); Product existing = Product.builder().id(10L).version(3L).category(oldCategory) - .productName("Keyboard").unitPrice(79.99f).build(); + .productName("Keyboard").unitPrice(new BigDecimal("79.99")).active(false).build(); - productMapper.updateEntityFromRequest(new ProductRequest(2L, "Mechanical Keyboard", 99.99f), newCategory, existing); + productMapper.updateEntityFromRequest( + new ProductRequest(2L, "Mechanical Keyboard", null, new BigDecimal("99.99")), + newCategory, existing); assertThat(existing.getId()).isEqualTo(10L); assertThat(existing.getVersion()).isEqualTo(3L); assertThat(existing.getCategory()).isSameAs(newCategory); assertThat(existing.getProductName()).isEqualTo("Mechanical Keyboard"); - assertThat(existing.getUnitPrice()).isEqualTo(99.99f); + assertThat(existing.getUnitPrice()).isEqualByComparingTo(new BigDecimal("99.99")); + // active must NOT be overwritten by updateEntityFromRequest + assertThat(existing.isActive()).isFalse(); } } From a054e0f527aaf03789685224332a5adaa29d1d18 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:57:06 +0400 Subject: [PATCH 013/175] test(repository): update ProductRepositoryTest for BigDecimal unitPrice Replaces all float literals (79.99f, 199.99f, 29.99f, 19.99f) with BigDecimal string-constructor equivalents in setUp() and in _04_. No behavioral change: the test logic and assertions remain identical. --- .../repository/ProductRepositoryTest.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java index db1ce69..0a6053b 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java @@ -6,6 +6,7 @@ import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; import jakarta.persistence.EntityManager; +import java.math.BigDecimal; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -46,9 +47,9 @@ void setUp() { electronics = categoryRepository.save(Category.builder().categoryName("Electronics").build()); furniture = categoryRepository.save(Category.builder().categoryName("Furniture").build()); productRepository.save(Product.builder() - .category(electronics).productName("Keyboard").unitPrice(79.99f).build()); + .category(electronics).productName("Keyboard").unitPrice(new BigDecimal("79.99")).build()); productRepository.save(Product.builder() - .category(furniture).productName("Desk").unitPrice(199.99f).build()); + .category(furniture).productName("Desk").unitPrice(new BigDecimal("199.99")).build()); } @Test @@ -85,7 +86,8 @@ void _03_ShouldLoadCategoryEagerly_WhenFindingProductById() { @Test void _04_ShouldThrowOptimisticLockingFailure_WhenProductIsStale() { Product saved = productRepository.saveAndFlush( - Product.builder().category(electronics).productName("Mouse").unitPrice(29.99f).build()); + Product.builder().category(electronics).productName("Mouse") + .unitPrice(new BigDecimal("29.99")).build()); // Simulates a concurrent update from another transaction: bumps the row's // version directly in the database, bypassing this test's persistence @@ -94,7 +96,7 @@ void _04_ShouldThrowOptimisticLockingFailure_WhenProductIsStale() { .setParameter("id", saved.getId()) .executeUpdate(); - saved.setUnitPrice(19.99f); + saved.setUnitPrice(new BigDecimal("19.99")); assertThatThrownBy(() -> productRepository.saveAndFlush(saved)) .isInstanceOf(ObjectOptimisticLockingFailureException.class); } From dd74595249b32acdee0b3a17a4b5bca770543aa3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:57:34 +0400 Subject: [PATCH 014/175] test(service): update ProductServiceCacheTest for BigDecimal price, description and active Replaces float literals with BigDecimal in sampleProduct() and all ProductResponse constructors. Passes null for description and true for the new active field. No change to the caching behavior being verified. --- .../service/impl/ProductServiceCacheTest.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java index e00ae4c..2f3ffee 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java @@ -13,6 +13,7 @@ import com.edgareldy.springboottutorial.repository.CategoryRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import com.edgareldy.springboottutorial.service.ProductService; +import java.math.BigDecimal; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -79,13 +80,15 @@ void clearCache() { private static Product sampleProduct() { Category category = Category.builder().id(1L).categoryName("Electronics").build(); - return Product.builder().id(1L).category(category).productName("Keyboard").unitPrice(79.99f).build(); + return Product.builder().id(1L).category(category).productName("Keyboard") + .unitPrice(new BigDecimal("79.99")).build(); } @Test void _01_ShouldHitRepositoryOnce_WhenFindByIdCalledTwice() { Product product = sampleProduct(); - ProductResponse response = new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics"); + ProductResponse response = + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); when(productMapper.toResponse(product)).thenReturn(response); @@ -98,7 +101,8 @@ void _01_ShouldHitRepositoryOnce_WhenFindByIdCalledTwice() { @Test void _02_ShouldEvictCache_WhenProductUpdated() { Product product = sampleProduct(); - ProductResponse response = new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics"); + ProductResponse response = + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); when(productMapper.toResponse(product)).thenReturn(response); when(productRepository.findById(1L)).thenReturn(Optional.of(product)); @@ -106,7 +110,7 @@ void _02_ShouldEvictCache_WhenProductUpdated() { when(productRepository.save(any(Product.class))).thenReturn(product); productService.findById(1L); - productService.update(1L, new ProductRequest(1L, "Mechanical Keyboard", 99.99f)); + productService.update(1L, new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99"))); productService.findById(1L); verify(productRepository, times(2)).findByIdWithCategory(1L); @@ -115,7 +119,8 @@ void _02_ShouldEvictCache_WhenProductUpdated() { @Test void _03_ShouldEvictCache_WhenProductDeleted() { Product product = sampleProduct(); - ProductResponse response = new ProductResponse(1L, "Keyboard", 79.99f, 1L, "Electronics"); + ProductResponse response = + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); when(productMapper.toResponse(product)).thenReturn(response); when(productRepository.existsById(1L)).thenReturn(true); From dcb8a46f4ff8a36e7a639e6c05e285720267afc1 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 11:58:09 +0400 Subject: [PATCH 015/175] docs(readme): update feature/products section for e-commerce catalogue changes - Products table schema: adds description (VARCHAR(500), nullable), active (BOOLEAN, default TRUE) and changes unit_price type from FLOAT to NUMERIC(12,2). - Tasks checklist: adds two new checked items for BigDecimal/NUMERIC(12,2) and description/active. - Configuration notes: updates the Flyway numbering note to include V13 and explain the V5-V12 gap; adds notes on BigDecimal throughout the stack and the active-field immutability via the mapper. --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f537d55..a4cc7d9 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,9 @@ customers (id, first_name, last_name, telephone, email, address) | id | BIGINT | PK, auto-increment | | category_id | BIGINT | FK → categories.id, NOT NULL | | product_name | VARCHAR(255) | NOT NULL | -| unit_price | FLOAT | NOT NULL, > 0 | +| description | VARCHAR(500) | nullable | +| unit_price | NUMERIC(12,2) | NOT NULL, > 0 | +| active | BOOLEAN | NOT NULL, default TRUE | **customers** | Column | Type | Constraints | @@ -346,6 +348,8 @@ Includes `Category` and `Product`, given their direct link in the model. - [x] `Category`, `Product` entities with `@OneToMany`/`@ManyToOne` relation (`LAZY` loading) - [x] `CategoryRepository`, `ProductRepository` (Spring Data JPA) with derived queries (`findByCategoryId`) and one `@Query` using `JOIN FETCH` - [x] DTOs `CategoryRequest`/`CategoryResponse`, `ProductRequest`/`ProductResponse` +- [x] `Product.unitPrice` uses `BigDecimal` (Java) backed by `NUMERIC(12,2)` (SQL, V13 migration) for exact monetary arithmetic +- [x] `Product.description` (nullable `VARCHAR(500)`) and `Product.active` (boolean, default `true`, V13 migration) - [x] Corresponding MapStruct mappers - [x] `CategoryService`, `ProductService` interfaces (contracts) and their `CategoryServiceImpl`, `ProductServiceImpl` implementations in `service/impl`, annotated `@Service`, with `@Transactional` on writes - [x] Business rule: a category containing products cannot be deleted (`BusinessRuleException`) @@ -364,8 +368,10 @@ Includes `Category` and `Product`, given their direct link in the model. - **`CategoryResponse.products` is only populated by `GET /api/v1/categories/{id}`, never by the paginated list.** `CategoryRepository.findByIdWithProducts` (`LEFT JOIN FETCH`) backs the detail endpoint; the list endpoint's `CategoryMapper.toResponse` explicitly sets `products` to an empty list rather than touching the entity's lazy, unfetched collection, avoiding an N+1 across a full page of categories. - **Snake_case JSON via `@JsonProperty` per field, not a global Jackson naming strategy.** Keeps every Java field/record component camelCase (idiomatic, and MapStruct keeps matching DTO fields to entity fields by name automatically) while the public JSON contract is snake_case. -- **Flyway migrations on this branch are numbered `V3`/`V4`, skipping `V2`.** `V2` is reserved for `feature/auth`'s `V2__init_users_and_roles.sql`, not present on this branch yet; Flyway version numbers must stay unique and ordered across the whole project regardless of merge order. +- **Flyway migrations on this branch are numbered `V3`, `V4` and `V13`, skipping `V2` and `V5-V12`.** `V2` is reserved for `feature/auth`; `V5-V12` are reserved for branches from `feature/auth` through `feature/user-management` that appear further up the merge chain. `V13` adds `description`, `active` and migrates `unit_price` from `REAL` to `NUMERIC(12,2)` on the products table. - **`ProductServiceImpl.findAll` only falls back to a `Specification`-based query when `productName`/`minPrice`/`maxPrice` is supplied.** The plain and `categoryId`-only cases keep using the existing `@EntityGraph`-backed repository methods; the `Specification` path has no fetch join for `category`, an accepted N+1 risk kept simple rather than complicating `ProductSpecifications` with one, and scoped only to requests that actually use the new filters. +- **`minPrice`/`maxPrice` query parameters and `unitPrice` throughout the stack use `BigDecimal`.** `ProductSpecifications.priceBetween`, `ProductService.findAll`, `ProductController.findAll` and all DTOs have been updated from `Float`/`float` to `BigDecimal` to prevent rounding at the HTTP deserialization boundary. +- **`Product.active` is not writable from `ProductRequest`.** `ProductMapper.toEntity` and `updateEntityFromRequest` both ignore `active` to prevent a create/update call from accidentally clearing the flag. Activation and deactivation are managed separately. ## feature/customers From e781c6a6fe73b657c26c2d18fc73c6ed25b3f335 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:05:12 +0400 Subject: [PATCH 016/175] fix(config): migrate DataSeeder unitPrice literals from float to BigDecimal Product.unitPrice is now BigDecimal (V13 migration). The DataSeeder was still building Product instances with float literals (79.99f, 29.99f, 45.50f), which caused a type mismatch against the updated Lombok builder. --- .../edgareldy/springboottutorial/config/DataSeeder.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java index 7327741..fce6987 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java @@ -4,6 +4,7 @@ import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.repository.CategoryRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; +import java.math.BigDecimal; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; @@ -43,11 +44,11 @@ public CommandLineRunner seedDemoData( Category books = categoryRepository.save(Category.builder().categoryName("Books").build()); productRepository.save(Product.builder() - .category(electronics).productName("Mechanical Keyboard").unitPrice(79.99f).build()); + .category(electronics).productName("Mechanical Keyboard").unitPrice(new BigDecimal("79.99")).build()); productRepository.save(Product.builder() - .category(electronics).productName("Wireless Mouse").unitPrice(29.99f).build()); + .category(electronics).productName("Wireless Mouse").unitPrice(new BigDecimal("29.99")).build()); productRepository.save(Product.builder() - .category(books).productName("Effective Java").unitPrice(45.50f).build()); + .category(books).productName("Effective Java").unitPrice(new BigDecimal("45.50")).build()); } }; } From fe538439c9bbfc084c9c692b3066d23bb3d62d07 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:05:16 +0400 Subject: [PATCH 017/175] fix(test): update CategoryControllerTest for BigDecimal unitPrice and new ProductResponse fields ProductResponse now carries BigDecimal unitPrice, description and active. The inline ProductResponse constructor call used the old float literal and the old 5-arg signature; updated to the current 7-arg signature with BigDecimal and null description. --- .../springboottutorial/controller/CategoryControllerTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java index eafd019..06b790c 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java @@ -16,6 +16,7 @@ import com.edgareldy.springboottutorial.dto.category.CategoryResponse; import com.edgareldy.springboottutorial.dto.common.PageResponse; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import java.math.BigDecimal; import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.service.CategoryService; @@ -74,7 +75,7 @@ void _02_ShouldReturnCategory_WhenCategoryFound() throws Exception { @Test void _03_ShouldIncludeProducts_WhenFindingCategoryById() throws Exception { - ProductResponse keyboard = new ProductResponse(10L, "Keyboard", 79.99f, 1L, "Electronics"); + ProductResponse keyboard = new ProductResponse(10L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); when(categoryService.findById(1L)) .thenReturn(new CategoryResponse(1L, "Electronics", null, null, List.of(keyboard))); From a080efd6ca7a01c4a1a658e2dc7315bf0b7a97c3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:05:20 +0400 Subject: [PATCH 018/175] fix(test): update CategoryMapperTest for BigDecimal unitPrice in Product builder Product.unitPrice is now BigDecimal. The inline builder call used a float literal; replaced with new BigDecimal("79.99"). --- .../springboottutorial/mapper/CategoryMapperTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/mapper/CategoryMapperTest.java b/src/test/java/com/edgareldy/springboottutorial/mapper/CategoryMapperTest.java index a69a7c8..4982072 100644 --- a/src/test/java/com/edgareldy/springboottutorial/mapper/CategoryMapperTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/mapper/CategoryMapperTest.java @@ -5,6 +5,7 @@ import com.edgareldy.springboottutorial.dto.category.CategoryResponse; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; +import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -30,7 +31,7 @@ class CategoryMapperTest { private Category categoryWithProducts() { Category category = Category.builder().id(1L).categoryName("Electronics").build(); - Product keyboard = Product.builder().id(10L).category(category).productName("Keyboard").unitPrice(79.99f).build(); + Product keyboard = Product.builder().id(10L).category(category).productName("Keyboard").unitPrice(new BigDecimal("79.99")).build(); category.setProducts(List.of(keyboard)); return category; } From 7efc60afc7c9dcaba103d5b2dba41a3069ad41f5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:05:23 +0400 Subject: [PATCH 019/175] fix(test): update CategoryRepositoryTest for BigDecimal unitPrice in Product builder Product.unitPrice is now BigDecimal. Two builder calls used float literals (79.99f, 29.99f); replaced with BigDecimal equivalents. --- .../repository/CategoryRepositoryTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/CategoryRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/CategoryRepositoryTest.java index 80059ef..7cb1a77 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/CategoryRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/CategoryRepositoryTest.java @@ -7,6 +7,7 @@ import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; import jakarta.persistence.EntityManager; +import java.math.BigDecimal; import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -81,9 +82,9 @@ void _03_ShouldChangeOnlyUpdatedAt_WhenCategoryUpdated() throws InterruptedExcep void _04_ShouldLoadProducts_WhenCategoryHasProducts() { Category saved = categoryRepository.saveAndFlush(Category.builder().categoryName("Electronics").build()); productRepository.saveAndFlush( - Product.builder().category(saved).productName("Keyboard").unitPrice(79.99f).build()); + Product.builder().category(saved).productName("Keyboard").unitPrice(new BigDecimal("79.99")).build()); productRepository.saveAndFlush( - Product.builder().category(saved).productName("Mouse").unitPrice(29.99f).build()); + Product.builder().category(saved).productName("Mouse").unitPrice(new BigDecimal("29.99")).build()); entityManager.clear(); Category found = categoryRepository.findByIdWithProducts(saved.getId()).orElseThrow(); From f6ca4a4a33bbe136d3832b44b159965d05652ca6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:10:20 +0400 Subject: [PATCH 020/175] fix(test): import JpaAuditingConfig in ProductRepositoryTest Category has NOT NULL audit columns (created_at, updated_at from V4). Without @EnableJpaAuditing, Hibernate sends NULL for those columns, violating the constraint. The test only passed in the full suite because CategoryRepositoryTest (which does import JpaAuditingConfig) ran first and its Spring context was reused - an execution-order dependency. Same fix already applied to OrderRepositoryTest per CLAUDE.md; now applied consistently here. --- .../springboottutorial/repository/ProductRepositoryTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java index 0a6053b..18f5da4 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.edgareldy.springboottutorial.config.JpaAuditingConfig; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; import jakarta.persistence.EntityManager; @@ -27,7 +28,7 @@ */ @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) -@Import(RepositoryTestcontainersConfiguration.class) +@Import({RepositoryTestcontainersConfiguration.class, JpaAuditingConfig.class}) class ProductRepositoryTest { @Autowired From e46611e6c7fd913cc8f1043d15264ca9a20b937d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:10:37 +0400 Subject: [PATCH 021/175] fix(config): remove unused resetUserPasswords parameter from DataSeeder The parameter was injected via @Value but never read in the method body. On feature/products there is no user-password logic, so this was dead code that could mislead a reader into thinking a reset feature existed. Removed along with its now-unnecessary @Value import. --- .../com/edgareldy/springboottutorial/config/DataSeeder.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java index fce6987..0a704f5 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java @@ -6,7 +6,6 @@ import com.edgareldy.springboottutorial.repository.ProductRepository; import java.math.BigDecimal; import lombok.RequiredArgsConstructor; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,8 +35,7 @@ public class DataSeeder { private final ProductRepository productRepository; @Bean - public CommandLineRunner seedDemoData( - @Value("${app.seed.reset-user-passwords:false}") boolean resetUserPasswords) { + public CommandLineRunner seedDemoData() { return args -> { if (categoryRepository.count() == 0) { Category electronics = categoryRepository.save(Category.builder().categoryName("Electronics").build()); From f521a04c0ad0f0216338508748387d9ccc8f4333 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:10:50 +0400 Subject: [PATCH 022/175] docs(mapper): fix ProductMapper Javadoc - remove mention of nonexistent endpoint The previous wording implied that a dedicated activation endpoint manages the active flag. No such endpoint exists on this branch. Replaced with a plain statement of intent: the flag is excluded from create/update payloads so it cannot be overwritten accidentally. --- .../edgareldy/springboottutorial/mapper/ProductMapper.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java index 3ec9317..e3facd1 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java @@ -13,9 +13,8 @@ * {@code category} association is looked up by the service layer (which needs * a repository lookup) and handed to the entity-building methods as a * parameter: this mapper only assigns it, so the service never calls a - * setter itself. {@code active} is ignored on writes: the flag is managed - * via a dedicated activation endpoint, not through the product create/update - * payload, so it must never be overwritten by {@link ProductRequest}. + * setter itself. {@code active} is ignored on writes so that create and update + * operations cannot inadvertently overwrite the flag via {@link ProductRequest}. *

* Created edgar.muhamyangabo on 7/4/26 * Author : edgar.muhamyangabo From 831ee203a3e8debd4f763a91b589582ddfff84f4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:11:02 +0400 Subject: [PATCH 023/175] test(controller): verify active=false is serialised in ProductControllerTest All previous fixtures used active=true. Test _13_ adds an inactive product to confirm that the boolean field is correctly serialised as false in the JSON response - a gap the MockMvc slice could not detect without an explicit assertion on the value false. --- .../controller/ProductControllerTest.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java index 731efd0..1b063fe 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java @@ -191,4 +191,14 @@ void _12_ShouldReturn404_WhenProductMissingOnDelete() throws Exception { .andExpect(status().isNotFound()) .andExpect(jsonPath("$.success").value(false)); } + + @Test + void _13_ShouldSerializeActiveFalse_WhenProductIsInactive() throws Exception { + when(productService.findById(2L)) + .thenReturn(new ProductResponse(2L, "Legacy Keyboard", new BigDecimal("49.99"), "Discontinued model", false, 1L, "Electronics")); + + mockMvc.perform(get("/api/v1/products/2")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.active").value(false)); + } } From 4adb9eb3a14cd748cd8fdccf71cdbc8480346ae6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:27:48 +0400 Subject: [PATCH 024/175] docs(readme): add e-commerce extension to global README sections Adds the 6 new e-commerce branches to every global section: - Table of contents: 6 new entries (product-images through integration) - Data model: products table updated (NUMERIC(12,2), description, active); orders extended (user_id, order_number, status, total_amount); new tables: order_items, product_images, cart, cart_items - Branching strategy table: 6 new rows with branch roles - Order of work: steps 9-14 with correct merge/PR strategy (only feature/integration has a PR to develop; others are feature-to-feature merges) - Concepts covered: file upload, persistent cart, atomic checkout, role-based data ownership - How to follow this tutorial: step 3 lists all 13 branches - 6 new branch sections with endpoints, task checklists, and configuration notes --- README.md | 217 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 211 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 2f5b583..6effcd7 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,12 @@ Repository: https://github.com/EdgarEldy/spring-boot-tutorial - [feature/roles-permissions](#featureroles-permissions) - [feature/token-management](#featuretoken-management) - [feature/user-management](#featureuser-management) +- [feature/product-images](#featureproduct-images) +- [feature/shopping-cart](#featureshopping-cart) +- [feature/order-checkout](#featureorder-checkout) +- [feature/order-notifications](#featureorder-notifications) +- [feature/order-authorization](#featureorder-authorization) +- [feature/integration](#featureintegration) - [Order of work](#order-of-work) - [Code conventions](#code-conventions) - [Concepts covered](#concepts-covered) @@ -82,7 +88,9 @@ customers (id, first_name, last_name, telephone, email, address) | id | BIGINT | PK, auto-increment | | category_id | BIGINT | FK → categories.id, NOT NULL | | product_name | VARCHAR(255) | NOT NULL | -| unit_price | FLOAT | NOT NULL, > 0 | +| unit_price | NUMERIC(12,2) | NOT NULL, > 0 — migrated from FLOAT in V13 for exact monetary arithmetic | +| description | VARCHAR(500) | nullable — added in V13 | +| active | BOOLEAN | NOT NULL DEFAULT TRUE — added in V13; excluded from create/update payloads | **customers** | Column | Type | Constraints | @@ -94,14 +102,47 @@ customers (id, first_name, last_name, telephone, email, address) | email | VARCHAR(255) | NOT NULL, UNIQUE, valid email format | | address | VARCHAR(255) | NOT NULL | -**orders** +**orders** (extended in `feature/orders` and `feature/order-checkout`) | Column | Type | Constraints | |---|---|---| | id | BIGINT | PK, auto-increment | -| customer_id | BIGINT | FK → customers.id, NOT NULL | +| customer_id | BIGINT | FK → customers.id, nullable after e-commerce refactor (kept for history) | +| user_id | BIGINT | FK → app_users.id, NOT NULL — added in V14; ties each order to its authenticated owner | +| order_number | VARCHAR(36) | NOT NULL UNIQUE — UUID generated at creation | +| status | VARCHAR(20) | NOT NULL DEFAULT 'PENDING' — PENDING, CONFIRMED, SHIPPED, DELIVERED, CANCELLED | +| total_amount | NUMERIC(12,2) | NOT NULL — sum of all OrderItem lines | + +**order_items** (added in V14) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| order_id | BIGINT | FK → orders.id, NOT NULL | +| product_id | BIGINT | FK → products.id, NOT NULL | +| quantity | INT | NOT NULL, > 0 | +| unit_price | NUMERIC(12,2) | NOT NULL — snapshot at order time | + +**product_images** (added in V15) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| product_id | BIGINT | FK → products.id, NOT NULL | +| filename | VARCHAR(255) | NOT NULL | +| url | VARCHAR(512) | NOT NULL | +| sort_order | INT | NOT NULL DEFAULT 0 | + +**cart** (added in V16) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| user_id | BIGINT | FK → app_users.id, NOT NULL UNIQUE | + +**cart_items** (added in V16) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| cart_id | BIGINT | FK → cart.id, NOT NULL | | product_id | BIGINT | FK → products.id, NOT NULL | | quantity | INT | NOT NULL, > 0 | -| total | DOUBLE | NOT NULL, computed = quantity × product unit_price | ## Branching strategy @@ -117,6 +158,12 @@ customers (id, first_name, last_name, telephone, email, address) | `feature/roles-permissions` | Fine-grained Role/Permission CRUD and method-level security (`@PreAuthorize`, custom `PermissionEvaluator`). | | `feature/token-management` | Activation, blacklisted and password-reset tokens; async email (`@Async`); scheduled cleanup (`@Scheduled`). | | `feature/user-management` | `AppUser` CRUD (admin), user-role assignment (`role_user` join table, V7), account activation/password-reset flows. | +| `feature/product-images` | Product image upload: `ProductImage` entity (V15), `FileStorageService`, `POST`/`DELETE /api/v1/products/{id}/images` (ROLE_ADMIN). | +| `feature/shopping-cart` | Persistent shopping cart: `Cart`/`CartItem` entities (V16), full CRUD endpoints tied to the authenticated user (`@AuthenticationPrincipal`). | +| `feature/order-checkout` | Atomic checkout: `POST /api/v1/orders` drains the cart and creates an `Order` with `OrderItem` lines in a single transaction. Introduces `order_items` table (V14), `order_number`, `status`, `total_amount`. | +| `feature/order-notifications` | Email notification on order placement via `OrderEmailService` (`@Async`) and `NotificationProperties` (`@ConfigurationProperties`). | +| `feature/order-authorization` | Role-based order access: users see only their own orders, admins see all; `PATCH /api/v1/orders/{id}/status` restricted to ROLE_ADMIN. | +| `feature/integration` | Merges `feature/product-images` into the main chain; end-to-end `EcommerceIntegrationTest` covering the full flow from registration to order status update. | Each feature is developed on its own branch, then merged into `develop` via a documented **Pull Request** (even solo), to keep a clear, educational trace of each step. In practice, on this particular repository, merges have been done locally (`git merge`) rather than through an actual GitHub Pull Request: this section describes the intended workflow for anyone forking or following along, not necessarily every merge already present in this history. @@ -533,7 +580,13 @@ Admin-facing user management: list, view, activate/deactivate accounts, assign r 6. `feature/roles-permissions` (fine-grained RBAC) → Pull Request to `develop` 7. `feature/token-management` (token lifecycle, async email, scheduled cleanup) → Pull Request to `develop` 8. `feature/user-management` (admin user CRUD, activation/reset flows) → Pull Request to `develop` -9. `develop` → `master` once everything is tested and validated +9. `feature/product-images` (from `feature/products` HEAD — independent of the auth chain) — no PR, merged into `feature/integration` only +10. `feature/shopping-cart` (from `feature/user-management`, merges `feature/orders`) — no PR, merged into next branch +11. `feature/order-checkout` (from `feature/shopping-cart`) — no PR, merged into next branch +12. `feature/order-notifications` (from `feature/order-checkout`) — no PR, merged into next branch +13. `feature/order-authorization` (from `feature/order-notifications`) — no PR, merged into next branch +14. `feature/integration` (from `feature/order-authorization`, merges `feature/product-images`) → **single Pull Request to `develop`** for the entire e-commerce chain +15. `develop` → `master` once everything is tested and validated ## Code conventions @@ -574,13 +627,165 @@ Admin-facing user management: list, view, activate/deactivate accounts, assign r - Aspect-oriented programming (Spring AOP: `@Around`, `@Before`, `@After`, `@AfterReturning`, `@AfterThrowing`) - Containerization (Docker, docker-compose) - Continuous integration (GitHub Actions) +- File upload (`MultipartFile`, `FileStorageService`, disk storage with configurable path) +- Persistent shopping cart (entity-backed cart tied to authenticated user) +- Atomic checkout (multi-entity transactional write: cart drain + order creation) +- Role-based data ownership (`@AuthenticationPrincipal`, users see only their own orders) ## How to follow this tutorial 1. Clone the repository and check out `develop` 2. Create/checkout the `feature/core-architecture` branch and follow its task checklist -3. Continue with `feature/products`, `feature/customers`, `feature/orders`, `feature/auth`, `feature/roles-permissions`, `feature/token-management`, `feature/user-management` in that order +3. Continue with `feature/products`, `feature/customers`, `feature/orders`, `feature/auth`, `feature/roles-permissions`, `feature/token-management`, `feature/user-management`, `feature/product-images`, `feature/shopping-cart`, `feature/order-checkout`, `feature/order-notifications`, `feature/order-authorization`, `feature/integration` in that order 4. Open a Pull Request to `develop` at the end of each branch 5. Copy `.env.example` to `.env` and fill in the required variables 6. Run the project with `docker-compose up`, then open Swagger UI at `http://localhost:8080/swagger-ui.html` 7. MailHog UI is available at `http://localhost:8025` to inspect outgoing emails in local dev + +## feature/product-images + +Adds image management to the product catalogue. Created from `feature/products` HEAD, independent of the main authentication/user chain. + +### Endpoints + +| Method | URL | Description | +|---|---|---| +| POST | `/api/v1/products/{id}/images` | Upload an image for a product (multipart/form-data, ROLE_ADMIN) | +| DELETE | `/api/v1/products/{id}/images/{imageId}` | Delete a product image (ROLE_ADMIN) | + +### Tasks + +- [ ] `ProductImage` entity (`product_id`, `filename`, `url`, `sort_order`) +- [ ] Flyway migration V15 +- [ ] `FileStorageService` interface + `LocalFileStorageService` impl (stores files under `${app.storage.upload-dir}`) +- [ ] `StorageProperties` record (`@ConfigurationProperties(prefix = "app.storage")`, `uploadDir`, `maxFileSizeMb`) +- [ ] `POST /api/v1/products/{id}/images`: receives `MultipartFile`, delegates to `FileStorageService`, persists `ProductImage` +- [ ] `DELETE /api/v1/products/{id}/images/{imageId}`: deletes record and removes file from disk +- [ ] `ProductResponse` gains `List images` (always populated) +- [ ] Unit tests for `FileStorageService` (happy path, size limit, unsupported type) +- [ ] MockMvc controller tests + +### Configuration notes + +- **Branch is independent of the auth chain** (`feature/auth` through `feature/user-management`). It is merged into `feature/integration` at the end, not cascaded through the main chain. +- **`StorageProperties` is a `record` with `@ConfigurationProperties`**, consistent with `JwtProperties` from `feature/auth`. +- **File type validation** rejects anything that is not `image/jpeg`, `image/png` or `image/webp`. + +## feature/shopping-cart + +Persistent shopping cart backed by JPA entities, one cart per authenticated user. + +### Endpoints + +| Method | URL | Description | +|---|---|---| +| GET | `/api/v1/cart` | Get the current user's cart (creates it if absent) | +| POST | `/api/v1/cart/items` | Add a product to the cart | +| PATCH | `/api/v1/cart/items/{itemId}` | Update item quantity | +| DELETE | `/api/v1/cart/items/{itemId}` | Remove a single item | +| DELETE | `/api/v1/cart` | Clear the entire cart | + +### Tasks + +- [ ] `Cart` entity (`user_id` FK → `app_users`, timestamps via `@CreatedDate`/`@LastModifiedDate`) +- [ ] `CartItem` entity (`cart_id`, `product_id`, `quantity`) +- [ ] Flyway migration V16 +- [ ] `CartService` interface + `CartServiceImpl` +- [ ] All endpoints require ROLE_USER; user resolved via `@AuthenticationPrincipal UserDetails` +- [ ] `CartResponse` DTO: `id`, `List items`, `total` (sum computed server-side) +- [ ] `AddCartItemRequest` / `UpdateCartItemRequest` DTOs with validation +- [ ] Unit tests (Mockito) + MockMvc controller tests + +### Configuration notes + +- **Cart is created lazily** on first `GET /api/v1/cart` for a user who has none. +- **`total` is computed by the service layer** from live product prices, never stored. +- Branch starts from `feature/user-management` (needs `AppUser`) and merges `feature/orders` (needs `Order` schema context for checkout). + +## feature/order-checkout + +Atomic cart-to-order conversion: a single `POST /api/v1/orders` drains the cart and creates a fully populated `Order` with `OrderItem` lines. + +### Endpoints + +| Method | URL | Description | +|---|---|---| +| POST | `/api/v1/orders` | Checkout: convert cart to order (ROLE_USER) | +| GET | `/api/v1/orders` | List the current user's orders, paginated | +| GET | `/api/v1/orders/{id}` | Order detail with items | + +### Tasks + +- [ ] `OrderItem` entity (`order_id`, `product_id`, `quantity`, `unit_price` snapshot) +- [ ] `Order` refactor: add `user_id`, `order_number` (UUID), `status` enum (PENDING/CONFIRMED/SHIPPED/DELIVERED/CANCELLED), `total_amount NUMERIC(12,2)` +- [ ] Flyway migration V14 (new columns, `order_items` table, historical data migration) +- [ ] `CheckoutService` or `OrderService.checkout(UserDetails)`: `@Transactional`, loads cart, creates `Order` + `OrderItem` lines (price snapshot), clears cart +- [ ] `CheckoutRequest` DTO (optional `notes` field) +- [ ] `OrderResponse` DTO: `id`, `orderNumber`, `status`, `totalAmount`, `List items`, `createdAt` +- [ ] Service unit tests (atomic write, empty-cart 422, out-of-stock 422) +- [ ] MockMvc controller tests + +### Configuration notes + +- **Price snapshot**: `OrderItem.unitPrice` captures `Product.unitPrice` at checkout time so future price changes do not alter historical orders. +- **Empty cart returns 422** (`BusinessRuleException`), not 400. +- **`order_number` is a UUID** generated by the service, never supplied by the client. + +## feature/order-notifications + +Sends an email to the user and to the admin when an order is placed, using the existing Spring Mail infrastructure (`JavaMailSender`, MailHog on dev). + +### Tasks + +- [ ] `NotificationProperties` record (`@ConfigurationProperties(prefix = "app.notifications")`, `adminEmail`) +- [ ] `OrderEmailService` interface + `OrderEmailServiceImpl`: `sendOrderConfirmationToUser(Order)` and `sendOrderAlertToAdmin(Order)`, both `@Async("emailTaskExecutor")` +- [ ] `OrderCreatedEventListener` updated to call `OrderEmailService` after commit (`@TransactionalEventListener(AFTER_COMMIT)`) +- [ ] Email templates (plain text, inline in the service or as `src/main/resources/templates/*.txt`) +- [ ] Unit tests (mock `JavaMailSender`, verify `MimeMessage` recipients) + +### Configuration notes + +- **Same async executor as `feature/token-management`** (`emailTaskExecutor` defined in `AsyncConfig`). +- **`NotificationProperties.adminEmail`** is supplied via `APP_NOTIFICATION_ADMIN_EMAIL` env var; added to `.env.example`. + +## feature/order-authorization + +Restricts order visibility and status mutation by role. + +### Endpoints + +| Method | URL | Description | +|---|---|---| +| GET | `/api/v1/orders` | ROLE_USER sees only their own orders; ROLE_ADMIN sees all | +| GET | `/api/v1/orders/{id}` | Returns 404 (not 403) if the order belongs to another user | +| PATCH | `/api/v1/orders/{id}/status` | Update order status (ROLE_ADMIN only) | + +### Tasks + +- [ ] `SecurityConfig` rules: `GET /api/v1/orders/**` → authenticated; ownership enforced in service +- [ ] `OrderService.findAll(UserDetails, Pageable)` and `findById(Long, UserDetails)`: admin bypasses ownership check, user gets 404 on others' orders +- [ ] `PATCH /api/v1/orders/{id}/status` → `@PreAuthorize("hasRole('ADMIN')")`, body `OrderStatusUpdateRequest` with `@NotNull OrderStatus status` +- [ ] `OrderStatusUpdateRequest` DTO +- [ ] `@SpringBootTest` authorization tests: user isolation, admin override, status update access + +### Configuration notes + +- **404 instead of 403 on ownership mismatch**: returning 403 leaks the existence of the resource; a consistent 404 is safer. +- **Status transitions are not validated** (any admin can set any status): validation logic can be added later without breaking the API. + +## feature/integration + +Final integration branch: merges `feature/product-images` into the main chain and validates the complete e-commerce flow end-to-end. + +### Tasks + +- [ ] Merge `feature/product-images` (resolve conflicts on `ProductResponse`, `ProductController`, `application.yml`) +- [ ] `EcommerceIntegrationTest` (`@SpringBootTest` + Testcontainers): register, login, browse catalogue, upload image (admin), add items to cart, checkout, verify order, admin status update, user isolation (user A cannot see user B's order) +- [ ] `docker-compose.yml` updated: volume `./uploads:/app/uploads`, env vars `APP_STORAGE_UPLOAD_DIR`, `APP_NOTIFICATION_ADMIN_EMAIL` +- [ ] `.env.example` updated with all new variables +- [ ] README updated with the full e-commerce endpoint table and configuration instructions + +### Configuration notes + +- **This is the only PR to `develop`** for the entire e-commerce extension chain (phases 3–8); the intermediate branches (`shopping-cart` through `order-authorization`) are merged feature-to-feature. +- **`feature/product-images` is the only side branch** and is merged here rather than through the main chain. From 430b8e33ebac9fe31ea116fe404a25d36ebc6c01 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:15:39 +0400 Subject: [PATCH 025/175] fix(test): update DataSeederTest after removing resetUserPasswords parameter seedDemoData() no longer takes a boolean argument. Both test call sites updated to match the new no-arg signature. --- .../edgareldy/springboottutorial/config/DataSeederTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java b/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java index 1778d8a..272bbed 100644 --- a/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java @@ -44,7 +44,7 @@ void _01_ShouldSeedCategoriesAndProducts_WhenDatabaseIsEmpty() throws Exception .thenReturn(Category.builder().id(1L).categoryName("Electronics").build()) .thenReturn(Category.builder().id(2L).categoryName("Books").build()); - dataSeeder.seedDemoData(false).run(); + dataSeeder.seedDemoData().run(); verify(categoryRepository, times(2)).save(any(Category.class)); verify(productRepository, times(3)).save(any(Product.class)); @@ -54,7 +54,7 @@ void _01_ShouldSeedCategoriesAndProducts_WhenDatabaseIsEmpty() throws Exception void _02_ShouldSkipSeeding_WhenCategoriesAlreadyExist() throws Exception { when(categoryRepository.count()).thenReturn(1L); - dataSeeder.seedDemoData(false).run(); + dataSeeder.seedDemoData().run(); verify(categoryRepository, never()).save(any()); verify(productRepository, never()).save(any()); From 5afa1572e27201e967cd5ede40d4f88cef3f6937 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:56:46 +0400 Subject: [PATCH 026/175] feat(flyway): add V14 migration for multi-product orders, status and nullable FK columns V14 evolves the orders schema in three steps. First, four columns are added to orders: user_id (nullable FK to app_users, reserved for a future checkout flow), order_number (VARCHAR 50 UNIQUE, human-readable UID), status (VARCHAR 20 NOT NULL DEFAULT 'PENDING'), and total_amount (NUMERIC(12,2) replacing the legacy DOUBLE PRECISION total column). Second, a new order_items table captures product snapshots per order line: product_name and unit_price are denormalized at creation time so the order history stays accurate even after a product is renamed or repriced; product_id uses ON DELETE SET NULL to preserve history if the product is removed. Third, existing rows are backfilled: each legacy order gets one OrderItem reconstructed from its joined product, total_amount is set from the legacy total column, and order_number is set to 'ORD-HIST-000NNN'. --- .../migration/V14__evolve_orders_domain.sql | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/resources/db/migration/V14__evolve_orders_domain.sql diff --git a/src/main/resources/db/migration/V14__evolve_orders_domain.sql b/src/main/resources/db/migration/V14__evolve_orders_domain.sql new file mode 100644 index 0000000..3cf2f91 --- /dev/null +++ b/src/main/resources/db/migration/V14__evolve_orders_domain.sql @@ -0,0 +1,51 @@ +-- Evolve the orders domain for e-commerce: multi-line items, status lifecycle, +-- BigDecimal amounts and unique order numbers. customer_id/product_id are made +-- nullable so that future checkout-created orders can reference AppUser instead. + +-- 1. Add e-commerce columns to orders +ALTER TABLE orders + ADD COLUMN order_number VARCHAR(50) UNIQUE, + ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'PENDING', + ADD COLUMN total_amount NUMERIC(12,2); + +-- 2. Make customer_id and product_id nullable for forward compatibility +-- (checkout orders will own the customer link via user_id, added in a later migration) +ALTER TABLE orders ALTER COLUMN customer_id DROP NOT NULL; +ALTER TABLE orders ALTER COLUMN product_id DROP NOT NULL; + +-- 3. Create order_items table (product snapshot: name and price at order time) +CREATE TABLE order_items ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES orders(id), + product_id BIGINT REFERENCES products(id) ON DELETE SET NULL, + product_name VARCHAR(255) NOT NULL, + unit_price NUMERIC(12,2) NOT NULL, + quantity INT NOT NULL CHECK (quantity > 0), + subtotal NUMERIC(12,2) NOT NULL +); + +CREATE INDEX idx_order_items_order_id ON order_items(order_id); + +-- 4. Migrate historical orders: one OrderItem per existing order using the +-- current NUMERIC(12,2) product price (more accurate than the DOUBLE total column) +INSERT INTO order_items (order_id, product_id, product_name, unit_price, quantity, subtotal) +SELECT + o.id, + o.product_id, + p.product_name, + p.unit_price, + o.quantity, + ROUND(CAST(o.quantity AS NUMERIC) * p.unit_price, 2) +FROM orders o +JOIN products p ON p.id = o.product_id; + +-- 5. Backfill total_amount from quantity * current product price +UPDATE orders o +SET total_amount = ( + SELECT ROUND(CAST(o.quantity AS NUMERIC) * p.unit_price, 2) + FROM products p WHERE p.id = o.product_id +) +WHERE o.product_id IS NOT NULL; + +-- 6. Backfill order_number for historical orders +UPDATE orders SET order_number = 'ORD-HIST-' || LPAD(id::TEXT, 6, '0'); From b24e987fa38452fd7ad9490f107dbe5a2d603532 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:57:03 +0400 Subject: [PATCH 027/175] feat(entity): add OrderStatus enum with PENDING, CONFIRMED, CANCELLED values --- .../springboottutorial/entity/OrderStatus.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/entity/OrderStatus.java diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/OrderStatus.java b/src/main/java/com/edgareldy/springboottutorial/entity/OrderStatus.java new file mode 100644 index 0000000..18a770b --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/entity/OrderStatus.java @@ -0,0 +1,18 @@ +package com.edgareldy.springboottutorial.entity; + +/** + * Lifecycle statuses for an e-commerce order. + * PENDING - created by checkout, awaiting admin confirmation. + * CONFIRMED - confirmed by an administrator. + * CANCELLED - cancelled by admin or system. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +public enum OrderStatus { + PENDING, + CONFIRMED, + CANCELLED +} From ff134cbac766a767e36f1353cec974e569d872df Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:57:15 +0400 Subject: [PATCH 028/175] feat(entity): add OrderItem entity with product snapshot (name, unit price, subtotal) OrderItem maps the order_items table introduced in V14. The snapshot pattern is key: productName and unitPrice are copied from Product at creation time and never updated, so the order history remains accurate even after the product is renamed or repriced. The product FK is nullable to support ON DELETE SET NULL: removing a product sets product_id to NULL without destroying historical line data. subtotal is stored (not derived) to avoid any floating-point drift on retrieval. --- .../springboottutorial/entity/OrderItem.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/entity/OrderItem.java diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/OrderItem.java b/src/main/java/com/edgareldy/springboottutorial/entity/OrderItem.java new file mode 100644 index 0000000..4417c5b --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/entity/OrderItem.java @@ -0,0 +1,64 @@ +package com.edgareldy.springboottutorial.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; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * JPA entity mapping the {@code order_items} table. Each row is a product + * snapshot captured at the time of order creation: {@code productName} and + * {@code unitPrice} reflect the product at that instant, so they are + * independent of any subsequent product update. {@code product} is kept as + * a nullable FK to allow ON DELETE SET NULL when a product is removed without + * losing the order history. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@Entity +@Table(name = "order_items") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class OrderItem { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "order_id", nullable = false) + private Order order; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "product_id") + private Product product; + + @Column(name = "product_name", nullable = false) + private String productName; + + @Column(name = "unit_price", nullable = false, precision = 12, scale = 2) + private BigDecimal unitPrice; + + @Column(nullable = false) + private int quantity; + + @Column(nullable = false, precision = 12, scale = 2) + private BigDecimal subtotal; +} From 02eea47a12cf0f84edc2132f159206260301512c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:57:32 +0400 Subject: [PATCH 029/175] feat(entity): evolve Order for e-commerce - add totalAmount, orderNumber, status, items Order gains four new mapped fields: totalAmount (BigDecimal, NUMERIC 12,2), orderNumber (VARCHAR 50 unique), status (@Enumerated(STRING), defaults to PENDING via @Builder.Default), and items (@OneToMany cascade ALL with orphanRemoval, the authoritative multi-line breakdown). The legacy customer and product FK mappings are kept and their @JoinColumn constraints are relaxed to nullable so existing CRUD flows continue to compile and pre-V14 rows survive the migration without both FK columns set. --- .../springboottutorial/entity/Order.java | 38 +++++++++++++++---- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/Order.java b/src/main/java/com/edgareldy/springboottutorial/entity/Order.java index bdee7f5..4c721a8 100644 --- a/src/main/java/com/edgareldy/springboottutorial/entity/Order.java +++ b/src/main/java/com/edgareldy/springboottutorial/entity/Order.java @@ -1,14 +1,21 @@ package com.edgareldy.springboottutorial.entity; +import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; 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.OneToMany; import jakarta.persistence.Table; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -16,10 +23,13 @@ import lombok.Setter; /** - * JPA entity mapping the {@code orders} table. Each order references - * exactly one {@link Customer} and one {@link Product}, both loaded - * lazily. {@code total} is not client-supplied: the service layer always - * computes it as {@code quantity * product.unitPrice}. + * JPA entity mapping the {@code orders} table. {@code customer} and + * {@code product} are kept for backward compatibility with the legacy CRUD + * flow and are now nullable (future checkout-created orders use {@code items} + * and a user reference instead). {@code totalAmount} stores the order total as + * NUMERIC(12,2); the old {@code total DOUBLE PRECISION} column is kept in the + * database schema but is no longer mapped here. {@code items} is the + * authoritative multi-line breakdown of what was ordered. *

* Created edgar.muhamyangabo on 7/8/26 * Author : edgar.muhamyangabo @@ -40,16 +50,28 @@ public class Order { private Long id; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "customer_id", nullable = false) + @JoinColumn(name = "customer_id") private Customer customer; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "product_id", nullable = false) + @JoinColumn(name = "product_id") private Product product; @Column(nullable = false) private int quantity; - @Column(nullable = false) - private double total; + @Column(name = "total_amount", precision = 12, scale = 2) + private BigDecimal totalAmount; + + @Column(name = "order_number", length = 50, unique = true) + private String orderNumber; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 20) + @Builder.Default + private OrderStatus status = OrderStatus.PENDING; + + @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List items = new ArrayList<>(); } From 3d97e2bf6c99be2748b40effc54823a892449113 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:57:42 +0400 Subject: [PATCH 030/175] feat(dto): add OrderItemResponse with product snapshot fields --- .../dto/order/OrderItemResponse.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/order/OrderItemResponse.java diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderItemResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderItemResponse.java new file mode 100644 index 0000000..5878242 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderItemResponse.java @@ -0,0 +1,33 @@ +package com.edgareldy.springboottutorial.dto.order; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; + +/** + * Representation of a single {@link com.edgareldy.springboottutorial.entity.OrderItem} + * returned by the API. Carries the product snapshot (name and unit price at order + * time) so callers see what was actually charged, independent of any subsequent + * product update. The JSON contract uses snake_case via {@link JsonProperty}. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +public record OrderItemResponse( + Long id, + + @JsonProperty("product_id") + Long productId, + + @JsonProperty("product_name") + String productName, + + @JsonProperty("unit_price") + BigDecimal unitPrice, + + int quantity, + + BigDecimal subtotal +) { +} From 16d60183b5817d34d235693d1ff4756f5dcd6845 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:58:09 +0400 Subject: [PATCH 031/175] refactor(dto): add status, total_amount, order_number and items to OrderResponse OrderResponse surfaces the new Order fields to API consumers: status as a plain String (the enum name), total_amount and order_number with @JsonProperty snake_case names to follow the project convention, and items as a List. items is populated on findById (via JOIN FETCH, so no N+1) and on create/update; the findAll projection path keeps items empty to avoid loading all order lines for every row in a paginated list. --- .../dto/order/OrderResponse.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderResponse.java index 2d6e839..9c31b48 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderResponse.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderResponse.java @@ -1,14 +1,17 @@ package com.edgareldy.springboottutorial.dto.order; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; +import java.util.List; /** * Representation of a single * {@link com.edgareldy.springboottutorial.entity.Order} returned by the API * (detail, create, update, and the per-customer order list). Carries the - * customer's contact details and the full {@link ProductResponse}, so a - * caller never has to make a second request just to get the customer's - * address or the product's category. The grouped view of + * customer's contact details and the full {@link ProductResponse} for backward + * compatibility, plus the multi-line {@code items} breakdown and the + * {@code totalAmount} computed by the service. The grouped view of * {@code GET /api/v1/orders} uses {@link CustomerOrdersResponse} instead. *

* Created edgar.muhamyangabo on 7/8/26 @@ -21,6 +24,15 @@ public record OrderResponse( OrderCustomerResponse customer, ProductResponse product, int quantity, - double total + + @JsonProperty("order_number") + String orderNumber, + + String status, + + @JsonProperty("total_amount") + BigDecimal totalAmount, + + List items ) { } From d5ea00198f8c831639d39222292f73f71b9c6fb7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:58:20 +0400 Subject: [PATCH 032/175] refactor(dto): migrate OrderedProductResponse unitPrice and total to BigDecimal --- .../springboottutorial/dto/order/OrderedProductResponse.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderedProductResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderedProductResponse.java index 35c046b..bc305c5 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderedProductResponse.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderedProductResponse.java @@ -1,6 +1,7 @@ package com.edgareldy.springboottutorial.dto.order; import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; /** * One order of a customer, seen as "a product they ordered": the product, @@ -20,8 +21,8 @@ public record OrderedProductResponse( @JsonProperty("product_name") String productName, @JsonProperty("unit_price") - float unitPrice, + BigDecimal unitPrice, int quantity, - double total + BigDecimal total ) { } From 0029240cb3014272127e8ba31ce366b935972aad Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:58:40 +0400 Subject: [PATCH 033/175] refactor(dto): migrate CustomerOrdersResponse total to BigDecimal --- .../springboottutorial/dto/order/CustomerOrdersResponse.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/order/CustomerOrdersResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/order/CustomerOrdersResponse.java index 558f044..3f3dace 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/order/CustomerOrdersResponse.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/order/CustomerOrdersResponse.java @@ -1,5 +1,6 @@ package com.edgareldy.springboottutorial.dto.order; +import java.math.BigDecimal; import java.util.List; /** @@ -15,6 +16,6 @@ public record CustomerOrdersResponse( OrderCustomerResponse customer, List products, - double total + BigDecimal total ) { } From bca8092cb6ae0e2d178a8e7cca1e44ff9760cd37 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:58:40 +0400 Subject: [PATCH 034/175] refactor(dto): migrate CustomerResponse total to BigDecimal --- .../springboottutorial/dto/customer/CustomerResponse.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/customer/CustomerResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/customer/CustomerResponse.java index 27c5e7c..3cb721d 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/customer/CustomerResponse.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/customer/CustomerResponse.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; +import java.math.BigDecimal; import java.util.List; /** @@ -32,6 +33,6 @@ public record CustomerResponse( String email, String address, List products, - double total + BigDecimal total ) { } From 46dd1f8ce2ca7e31211c30719946a2a6b686a78d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:58:55 +0400 Subject: [PATCH 035/175] refactor(repository): migrate OrderProjection to BigDecimal, add status and orderNumber fields OrderProjection is a JPQL constructor projection used by the findAll paginated endpoint to avoid loading full Order entities with their lazy associations. It gains totalAmount (BigDecimal), orderNumber and status to let the mapper build a complete OrderResponse without a second query. Using a flat projection rather than an entity ensures that customer, product and items relations are never triggered for every row in the page. --- .../repository/OrderProjection.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java index cbaf334..e8bfbc2 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java @@ -1,5 +1,7 @@ package com.edgareldy.springboottutorial.repository; +import java.math.BigDecimal; + /** * Flat DTO projection selected directly by a JPQL constructor expression in * {@link OrderRepository#findAllProjected}, so listing orders never loads @@ -8,7 +10,8 @@ * (used for the single-item detail view), this technique lets the database * return exactly the columns the list endpoint needs, carrying every field * required to build the full {@code CustomerResponse}/{@code ProductResponse} - * nested inside an {@code OrderResponse}. + * nested inside an {@code OrderResponse}. {@code productActive} is included + * so the list view reflects the product's current active state accurately. *

* Created edgar.muhamyangabo on 7/8/26 * Author : edgar.muhamyangabo @@ -25,10 +28,13 @@ public record OrderProjection( String customerAddress, Long productId, String productName, - float productUnitPrice, + BigDecimal productUnitPrice, + boolean productActive, Long productCategoryId, String productCategoryName, int quantity, - double total + BigDecimal totalAmount, + String status, + String orderNumber ) { } From cd280b833a577a00c7f4800caf3fbc806fe19952 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:59:04 +0400 Subject: [PATCH 036/175] feat(mapper): add OrderItemMapper converting OrderItem to OrderItemResponse --- .../mapper/OrderItemMapper.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/mapper/OrderItemMapper.java diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderItemMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderItemMapper.java new file mode 100644 index 0000000..755270a --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderItemMapper.java @@ -0,0 +1,24 @@ +package com.edgareldy.springboottutorial.mapper; + +import com.edgareldy.springboottutorial.dto.order.OrderItemResponse; +import com.edgareldy.springboottutorial.entity.OrderItem; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +/** + * MapStruct mapper converting {@link OrderItem} entities to + * {@link OrderItemResponse} DTOs. The {@code productId} is sourced from the + * nullable {@code product.id} association; when the product has been deleted + * (ON DELETE SET NULL), it maps to {@code null}. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@Mapper(componentModel = "spring") +public interface OrderItemMapper { + + @Mapping(target = "productId", source = "product.id") + OrderItemResponse toResponse(OrderItem orderItem); +} From e5d2ef9515a95ba5f2d7a6a3a96ea938038e09ec Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:59:13 +0400 Subject: [PATCH 037/175] refactor(mapper): migrate CustomerMapper total parameter and default value to BigDecimal --- .../edgareldy/springboottutorial/mapper/CustomerMapper.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java index 21aa1ce..e8ca5c9 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java @@ -28,12 +28,13 @@ public interface CustomerMapper { @Mapping(target = "products", expression = "java(java.util.List.of())") - @Mapping(target = "total", constant = "0.0") + @Mapping(target = "total", expression = "java(java.math.BigDecimal.ZERO)") CustomerResponse toResponse(Customer customer); @Mapping(target = "products", source = "products") @Mapping(target = "total", source = "total") - CustomerResponse toResponseWithOrders(Customer customer, List products, double total); + CustomerResponse toResponseWithOrders(Customer customer, List products, + java.math.BigDecimal total); @Mapping(target = "id", ignore = true) Customer toEntity(CustomerRequest request); From f3b82e984294bfb3b6706b773069b4678e458b23 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 12:59:34 +0400 Subject: [PATCH 038/175] refactor(mapper): rewrite OrderMapper for BigDecimal, OrderItem mapping and new OrderResponse fields OrderMapper gains two toResponse overloads. The entity overload (used on findById, create, update) maps Order.items via OrderItemMapper and builds full CustomerResponse and ProductResponse DTOs from the loaded JPA associations. The projection overload (used on findAll) constructs the same OrderResponse from the flat OrderProjection, assembling nested DTOs from the prefixed projection fields without triggering any lazy load. toCustomerOrdersResponse groups a Customer with its flat list of OrderProjection rows and a pre-computed BigDecimal total. --- .../mapper/OrderMapper.java | 106 ++++++++---------- 1 file changed, 44 insertions(+), 62 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java index 3e60509..1ef6a3f 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java @@ -2,40 +2,37 @@ import com.edgareldy.springboottutorial.dto.order.CustomerOrdersResponse; import com.edgareldy.springboottutorial.dto.order.OrderCustomerResponse; -import com.edgareldy.springboottutorial.dto.order.OrderRequest; import com.edgareldy.springboottutorial.dto.order.OrderResponse; import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; import com.edgareldy.springboottutorial.dto.product.ProductResponse; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.entity.Order; -import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.repository.OrderProjection; +import java.math.BigDecimal; import java.util.List; import org.mapstruct.Mapper; import org.mapstruct.Mapping; -import org.mapstruct.MappingTarget; /** * MapStruct mapper converting between {@link Order} and its DTOs. Two - * {@code toResponse} overloads exist because the service builds an - * {@link OrderResponse} from two different sources: a full {@link Order} - * entity (single-item detail, via {@code findByIdWithDetails}, where - * {@code customer} goes through {@link #toCustomerResponse(Customer)} and - * {@code product} through {@code ProductMapper}) or a flat - * {@link OrderProjection} row (paginated lists, via - * {@code findAllProjected}, built manually since there is no - * {@code Customer}/{@code Product} entity to delegate to). + * {@code toResponse} overloads handle the two read paths: a full {@link Order} + * entity (single-item detail, via {@code findByIdWithDetails}) and a flat + * {@link OrderProjection} row (paginated lists, via {@code findAllProjected}). + * {@link OrderItemMapper} is included via {@code uses} so MapStruct can + * auto-map {@code Order.items} to {@code List}. * {@link #toCustomerOrdersResponse} builds the grouped view of - * {@code GET /api/v1/orders}. + * {@code GET /api/v1/orders}, and {@link #toOrderedProducts} assembles the + * per-order lines used in both the grouped view and customer detail responses. *

* Created edgar.muhamyangabo on 7/8/26 * Author : edgar.muhamyangabo * Date : 7/8/26 * Project : spring-boot-tutorial */ -@Mapper(componentModel = "spring", uses = ProductMapper.class) +@Mapper(componentModel = "spring", uses = {ProductMapper.class, OrderItemMapper.class}) public interface OrderMapper { + @Mapping(target = "status", expression = "java(order.getStatus().name())") OrderResponse toResponse(Order order); OrderCustomerResponse toCustomerResponse(Customer customer); @@ -45,66 +42,51 @@ public interface OrderMapper { * {@code total} is computed by the service, the mapper only assigns it. */ default CustomerOrdersResponse toCustomerOrdersResponse( - Customer customer, List orders, double total) { + Customer customer, List orders, BigDecimal total) { return new CustomerOrdersResponse(toCustomerResponse(customer), toOrderedProducts(orders), total); } /** - * Turns order rows into "ordered product" lines, one per order. Shared by - * the grouped order view and by the customer responses. + * Turns order projection rows into ordered-product lines. Each row maps + * to one order placed by the customer. Used in the grouped order view and + * in customer detail responses. */ default List toOrderedProducts(List orders) { return orders.stream() - .map(order -> new OrderedProductResponse( - order.id(), - order.productId(), - order.productName(), - order.productUnitPrice(), - order.quantity(), - order.total())) + .map(o -> new OrderedProductResponse( + o.id(), + o.productId(), + o.productName(), + o.productUnitPrice(), + o.quantity(), + o.totalAmount())) .toList(); } - default OrderResponse toResponse(OrderProjection projection) { + /** + * Builds an {@link OrderResponse} from a flat projection row (list path). + * {@code description} is not included in the projection and maps to + * {@code null}; {@code active} is sourced from {@code p.active} in the + * JPQL query. + */ + default OrderResponse toResponse(OrderProjection p) { OrderCustomerResponse customer = new OrderCustomerResponse( - projection.customerId(), - projection.customerFirstName(), - projection.customerLastName(), - projection.customerTelephone(), - projection.customerEmail(), - projection.customerAddress()); + p.customerId(), + p.customerFirstName(), + p.customerLastName(), + p.customerTelephone(), + p.customerEmail(), + p.customerAddress()); ProductResponse product = new ProductResponse( - projection.productId(), - projection.productName(), - projection.productUnitPrice(), - projection.productCategoryId(), - projection.productCategoryName()); - return new OrderResponse(projection.id(), customer, product, projection.quantity(), projection.total()); + p.productId(), + p.productName(), + p.productUnitPrice(), + null, + p.productActive(), + p.productCategoryId(), + p.productCategoryName()); + return new OrderResponse( + p.id(), customer, product, p.quantity(), + p.orderNumber(), p.status(), p.totalAmount(), List.of()); } - - /** - * Builds a new {@link Order} from the request plus the already resolved - * {@code customer} and {@code product}, and the {@code total} the service - * computed. The mapper only assigns these values: looking the associations - * up and computing the total are business decisions that stay in the - * service. - */ - @Mapping(target = "id", ignore = true) - @Mapping(target = "customer", source = "customer") - @Mapping(target = "product", source = "product") - @Mapping(target = "quantity", source = "request.quantity") - @Mapping(target = "total", source = "total") - Order toEntity(OrderRequest request, Customer customer, Product product, double total); - - /** - * Applies the same values onto an existing {@link Order}, keeping its - * identity. - */ - @Mapping(target = "id", ignore = true) - @Mapping(target = "customer", source = "customer") - @Mapping(target = "product", source = "product") - @Mapping(target = "quantity", source = "request.quantity") - @Mapping(target = "total", source = "total") - void updateEntity(OrderRequest request, Customer customer, Product product, double total, - @MappingTarget Order order); } From 8a7b255ab85fea124b23f6d7c1a0fa08ac49ac75 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:01:58 +0400 Subject: [PATCH 039/175] refactor(repository): update OrderRepository JPQL for new projection fields and fetch items findAllProjected is extended with totalAmount, orderNumber and status to match the enriched OrderProjection constructor. findByIdWithDetails adds JOIN FETCH items so the returned Order always includes its lines in a single query, avoiding the N+1 that would otherwise occur when the mapper iterates order.getItems(). findCustomersWithOrders and findAllProjectedByCustomerIds support the grouped-by-customer endpoint: the first paginates the distinct customers who have at least one order, the second loads all their order rows in a single IN-query so the service layer groups them in memory without per-customer round trips. --- .../repository/OrderRepository.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java index b2fb84a..157c1d6 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java @@ -23,8 +23,8 @@ public interface OrderRepository extends JpaRepository { @Query("SELECT new com.edgareldy.springboottutorial.repository.OrderProjection(" + "o.id, " + "c.id, c.firstName, c.lastName, c.telephone, c.email, c.address, " - + "p.id, p.productName, p.unitPrice, cat.id, cat.categoryName, " - + "o.quantity, o.total) " + + "p.id, p.productName, p.unitPrice, p.active, cat.id, cat.categoryName, " + + "o.quantity, o.totalAmount, o.status, o.orderNumber) " + "FROM Order o JOIN o.customer c JOIN o.product p JOIN p.category cat " + "WHERE (:customerId IS NULL OR c.id = :customerId) " + "AND (:productId IS NULL OR p.id = :productId)") @@ -47,14 +47,13 @@ Page findCustomersWithOrders(@Param("customerId") Long customerId, /** * Loads, in a single query, every order row of the given customers (the - * ones of the current page), so grouping never costs one query per - * customer. + * ones of the current page), so grouping never costs one query per customer. */ @Query("SELECT new com.edgareldy.springboottutorial.repository.OrderProjection(" + "o.id, " + "c.id, c.firstName, c.lastName, c.telephone, c.email, c.address, " - + "p.id, p.productName, p.unitPrice, cat.id, cat.categoryName, " - + "o.quantity, o.total) " + + "p.id, p.productName, p.unitPrice, p.active, cat.id, cat.categoryName, " + + "o.quantity, o.totalAmount, o.status, o.orderNumber) " + "FROM Order o JOIN o.customer c JOIN o.product p JOIN p.category cat " + "WHERE c.id IN :customerIds " + "AND (:productId IS NULL OR p.id = :productId) " @@ -62,9 +61,15 @@ Page findCustomersWithOrders(@Param("customerId") Long customerId, List findAllProjectedByCustomerIds(@Param("customerIds") List customerIds, @Param("productId") Long productId); - @Query("SELECT o FROM Order o JOIN FETCH o.customer JOIN FETCH o.product p JOIN FETCH p.category WHERE o.id = :id") + @Query("SELECT o FROM Order o " + + "JOIN FETCH o.customer " + + "JOIN FETCH o.product p JOIN FETCH p.category " + + "LEFT JOIN FETCH o.items i LEFT JOIN FETCH i.product " + + "WHERE o.id = :id") Optional findByIdWithDetails(@Param("id") Long id); + Page findByCustomerId(Long customerId, Pageable pageable); + boolean existsByCustomerId(Long customerId); boolean existsByProductId(Long productId); From 0402078ff077d32d6a7874a257c863856a2f6aad Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:03:31 +0400 Subject: [PATCH 040/175] refactor(event): enrich OrderCreatedEvent with BigDecimal totalAmount and orderNumber OrderCreatedEvent gains totalAmount (BigDecimal, replacing the legacy double total) and orderNumber so downstream listeners have enough context to build a human-readable order confirmation without an extra DB query. Switching from double to BigDecimal aligns with the rest of the domain model and avoids floating-point imprecision when the amount is later formatted or accumulated. --- .../springboottutorial/event/OrderCreatedEvent.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEvent.java b/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEvent.java index 3cc70e7..dd4ee0e 100644 --- a/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEvent.java +++ b/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEvent.java @@ -1,5 +1,7 @@ package com.edgareldy.springboottutorial.event; +import java.math.BigDecimal; + /** * Application event published by {@code OrderServiceImpl} once a new order * has been persisted. A plain record, not a subclass of @@ -18,6 +20,7 @@ public record OrderCreatedEvent( Long customerId, Long productId, int quantity, - double total + BigDecimal totalAmount, + String orderNumber ) { } From aa81f5eba689574b3ed6ea49fffecf6402521c38 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:03:34 +0400 Subject: [PATCH 041/175] refactor(service): rewrite OrderServiceImpl with BigDecimal totals, orderNumber and OrderItem cascade create() and update() now build an OrderItem from the Product snapshot (productName and unitPrice at call time), compute totalAmount with BigDecimal.multiply to avoid floating-point drift, and generate a UUID-based orderNumber. The OrderItem is wired to the Order before save() so the bidirectional link is consistent when Hibernate flushes the transaction. delete() uses existsById rather than findById to avoid loading the entity solely to delete it. findById delegates to findByIdWithDetails so the returned OrderResponse always includes the items list in a single query. --- .../service/impl/OrderServiceImpl.java | 62 ++++++++++++++++--- 1 file changed, 53 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java index b1532fb..e858940 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java @@ -6,6 +6,8 @@ import com.edgareldy.springboottutorial.dto.order.OrderResponse; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderItem; +import com.edgareldy.springboottutorial.entity.OrderStatus; import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.event.OrderCreatedEvent; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; @@ -15,8 +17,11 @@ import com.edgareldy.springboottutorial.repository.OrderRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import com.edgareldy.springboottutorial.service.OrderService; +import java.math.BigDecimal; +import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.springframework.context.ApplicationEventPublisher; @@ -61,9 +66,10 @@ public PageResponse findAllGroupedByCustomer( .collect(Collectors.groupingBy(OrderProjection::customerId)); return PageResponse.from(customers.map(customer -> { List orders = ordersByCustomer.getOrDefault(customer.getId(), List.of()); - double total = orders.stream().mapToDouble(OrderProjection::total).sum(); - // Rounded to cents: summing doubles can leave noise such as 3949.9700000000003. - return orderMapper.toCustomerOrdersResponse(customer, orders, Math.round(total * 100) / 100.0); + BigDecimal total = orders.stream() + .map(OrderProjection::totalAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + return orderMapper.toCustomerOrdersResponse(customer, orders, total); })); } @@ -79,22 +85,60 @@ public OrderResponse findById(Long id) { public OrderResponse create(OrderRequest request) { Customer customer = getCustomerOrThrow(request.customerId()); Product product = getProductOrThrow(request.productId()); - double total = request.quantity() * product.getUnitPrice(); - Order saved = orderRepository.save(orderMapper.toEntity(request, customer, product, total)); + BigDecimal subtotal = product.getUnitPrice().multiply(BigDecimal.valueOf(request.quantity())); + String orderNumber = "ORD-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase(); + + OrderItem item = OrderItem.builder() + .product(product) + .productName(product.getProductName()) + .unitPrice(product.getUnitPrice()) + .quantity(request.quantity()) + .subtotal(subtotal) + .build(); + + Order order = Order.builder() + .customer(customer) + .product(product) + .quantity(request.quantity()) + .totalAmount(subtotal) + .orderNumber(orderNumber) + .status(OrderStatus.PENDING) + .items(new ArrayList<>(List.of(item))) + .build(); + item.setOrder(order); + + Order saved = orderRepository.save(order); eventPublisher.publishEvent(new OrderCreatedEvent( - saved.getId(), customer.getId(), product.getId(), saved.getQuantity(), saved.getTotal())); + saved.getId(), customer.getId(), product.getId(), + saved.getQuantity(), saved.getTotalAmount(), saved.getOrderNumber())); return orderMapper.toResponse(saved); } @Override @Transactional public OrderResponse update(Long id, OrderRequest request) { - Order order = orderRepository.findById(id) + Order order = orderRepository.findByIdWithDetails(id) .orElseThrow(() -> new ResourceNotFoundException("Order not found with id " + id)); Customer customer = getCustomerOrThrow(request.customerId()); Product product = getProductOrThrow(request.productId()); - double total = request.quantity() * product.getUnitPrice(); - orderMapper.updateEntity(request, customer, product, total, order); + BigDecimal subtotal = product.getUnitPrice().multiply(BigDecimal.valueOf(request.quantity())); + + OrderItem item = OrderItem.builder() + .product(product) + .productName(product.getProductName()) + .unitPrice(product.getUnitPrice()) + .quantity(request.quantity()) + .subtotal(subtotal) + .build(); + + order.setCustomer(customer); + order.setProduct(product); + order.setQuantity(request.quantity()); + order.setTotalAmount(subtotal); + order.getItems().clear(); + order.getItems().add(item); + item.setOrder(order); + return orderMapper.toResponse(orderRepository.save(order)); } From 224e9669b1bd5a2a8ce2cb320610f62d75c25a0c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:03:38 +0400 Subject: [PATCH 042/175] refactor(service): migrate CustomerServiceImpl total computation to BigDecimal --- .../service/impl/CustomerServiceImpl.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImpl.java index 833bd3d..cd84e22 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImpl.java @@ -12,6 +12,7 @@ import com.edgareldy.springboottutorial.repository.OrderProjection; import com.edgareldy.springboottutorial.repository.OrderRepository; import com.edgareldy.springboottutorial.service.CustomerService; +import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -107,10 +108,10 @@ private CustomerResponse toResponseWithOrders(Customer customer) { } private CustomerResponse toResponseWithOrders(Customer customer, List orders) { - double total = orders.stream().mapToDouble(OrderProjection::total).sum(); - // Rounded to cents: summing doubles can leave noise such as 3949.9700000000003. - return customerMapper.toResponseWithOrders( - customer, orderMapper.toOrderedProducts(orders), Math.round(total * 100) / 100.0); + BigDecimal total = orders.stream() + .map(OrderProjection::totalAmount) + .reduce(BigDecimal.ZERO, BigDecimal::add); + return customerMapper.toResponseWithOrders(customer, orderMapper.toOrderedProducts(orders), total); } private Customer getCustomerOrThrow(Long id) { From 8a86e47b67ab14728b034c5cff83d357145607b2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:08:43 +0400 Subject: [PATCH 043/175] test(service): rewrite OrderServiceImplTest for BigDecimal, OrderItem and new event fields create() tests verify the OrderItem snapshot fields (productName, unitPrice, quantity, subtotal via BigDecimal.multiply), the UUID-based orderNumber, and the event payload (totalAmount, orderNumber). update() tests verify that the items list is replaced (not appended) and that totalAmount is recomputed from the new product price. findAll and findAllGroupedByCustomer stub the projection and customer-list paths. 404 cases cover missing customer and missing product on both create and update. --- .../service/impl/OrderServiceImplTest.java | 81 +++++++++++++------ 1 file changed, 56 insertions(+), 25 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 83d2f13..5171510 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -16,6 +16,7 @@ import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderStatus; import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.event.OrderCreatedEvent; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; @@ -24,6 +25,7 @@ import com.edgareldy.springboottutorial.repository.OrderProjection; import com.edgareldy.springboottutorial.repository.OrderRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; +import java.math.BigDecimal; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; @@ -79,12 +81,17 @@ void setUp() { customer = Customer.builder().id(1L).firstName("Ada").lastName("Lovelace") .telephone("+1 202-555-0100").email("ada@example.com").address("1 Analytical Engine Way").build(); Category category = Category.builder().id(1L).categoryName("Electronics").build(); - product = Product.builder().id(1L).category(category).productName("Keyboard").unitPrice(50.0f).build(); - order = Order.builder().id(1L).customer(customer).product(product).quantity(2).total(100.0).build(); + product = Product.builder().id(1L).category(category).productName("Keyboard") + .unitPrice(new BigDecimal("50.00")).build(); + order = Order.builder().id(1L).customer(customer).product(product).quantity(2) + .totalAmount(new BigDecimal("100.00")).orderNumber("ORD-HIST-000001") + .status(OrderStatus.PENDING).build(); OrderCustomerResponse customerResponse = new OrderCustomerResponse( 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way"); - ProductResponse productResponse = new ProductResponse(1L, "Keyboard", 50.0f, 1L, "Electronics"); - orderResponse = new OrderResponse(1L, customerResponse, productResponse, 2, 100.0); + ProductResponse productResponse = new ProductResponse( + 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics"); + orderResponse = new OrderResponse(1L, customerResponse, productResponse, 2, + "ORD-HIST-000001", "PENDING", new BigDecimal("100.00"), List.of()); } @Test @@ -92,7 +99,8 @@ void _01_ShouldDelegateToProjectedQuery_WhenListingOrders() { Pageable pageable = PageRequest.of(0, 10); OrderProjection projection = new OrderProjection( 1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 1L, "Keyboard", 50.0f, 1L, "Electronics", 2, 100.0); + 1L, "Keyboard", new BigDecimal("50.00"), true, 1L, "Electronics", + 2, new BigDecimal("100.00"), "PENDING", "ORD-HIST-000001"); when(orderRepository.findAllProjected(null, null, pageable)) .thenReturn(new PageImpl<>(List.of(projection), pageable, 1)); when(orderMapper.toResponse(projection)).thenReturn(orderResponse); @@ -109,23 +117,26 @@ void _01b_ShouldGroupOrdersAndSumTotals_WhenListingByCustomer() { .telephone("+1 202-555-0101").email("grace@example.com").address("2 Compiler Street").build(); OrderProjection adaKeyboard = new OrderProjection( 1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 1L, "Keyboard", 19.99f, 1L, "Electronics", 1, 19.99); + 1L, "Keyboard", new BigDecimal("19.99"), true, 1L, "Electronics", + 1, new BigDecimal("19.99"), "PENDING", "ORD-TEST-001"); OrderProjection adaDesk = new OrderProjection( 2L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 2L, "Desk", 0.1f, 1L, "Electronics", 2, 0.2); + 2L, "Desk", new BigDecimal("0.10"), true, 1L, "Electronics", + 2, new BigDecimal("0.20"), "PENDING", "ORD-TEST-002"); OrderProjection graceDesk = new OrderProjection( 3L, 2L, "Grace", "Hopper", "+1 202-555-0101", "grace@example.com", "2 Compiler Street", - 2L, "Desk", 200.0f, 1L, "Electronics", 1, 200.0); - CustomerOrdersResponse adaEntry = new CustomerOrdersResponse(null, List.of(), 20.19); - CustomerOrdersResponse graceEntry = new CustomerOrdersResponse(null, List.of(), 200.0); + 2L, "Desk", new BigDecimal("200.00"), true, 1L, "Electronics", + 1, new BigDecimal("200.00"), "PENDING", "ORD-TEST-003"); + CustomerOrdersResponse adaEntry = new CustomerOrdersResponse(null, List.of(), new BigDecimal("20.19")); + CustomerOrdersResponse graceEntry = new CustomerOrdersResponse(null, List.of(), new BigDecimal("200.00")); when(orderRepository.findCustomersWithOrders(null, null, pageable)) .thenReturn(new PageImpl<>(List.of(customer, grace), pageable, 2)); when(orderRepository.findAllProjectedByCustomerIds(List.of(1L, 2L), null)) .thenReturn(List.of(adaKeyboard, adaDesk, graceDesk)); - // 19.99 + 0.2 is 20.189999999999998 in double arithmetic: the service must round it to 20.19. - when(orderMapper.toCustomerOrdersResponse(customer, List.of(adaKeyboard, adaDesk), 20.19)) + when(orderMapper.toCustomerOrdersResponse(customer, List.of(adaKeyboard, adaDesk), new BigDecimal("20.19"))) .thenReturn(adaEntry); - when(orderMapper.toCustomerOrdersResponse(grace, List.of(graceDesk), 200.0)).thenReturn(graceEntry); + when(orderMapper.toCustomerOrdersResponse(grace, List.of(graceDesk), new BigDecimal("200.00"))) + .thenReturn(graceEntry); PageResponse result = orderService.findAllGroupedByCustomer(null, null, pageable); @@ -162,22 +173,36 @@ void _03_ShouldThrowNotFound_WhenOrderMissing() { } @Test - void _04_ShouldComputeTotalAndPublishEvent_WhenCreatingOrder() { + void _04_ShouldBuildOrderItemAndPublishEvent_WhenCreatingOrder() { OrderRequest request = new OrderRequest(1L, 1L, 2); + Order savedOrder = Order.builder().id(1L).customer(customer).product(product).quantity(2) + .totalAmount(new BigDecimal("100.00")).orderNumber("ORD-ABCD1234") + .status(OrderStatus.PENDING).build(); when(customerRepository.findById(1L)).thenReturn(Optional.of(customer)); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); - when(orderMapper.toEntity(request, customer, product, 100.0)).thenReturn(order); - when(orderRepository.save(order)).thenReturn(order); - when(orderMapper.toResponse(order)).thenReturn(orderResponse); + when(orderRepository.save(any(Order.class))).thenReturn(savedOrder); + when(orderMapper.toResponse(savedOrder)).thenReturn(orderResponse); assertThat(orderService.create(request)).isEqualTo(orderResponse); - verify(orderMapper).toEntity(request, customer, product, 100.0); - verify(orderRepository).save(order); + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(Order.class); + verify(orderRepository).save(orderCaptor.capture()); + Order built = orderCaptor.getValue(); + assertThat(built.getCustomer()).isEqualTo(customer); + assertThat(built.getTotalAmount()).isEqualByComparingTo(new BigDecimal("100.00")); + assertThat(built.getItems()).hasSize(1); + assertThat(built.getItems().get(0).getProductName()).isEqualTo("Keyboard"); + assertThat(built.getItems().get(0).getQuantity()).isEqualTo(2); ArgumentCaptor eventCaptor = ArgumentCaptor.forClass(OrderCreatedEvent.class); verify(eventPublisher).publishEvent(eventCaptor.capture()); - assertThat(eventCaptor.getValue()).isEqualTo(new OrderCreatedEvent(1L, 1L, 1L, 2, 100.0)); + OrderCreatedEvent event = eventCaptor.getValue(); + assertThat(event.orderId()).isEqualTo(1L); + assertThat(event.customerId()).isEqualTo(1L); + assertThat(event.productId()).isEqualTo(1L); + assertThat(event.quantity()).isEqualTo(2); + assertThat(event.totalAmount()).isEqualByComparingTo(new BigDecimal("100.00")); + assertThat(event.orderNumber()).isNotBlank(); } @Test @@ -206,10 +231,12 @@ void _06_ShouldThrowNotFound_WhenProductMissingOnCreate() { } @Test - void _07_ShouldRecomputeTotal_WhenUpdatingOrder() { + void _07_ShouldRecomputeTotalAndReplaceItems_WhenUpdatingOrder() { OrderRequest request = new OrderRequest(1L, 1L, 3); - Order existing = Order.builder().id(1L).customer(customer).product(product).quantity(2).total(100.0).build(); - when(orderRepository.findById(1L)).thenReturn(Optional.of(existing)); + Order existing = Order.builder().id(1L).customer(customer).product(product).quantity(2) + .totalAmount(new BigDecimal("100.00")).orderNumber("ORD-HIST-000001") + .status(OrderStatus.PENDING).build(); + when(orderRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(existing)); when(customerRepository.findById(1L)).thenReturn(Optional.of(customer)); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); when(orderRepository.save(existing)).thenReturn(existing); @@ -217,13 +244,17 @@ void _07_ShouldRecomputeTotal_WhenUpdatingOrder() { orderService.update(1L, request); - verify(orderMapper).updateEntity(request, customer, product, 150.0, existing); + assertThat(existing.getQuantity()).isEqualTo(3); + assertThat(existing.getTotalAmount()).isEqualByComparingTo(new BigDecimal("150.00")); + assertThat(existing.getItems()).hasSize(1); + assertThat(existing.getItems().get(0).getQuantity()).isEqualTo(3); + verify(orderRepository).save(existing); } @Test void _08_ShouldThrowNotFound_WhenOrderMissingOnUpdate() { OrderRequest request = new OrderRequest(1L, 1L, 3); - when(orderRepository.findById(99L)).thenReturn(Optional.empty()); + when(orderRepository.findByIdWithDetails(99L)).thenReturn(Optional.empty()); assertThatThrownBy(() -> orderService.update(99L, request)) .isInstanceOf(ResourceNotFoundException.class); From 82d5206584fc2beb4488befee17d636622a0c76f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:08:49 +0400 Subject: [PATCH 044/175] test(repository): update OrderRepositoryTest for BigDecimal prices, OrderItem and new projection fields --- .../repository/OrderRepositoryTest.java | 39 ++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java index 6eb0c3b..0ee64cf 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java @@ -6,7 +6,10 @@ import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderItem; import com.edgareldy.springboottutorial.entity.Product; +import java.math.BigDecimal; +import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -58,12 +61,12 @@ void setUp() { .firstName("Grace").lastName("Hopper").telephone("+1 202-555-0101") .email("grace@example.com").address("2 Compiler Street").build()); keyboard = productRepository.save(Product.builder() - .category(category).productName("Keyboard").unitPrice(50.0f).build()); + .category(category).productName("Keyboard").unitPrice(new BigDecimal("50.00")).build()); desk = productRepository.save(Product.builder() - .category(category).productName("Desk").unitPrice(200.0f).build()); + .category(category).productName("Desk").unitPrice(new BigDecimal("200.00")).build()); - orderRepository.save(Order.builder().customer(ada).product(keyboard).quantity(2).total(100.0).build()); - orderRepository.save(Order.builder().customer(grace).product(desk).quantity(1).total(200.0).build()); + saveOrderWithItem(ada, keyboard, 2, new BigDecimal("100.00"), "ORD-TEST-001"); + saveOrderWithItem(grace, desk, 1, new BigDecimal("200.00"), "ORD-TEST-002"); } @Test @@ -82,7 +85,7 @@ void _02_ShouldFilterByCustomer_WhenCustomerIdGiven() { assertThat(projection.customerFirstName()).isEqualTo("Ada"); assertThat(projection.customerLastName()).isEqualTo("Lovelace"); assertThat(projection.productName()).isEqualTo("Keyboard"); - assertThat(projection.total()).isEqualTo(100.0); + assertThat(projection.totalAmount()).isEqualByComparingTo(new BigDecimal("100.00")); } @Test @@ -96,7 +99,7 @@ void _03_ShouldFilterByProduct_WhenProductIdGiven() { @Test void _03b_ShouldReturnEachCustomerOnce_WhenCustomerHasSeveralOrders() { - orderRepository.save(Order.builder().customer(ada).product(desk).quantity(1).total(200.0).build()); + saveOrderWithItem(ada, desk, 1, new BigDecimal("200.00"), "ORD-TEST-003"); var page = orderRepository.findCustomersWithOrders( null, null, PageRequest.of(0, 10, Sort.by("id"))); @@ -123,7 +126,7 @@ void _03c_ShouldExcludeCustomersWithoutMatchingOrder_WhenPagingCustomers() { @Test void _03d_ShouldLoadEveryOrderOfGivenCustomers_WhenProjectingByCustomerIds() { - orderRepository.save(Order.builder().customer(ada).product(desk).quantity(3).total(600.0).build()); + saveOrderWithItem(ada, desk, 3, new BigDecimal("600.00"), "ORD-TEST-003"); List all = orderRepository.findAllProjectedByCustomerIds( List.of(ada.getId(), grace.getId()), null); @@ -135,11 +138,11 @@ void _03d_ShouldLoadEveryOrderOfGivenCustomers_WhenProjectingByCustomerIds() { .extracting(OrderProjection::productName).containsExactly("Keyboard", "Desk"); assertThat(adaDeskOnly).hasSize(1); assertThat(adaDeskOnly.get(0).quantity()).isEqualTo(3); - assertThat(adaDeskOnly.get(0).total()).isEqualTo(600.0); + assertThat(adaDeskOnly.get(0).totalAmount()).isEqualByComparingTo(new BigDecimal("600.00")); } @Test - void _04_ShouldLoadCustomerAndProductEagerly_WhenFindingOrderById() { + void _04_ShouldLoadCustomerProductAndItems_WhenFindingOrderById() { Long orderId = orderRepository.findAllProjected(ada.getId(), null, PageRequest.of(0, 10)) .getContent().get(0).id(); @@ -148,5 +151,23 @@ void _04_ShouldLoadCustomerAndProductEagerly_WhenFindingOrderById() { assertThat(found).isPresent(); assertThat(found.get().getCustomer().getEmail()).isEqualTo("ada@example.com"); assertThat(found.get().getProduct().getProductName()).isEqualTo("Keyboard"); + assertThat(found.get().getItems()).hasSize(1); + assertThat(found.get().getItems().get(0).getProductName()).isEqualTo("Keyboard"); + assertThat(found.get().getItems().get(0).getUnitPrice()).isEqualByComparingTo(new BigDecimal("50.00")); + } + + private Order saveOrderWithItem(Customer c, Product p, int qty, BigDecimal total, String orderNum) { + BigDecimal subtotal = p.getUnitPrice().multiply(BigDecimal.valueOf(qty)); + OrderItem item = OrderItem.builder() + .product(p).productName(p.getProductName()) + .unitPrice(p.getUnitPrice()).quantity(qty).subtotal(subtotal) + .build(); + Order order = Order.builder() + .customer(c).product(p).quantity(qty) + .totalAmount(total).orderNumber(orderNum) + .items(new ArrayList<>(List.of(item))) + .build(); + item.setOrder(order); + return orderRepository.save(order); } } From f67987864591abac0d8eae75cb1b9d3ddd78e17b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:08:54 +0400 Subject: [PATCH 045/175] test(controller): update OrderControllerTest for BigDecimal, new OrderResponse and ProductResponse fields --- .../controller/OrderControllerTest.java | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index 14fab45..e00aaef 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java @@ -22,6 +22,7 @@ import com.edgareldy.springboottutorial.dto.product.ProductResponse; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.service.OrderService; +import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -60,16 +61,18 @@ private static OrderCustomerResponse sampleCustomer() { } private static OrderResponse sampleResponse() { - ProductResponse product = new ProductResponse(1L, "Keyboard", 50.0f, 1L, "Electronics"); - return new OrderResponse(1L, sampleCustomer(), product, 2, 100.0); + ProductResponse product = new ProductResponse( + 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics"); + return new OrderResponse(1L, sampleCustomer(), product, 2, + "ORD-TEST-0001", "PENDING", new BigDecimal("100.00"), List.of()); } private static PageResponse sampleGroupedPage() { CustomerOrdersResponse entry = new CustomerOrdersResponse( sampleCustomer(), - List.of(new OrderedProductResponse(1L, 1L, "Keyboard", 50.0f, 2, 100.0), - new OrderedProductResponse(2L, 2L, "Desk", 200.0f, 1, 200.0)), - 300.0); + List.of(new OrderedProductResponse(1L, 1L, "Keyboard", new BigDecimal("50.00"), 2, new BigDecimal("100.00")), + new OrderedProductResponse(2L, 2L, "Desk", new BigDecimal("200.00"), 1, new BigDecimal("200.00"))), + new BigDecimal("300.00")); return new PageResponse<>(List.of(entry), 0, 20, 1, 1); } @@ -84,11 +87,11 @@ void _01_ShouldReturnOrdersGroupedByCustomer_WhenNoFilterGiven() throws Exceptio .andExpect(jsonPath("$.data.content[0].products.length()").value(2)) .andExpect(jsonPath("$.data.content[0].products[0].order_id").value(1)) .andExpect(jsonPath("$.data.content[0].products[0].product_name").value("Keyboard")) - .andExpect(jsonPath("$.data.content[0].products[0].unit_price").value(50.0)) + .andExpect(jsonPath("$.data.content[0].products[0].unit_price").value(50.00)) .andExpect(jsonPath("$.data.content[0].products[0].quantity").value(2)) - .andExpect(jsonPath("$.data.content[0].products[0].total").value(100.0)) + .andExpect(jsonPath("$.data.content[0].products[0].total").value(100.00)) .andExpect(jsonPath("$.data.content[0].products[1].product_id").value(2)) - .andExpect(jsonPath("$.data.content[0].total").value(300.0)); + .andExpect(jsonPath("$.data.content[0].total").value(300.00)); } @Test @@ -117,7 +120,10 @@ void _04_ShouldReturn201_WhenCreateRequestValid() throws Exception { .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(new OrderRequest(1L, 1L, 2)))) .andExpect(status().isCreated()) - .andExpect(jsonPath("$.data.product.product_name").value("Keyboard")); + .andExpect(jsonPath("$.data.product.product_name").value("Keyboard")) + .andExpect(jsonPath("$.data.order_number").value("ORD-TEST-0001")) + .andExpect(jsonPath("$.data.status").value("PENDING")) + .andExpect(jsonPath("$.data.total_amount").value(100.00)); } @Test From 77c1faabb432f132ede4d3ec5b7839fe59f335d6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:09:00 +0400 Subject: [PATCH 046/175] test(service): update CustomerServiceImplTest for BigDecimal totals and new OrderProjection fields --- .../service/impl/CustomerServiceImplTest.java | 51 +++++++++++-------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java index 80bf5d4..0a9029f 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java @@ -10,15 +10,16 @@ import com.edgareldy.springboottutorial.dto.common.PageResponse; import com.edgareldy.springboottutorial.dto.customer.CustomerRequest; import com.edgareldy.springboottutorial.dto.customer.CustomerResponse; +import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; -import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; import com.edgareldy.springboottutorial.mapper.CustomerMapper; import com.edgareldy.springboottutorial.mapper.OrderMapper; import com.edgareldy.springboottutorial.repository.CustomerRepository; import com.edgareldy.springboottutorial.repository.OrderProjection; import com.edgareldy.springboottutorial.repository.OrderRepository; +import java.math.BigDecimal; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; @@ -67,14 +68,15 @@ void setUp() { .id(1L).firstName("Ada").lastName("Lovelace").telephone("+1 202-555-0100") .email("ada@example.com").address("1 Analytical Engine Way").build(); customerResponse = new CustomerResponse( - 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", List.of(), 0.0); + 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", + "1 Analytical Engine Way", List.of(), BigDecimal.ZERO); } @Test void _01_ShouldUsePlainFindAll_WhenNoSearchTermGiven() { Pageable pageable = PageRequest.of(0, 10); when(customerRepository.findAll(pageable)).thenReturn(new PageImpl<>(List.of(customer), pageable, 1)); - when(customerMapper.toResponseWithOrders(customer, List.of(), 0.0)).thenReturn(customerResponse); + when(customerMapper.toResponseWithOrders(customer, List.of(), BigDecimal.ZERO)).thenReturn(customerResponse); PageResponse result = customerService.findAll(null, pageable); @@ -87,7 +89,7 @@ void _02_ShouldUseSearchQuery_WhenSearchTermGiven() { Pageable pageable = PageRequest.of(0, 10); when(customerRepository.search("lovelace", pageable)) .thenReturn(new PageImpl<>(List.of(customer), pageable, 1)); - when(customerMapper.toResponseWithOrders(customer, List.of(), 0.0)).thenReturn(customerResponse); + when(customerMapper.toResponseWithOrders(customer, List.of(), BigDecimal.ZERO)).thenReturn(customerResponse); PageResponse result = customerService.findAll("lovelace", pageable); @@ -103,27 +105,29 @@ void _02b_ShouldAttachEachCustomerOrdersWithOneQuery_WhenListingCustomers() { .email("grace@example.com").address("2 Compiler Street").build(); OrderProjection adaKeyboard = new OrderProjection( 1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 1L, "Keyboard", 19.99f, 1L, "Electronics", 1, 19.99); + 1L, "Keyboard", new BigDecimal("19.99"), true, 1L, "Electronics", + 1, new BigDecimal("19.99"), "PENDING", "ORD-TEST-001"); OrderProjection adaDesk = new OrderProjection( 2L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 2L, "Desk", 0.1f, 1L, "Electronics", 2, 0.2); + 2L, "Desk", new BigDecimal("0.10"), true, 1L, "Electronics", + 2, new BigDecimal("0.20"), "PENDING", "ORD-TEST-002"); List adaLines = List.of( - new OrderedProductResponse(1L, 1L, "Keyboard", 19.99f, 1, 19.99), - new OrderedProductResponse(2L, 2L, "Desk", 0.1f, 2, 0.2)); + new OrderedProductResponse(1L, 1L, "Keyboard", new BigDecimal("19.99"), 1, new BigDecimal("19.99")), + new OrderedProductResponse(2L, 2L, "Desk", new BigDecimal("0.10"), 2, new BigDecimal("0.20"))); CustomerResponse adaResponse = new CustomerResponse( 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - adaLines, 20.19); + adaLines, new BigDecimal("20.19")); CustomerResponse graceResponse = new CustomerResponse( - 2L, "Grace", "Hopper", "+1 202-555-0101", "grace@example.com", "2 Compiler Street", List.of(), 0.0); + 2L, "Grace", "Hopper", "+1 202-555-0101", "grace@example.com", "2 Compiler Street", + List.of(), BigDecimal.ZERO); when(customerRepository.findAll(pageable)) .thenReturn(new PageImpl<>(List.of(customer, grace), pageable, 2)); when(orderRepository.findAllProjectedByCustomerIds(List.of(1L, 2L), null)) .thenReturn(List.of(adaKeyboard, adaDesk)); when(orderMapper.toOrderedProducts(List.of(adaKeyboard, adaDesk))).thenReturn(adaLines); when(orderMapper.toOrderedProducts(List.of())).thenReturn(List.of()); - // 19.99 + 0.2 is 20.189999999999998 in double arithmetic: the service must round it to 20.19. - when(customerMapper.toResponseWithOrders(customer, adaLines, 20.19)).thenReturn(adaResponse); - when(customerMapper.toResponseWithOrders(grace, List.of(), 0.0)).thenReturn(graceResponse); + when(customerMapper.toResponseWithOrders(customer, adaLines, new BigDecimal("20.19"))).thenReturn(adaResponse); + when(customerMapper.toResponseWithOrders(grace, List.of(), BigDecimal.ZERO)).thenReturn(graceResponse); PageResponse result = customerService.findAll(null, pageable); @@ -145,16 +149,17 @@ void _02c_ShouldSkipOrderQuery_WhenPageIsEmpty() { void _03_ShouldReturnResponseWithOrderedProducts_WhenCustomerFound() { OrderProjection keyboardOrder = new OrderProjection( 7L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 1L, "Keyboard", 79.99f, 1L, "Electronics", 2, 159.98); - List lines = - List.of(new OrderedProductResponse(7L, 1L, "Keyboard", 79.99f, 2, 159.98)); + 1L, "Keyboard", new BigDecimal("79.99"), true, 1L, "Electronics", + 2, new BigDecimal("159.98"), "PENDING", "ORD-TEST-007"); + List lines = List.of( + new OrderedProductResponse(7L, 1L, "Keyboard", new BigDecimal("79.99"), 2, new BigDecimal("159.98"))); CustomerResponse detailResponse = new CustomerResponse( 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - lines, 159.98); + lines, new BigDecimal("159.98")); when(customerRepository.findById(1L)).thenReturn(Optional.of(customer)); when(orderRepository.findAllProjectedByCustomerIds(List.of(1L), null)).thenReturn(List.of(keyboardOrder)); when(orderMapper.toOrderedProducts(List.of(keyboardOrder))).thenReturn(lines); - when(customerMapper.toResponseWithOrders(customer, lines, 159.98)).thenReturn(detailResponse); + when(customerMapper.toResponseWithOrders(customer, lines, new BigDecimal("159.98"))).thenReturn(detailResponse); assertThat(customerService.findById(1L)).isEqualTo(detailResponse); } @@ -208,10 +213,11 @@ void _08_ShouldApplyRequest_WhenEmailUnchanged() { CustomerRequest request = new CustomerRequest( "Ada", "Byron", "+1 202-555-0100", "ada@example.com", "2 Analytical Engine Way"); CustomerResponse updatedResponse = new CustomerResponse( - 1L, "Ada", "Byron", "+1 202-555-0100", "ada@example.com", "2 Analytical Engine Way", List.of(), 0.0); + 1L, "Ada", "Byron", "+1 202-555-0100", "ada@example.com", + "2 Analytical Engine Way", List.of(), BigDecimal.ZERO); when(customerRepository.findById(1L)).thenReturn(Optional.of(customer)); when(customerRepository.save(customer)).thenReturn(customer); - when(customerMapper.toResponseWithOrders(customer, List.of(), 0.0)).thenReturn(updatedResponse); + when(customerMapper.toResponseWithOrders(customer, List.of(), BigDecimal.ZERO)).thenReturn(updatedResponse); assertThat(customerService.update(1L, request)).isEqualTo(updatedResponse); @@ -224,10 +230,11 @@ void _09_ShouldSkipEmailCheck_WhenOnlyCaseDiffers() { CustomerRequest request = new CustomerRequest( "Ada", "Byron", "+1 202-555-0100", "ADA@EXAMPLE.COM", "2 Analytical Engine Way"); CustomerResponse updatedResponse = new CustomerResponse( - 1L, "Ada", "Byron", "+1 202-555-0100", "ADA@EXAMPLE.COM", "2 Analytical Engine Way", List.of(), 0.0); + 1L, "Ada", "Byron", "+1 202-555-0100", "ADA@EXAMPLE.COM", + "2 Analytical Engine Way", List.of(), BigDecimal.ZERO); when(customerRepository.findById(1L)).thenReturn(Optional.of(customer)); when(customerRepository.save(customer)).thenReturn(customer); - when(customerMapper.toResponseWithOrders(customer, List.of(), 0.0)).thenReturn(updatedResponse); + when(customerMapper.toResponseWithOrders(customer, List.of(), BigDecimal.ZERO)).thenReturn(updatedResponse); assertThat(customerService.update(1L, request)).isEqualTo(updatedResponse); From e795a943734fad4fae0334fdc461e59882762e9a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:09:03 +0400 Subject: [PATCH 047/175] test(controller): update CustomerControllerTest for BigDecimal prices and new DTO fields --- .../controller/CustomerControllerTest.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java index a857bbc..c5eaa1d 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java @@ -24,6 +24,7 @@ import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.service.CustomerService; import com.edgareldy.springboottutorial.service.OrderService; +import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -66,7 +67,8 @@ private static CustomerRequest validRequest() { private static CustomerResponse savedResponse() { return new CustomerResponse( 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - List.of(new OrderedProductResponse(7L, 3L, "Keyboard", 50.0f, 2, 100.0)), 100.0); + List.of(new OrderedProductResponse(7L, 3L, "Keyboard", new BigDecimal("50.00"), 2, new BigDecimal("100.00"))), + new BigDecimal("100.00")); } @Test @@ -178,10 +180,12 @@ void _10_ShouldReturn404_WhenCustomerMissingOnDelete() throws Exception { @Test void _11_ShouldReturn200_WhenListingOrdersOfExistingCustomer() throws Exception { - ProductResponse product = new ProductResponse(1L, "Keyboard", 50.0f, 1L, "Electronics"); + ProductResponse product = new ProductResponse( + 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics"); OrderCustomerResponse customer = new OrderCustomerResponse( 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way"); - OrderResponse order = new OrderResponse(1L, customer, product, 2, 100.0); + OrderResponse order = new OrderResponse(1L, customer, product, 2, + "ORD-TEST-0001", "PENDING", new BigDecimal("100.00"), List.of()); PageResponse page = new PageResponse<>(List.of(order), 0, 20, 1, 1); when(customerService.findById(1L)).thenReturn(savedResponse()); when(orderService.findAll(eq(1L), isNull(), any())).thenReturn(page); From 406c67d16f6b9721b854a9ea77471c0b4517bb02 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:09:06 +0400 Subject: [PATCH 048/175] test(mapper): add OrderMapperTest covering entity, projection and grouped-view mappings OrderMapper has two code paths not exercised by the service tests, which stub the mapper entirely: entity->DTO and projection->DTO. This class exercises both against the MapStruct-generated implementation, asserting that nested DTOs (CustomerResponse, ProductResponse, OrderItemResponse) are assembled correctly from each input type. toCustomerOrdersResponse is also tested to verify that the pre-computed total is passed through unchanged and that the product list is built from the flat projection rows. --- .../mapper/OrderMapperTest.java | 168 ++++++++---------- 1 file changed, 78 insertions(+), 90 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java b/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java index 5b3b465..a14fcf2 100644 --- a/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java @@ -3,136 +3,124 @@ import static org.assertj.core.api.Assertions.assertThat; import com.edgareldy.springboottutorial.dto.order.CustomerOrdersResponse; -import com.edgareldy.springboottutorial.dto.order.OrderRequest; +import com.edgareldy.springboottutorial.dto.order.OrderItemResponse; import com.edgareldy.springboottutorial.dto.order.OrderResponse; +import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderItem; +import com.edgareldy.springboottutorial.entity.OrderStatus; import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.repository.OrderProjection; +import java.math.BigDecimal; +import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; /** - * Tests the real MapStruct-generated {@link OrderMapperImpl}, not a mock. - * {@link OrderMapper#toResponse(Order)} delegates to - * {@link ProductMapper} (via {@code uses}), while - * {@link OrderMapper#toResponse(OrderProjection)} is a hand-written - * {@code default} method rebuilding the same DTOs field by field from a flat - * projection; only a test against the generated code can catch a silent - * field transposition (e.g. first/last name swapped) in either path. + * Tests the real MapStruct-generated {@link OrderMapperImpl} together with + * {@link OrderItemMapperImpl} and {@link ProductMapperImpl}: verifies that + * entity-to-DTO mapping, enum-to-String conversion for {@code status}, the + * manual {@code toResponse(OrderProjection)} overload, and the grouped-view + * helper {@code toCustomerOrdersResponse} all produce correct output. *

- * Created edgar.muhamyangabo on 9/3/26 + * Created edgar.muhamyangabo on 11/17/26 * Author : edgar.muhamyangabo - * Date : 9/3/26 + * Date : 11/17/26 * Project : spring-boot-tutorial */ -@SpringBootTest(classes = {OrderMapperImpl.class, ProductMapperImpl.class}) +@SpringBootTest(classes = {OrderMapperImpl.class, OrderItemMapperImpl.class, ProductMapperImpl.class}) class OrderMapperTest { @Autowired private OrderMapper orderMapper; @Test - void _01_ShouldNestFullCustomerAndProduct_WhenMappingFromEntity() { - Customer customer = Customer.builder().id(1L).firstName("Ada").lastName("Lovelace") - .telephone("+1 202-555-0100").email("ada@example.com").address("1 Analytical Engine Way").build(); - Category category = Category.builder().id(1L).categoryName("Electronics").build(); - Product product = Product.builder().id(10L).category(category).productName("Keyboard").unitPrice(50.0f).build(); - Order order = Order.builder().id(100L).customer(customer).product(product).quantity(2).total(100.0).build(); + void _01_ShouldMapOrderEntityToResponse_WithStatusStringAndItems() { + Category cat = Category.builder().id(1L).categoryName("Electronics").build(); + Product product = Product.builder().id(2L).productName("Keyboard") + .unitPrice(new BigDecimal("50.00")).category(cat).build(); + Customer customer = Customer.builder().id(3L).firstName("Ada").lastName("Lovelace") + .telephone("+1 202-555-0100").email("ada@example.com") + .address("1 Analytical Engine Way").build(); + + OrderItem item = OrderItem.builder() + .id(10L).product(product).productName("Keyboard") + .unitPrice(new BigDecimal("50.00")).quantity(2) + .subtotal(new BigDecimal("100.00")).build(); + Order order = Order.builder() + .id(5L).customer(customer).product(product).quantity(2) + .totalAmount(new BigDecimal("100.00")).orderNumber("ORD-TEST-001") + .status(OrderStatus.PENDING) + .items(new ArrayList<>(List.of(item))) + .build(); + item.setOrder(order); OrderResponse response = orderMapper.toResponse(order); + assertThat(response.id()).isEqualTo(5L); + assertThat(response.status()).isEqualTo("PENDING"); + assertThat(response.orderNumber()).isEqualTo("ORD-TEST-001"); + assertThat(response.totalAmount()).isEqualByComparingTo(new BigDecimal("100.00")); assertThat(response.customer().firstName()).isEqualTo("Ada"); - assertThat(response.customer().lastName()).isEqualTo("Lovelace"); assertThat(response.product().productName()).isEqualTo("Keyboard"); - assertThat(response.product().categoryName()).isEqualTo("Electronics"); + assertThat(response.items()).hasSize(1); + OrderItemResponse itemResponse = response.items().get(0); + assertThat(itemResponse.id()).isEqualTo(10L); + assertThat(itemResponse.productId()).isEqualTo(2L); + assertThat(itemResponse.productName()).isEqualTo("Keyboard"); + assertThat(itemResponse.unitPrice()).isEqualByComparingTo(new BigDecimal("50.00")); + assertThat(itemResponse.quantity()).isEqualTo(2); + assertThat(itemResponse.subtotal()).isEqualByComparingTo(new BigDecimal("100.00")); } @Test - void _02_ShouldMapEachField_WhenMappingFromProjection() { + void _02_ShouldMapProjectionToResponse_WithNullDescriptionAndActiveFromProjection() { OrderProjection projection = new OrderProjection( - 100L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 10L, "Keyboard", 50.0f, 5L, "Electronics", 2, 100.0); + 7L, 3L, "Grace", "Hopper", "+1 202-555-0101", "grace@example.com", "2 Compiler Street", + 1L, "Desk", new BigDecimal("200.00"), true, 2L, "Office", + 1, new BigDecimal("200.00"), "CONFIRMED", "ORD-TEST-007"); OrderResponse response = orderMapper.toResponse(projection); - assertThat(response.customer().id()).isEqualTo(1L); - assertThat(response.customer().firstName()).isEqualTo("Ada"); - assertThat(response.customer().lastName()).isEqualTo("Lovelace"); - assertThat(response.customer().telephone()).isEqualTo("+1 202-555-0100"); - assertThat(response.customer().email()).isEqualTo("ada@example.com"); - assertThat(response.customer().address()).isEqualTo("1 Analytical Engine Way"); - assertThat(response.product().id()).isEqualTo(10L); - assertThat(response.product().productName()).isEqualTo("Keyboard"); - assertThat(response.product().unitPrice()).isEqualTo(50.0f); - assertThat(response.product().categoryId()).isEqualTo(5L); - assertThat(response.product().categoryName()).isEqualTo("Electronics"); - assertThat(response.quantity()).isEqualTo(2); - assertThat(response.total()).isEqualTo(100.0); + assertThat(response.id()).isEqualTo(7L); + assertThat(response.status()).isEqualTo("CONFIRMED"); + assertThat(response.orderNumber()).isEqualTo("ORD-TEST-007"); + assertThat(response.totalAmount()).isEqualByComparingTo(new BigDecimal("200.00")); + assertThat(response.customer().firstName()).isEqualTo("Grace"); + assertThat(response.product().productName()).isEqualTo("Desk"); + assertThat(response.product().description()).isNull(); + assertThat(response.product().active()).isTrue(); + assertThat(response.items()).isEmpty(); } @Test - void _02b_ShouldListOneLinePerOrder_WhenBuildingCustomerOrders() { + void _03_ShouldBuildGroupedResponse_WithOrderedProductLines() { Customer customer = Customer.builder().id(1L).firstName("Ada").lastName("Lovelace") - .telephone("+1 202-555-0100").email("ada@example.com").address("1 Analytical Engine Way").build(); - OrderProjection keyboardOrder = new OrderProjection( - 100L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 10L, "Keyboard", 50.0f, 5L, "Electronics", 2, 100.0); - OrderProjection deskOrder = new OrderProjection( - 101L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", - 11L, "Desk", 200.0f, 5L, "Electronics", 1, 200.0); - - CustomerOrdersResponse response = - orderMapper.toCustomerOrdersResponse(customer, List.of(keyboardOrder, deskOrder), 300.0); + .telephone("+1 202-555-0100").email("ada@example.com") + .address("1 Analytical Engine Way").build(); + List projections = List.of( + new OrderProjection(1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", + "1 Analytical Engine Way", 2L, "Keyboard", new BigDecimal("50.00"), true, + 3L, "Electronics", 2, new BigDecimal("100.00"), "PENDING", "ORD-TEST-001"), + new OrderProjection(2L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", + "1 Analytical Engine Way", 4L, "Desk", new BigDecimal("200.00"), true, + 3L, "Electronics", 1, new BigDecimal("200.00"), "PENDING", "ORD-TEST-002")); + + CustomerOrdersResponse response = orderMapper.toCustomerOrdersResponse( + customer, projections, new BigDecimal("300.00")); - assertThat(response.customer().id()).isEqualTo(1L); assertThat(response.customer().firstName()).isEqualTo("Ada"); - assertThat(response.customer().lastName()).isEqualTo("Lovelace"); - assertThat(response.customer().telephone()).isEqualTo("+1 202-555-0100"); - assertThat(response.customer().email()).isEqualTo("ada@example.com"); - assertThat(response.customer().address()).isEqualTo("1 Analytical Engine Way"); + assertThat(response.total()).isEqualByComparingTo(new BigDecimal("300.00")); assertThat(response.products()).hasSize(2); - assertThat(response.products().get(0).orderId()).isEqualTo(100L); - assertThat(response.products().get(0).productId()).isEqualTo(10L); - assertThat(response.products().get(0).productName()).isEqualTo("Keyboard"); - assertThat(response.products().get(0).unitPrice()).isEqualTo(50.0f); - assertThat(response.products().get(0).quantity()).isEqualTo(2); - assertThat(response.products().get(0).total()).isEqualTo(100.0); - assertThat(response.products().get(1).orderId()).isEqualTo(101L); - assertThat(response.products().get(1).productName()).isEqualTo("Desk"); - assertThat(response.total()).isEqualTo(300.0); - } - - @Test - void _03_ShouldAssignAssociationsQuantityAndTotal_WhenBuildingNewOrder() { - Customer customer = Customer.builder().id(1L).firstName("Ada").lastName("Lovelace").build(); - Product product = Product.builder().id(10L).productName("Keyboard").unitPrice(50.0f).build(); - - Order order = orderMapper.toEntity(new OrderRequest(1L, 10L, 2), customer, product, 100.0); - - assertThat(order.getId()).isNull(); - assertThat(order.getCustomer()).isSameAs(customer); - assertThat(order.getProduct()).isSameAs(product); - assertThat(order.getQuantity()).isEqualTo(2); - assertThat(order.getTotal()).isEqualTo(100.0); - } - - @Test - void _04_ShouldKeepIdentityAndReplaceValues_WhenUpdatingExistingOrder() { - Customer oldCustomer = Customer.builder().id(1L).firstName("Ada").lastName("Lovelace").build(); - Customer newCustomer = Customer.builder().id(2L).firstName("Grace").lastName("Hopper").build(); - Product product = Product.builder().id(10L).productName("Keyboard").unitPrice(50.0f).build(); - Order existing = Order.builder().id(100L).customer(oldCustomer).product(product).quantity(2).total(100.0).build(); - - orderMapper.updateEntity(new OrderRequest(2L, 10L, 3), newCustomer, product, 150.0, existing); - - assertThat(existing.getId()).isEqualTo(100L); - assertThat(existing.getCustomer()).isSameAs(newCustomer); - assertThat(existing.getProduct()).isSameAs(product); - assertThat(existing.getQuantity()).isEqualTo(3); - assertThat(existing.getTotal()).isEqualTo(150.0); + List lines = response.products(); + assertThat(lines.get(0).productName()).isEqualTo("Keyboard"); + assertThat(lines.get(0).quantity()).isEqualTo(2); + assertThat(lines.get(0).total()).isEqualByComparingTo(new BigDecimal("100.00")); + assertThat(lines.get(1).productName()).isEqualTo("Desk"); + assertThat(lines.get(1).total()).isEqualByComparingTo(new BigDecimal("200.00")); } } From 7d2a61c516ea929fffff73f47a784b40b9e7e84e Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:09:38 +0400 Subject: [PATCH 049/175] test(mapper): update CustomerMapperTest for BigDecimal prices and total --- .../springboottutorial/mapper/CustomerMapperTest.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/mapper/CustomerMapperTest.java b/src/test/java/com/edgareldy/springboottutorial/mapper/CustomerMapperTest.java index 5b161f6..6a209cc 100644 --- a/src/test/java/com/edgareldy/springboottutorial/mapper/CustomerMapperTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/mapper/CustomerMapperTest.java @@ -5,6 +5,7 @@ import com.edgareldy.springboottutorial.dto.customer.CustomerResponse; import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; import com.edgareldy.springboottutorial.entity.Customer; +import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -44,14 +45,16 @@ void _01_ShouldReturnEmptyProductsAndZeroTotal_WhenUsingPlainResponse() { @Test void _02_ShouldMapSuppliedProductsAndTotal_WhenUsingResponseWithOrders() { - OrderedProductResponse keyboard = new OrderedProductResponse(100L, 10L, "Keyboard", 79.99f, 2, 159.98); + OrderedProductResponse keyboard = new OrderedProductResponse( + 100L, 10L, "Keyboard", new BigDecimal("79.99"), 2, new BigDecimal("159.98")); - CustomerResponse response = customerMapper.toResponseWithOrders(customer(), List.of(keyboard), 159.98); + CustomerResponse response = customerMapper.toResponseWithOrders( + customer(), List.of(keyboard), new BigDecimal("159.98")); assertThat(response.id()).isEqualTo(1L); assertThat(response.lastName()).isEqualTo("Lovelace"); assertThat(response.products()).containsExactly(keyboard); - assertThat(response.total()).isEqualTo(159.98); + assertThat(response.total()).isEqualByComparingTo(new BigDecimal("159.98")); } } From 3d59869086bfa86f3c9942618da96a969d7bc637 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:11:17 +0400 Subject: [PATCH 050/175] fix(event): update OrderCreatedEventListener to use totalAmount and orderNumber from OrderCreatedEvent OrderCreatedEvent replaced its legacy double total field with totalAmount (BigDecimal) and added orderNumber. The listener was still reading the removed fields, causing a compilation error. Updated to log both new fields; the log statement is the only consumer of this event at this stage so no other call sites required changes. --- .../springboottutorial/event/OrderCreatedEventListener.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java b/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java index eeca3a5..5b836d7 100644 --- a/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java +++ b/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java @@ -28,7 +28,8 @@ public class OrderCreatedEventListener { @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void onOrderCreated(OrderCreatedEvent event) { - log.info("Order {} created for customer {} on product {}: quantity={}, total={}", - event.orderId(), event.customerId(), event.productId(), event.quantity(), event.total()); + log.info("Order {} ({}) created for customer {} on product {}: quantity={}, total={}", + event.orderId(), event.orderNumber(), event.customerId(), event.productId(), + event.quantity(), event.totalAmount()); } } From a92796652ea11eb98488a4a1465c7bdf4eb34619 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:16:26 +0400 Subject: [PATCH 051/175] fix(repository): change OrderProjection status field from String to OrderStatus to fix JPQL SELECT new type mismatch JPQL SELECT new constructors require an exact type match between the expression type and the constructor parameter. Order.status maps to an OrderStatus enum, so Hibernate resolves the JPQL column expression to OrderStatus, not String. The original String declaration caused a constructor-not-found error at startup. Fixed by changing the projection field and constructor parameter to OrderStatus; the mapper calls .name() to convert the enum to the String stored in OrderResponse. --- .../springboottutorial/repository/OrderProjection.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java index e8bfbc2..47911fb 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java @@ -1,5 +1,6 @@ package com.edgareldy.springboottutorial.repository; +import com.edgareldy.springboottutorial.entity.OrderStatus; import java.math.BigDecimal; /** @@ -34,7 +35,7 @@ public record OrderProjection( String productCategoryName, int quantity, BigDecimal totalAmount, - String status, + OrderStatus status, String orderNumber ) { } From f287682a5e119364b92edef7e9b59ab04eda6c2a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:16:30 +0400 Subject: [PATCH 052/175] fix(mapper): call status().name() on OrderProjection to serialize enum as String in OrderResponse After OrderProjection.status was corrected to OrderStatus (see prior commit), the projection overload of OrderMapper still tried to assign it directly to OrderResponse.status, a String field. The assignment failed to compile. Fixed by calling .name() explicitly, consistent with the entity overload which already used order.getStatus().name() correctly. --- .../com/edgareldy/springboottutorial/mapper/OrderMapper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java index 1ef6a3f..670fd63 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java @@ -87,6 +87,6 @@ default OrderResponse toResponse(OrderProjection p) { p.productCategoryName()); return new OrderResponse( p.id(), customer, product, p.quantity(), - p.orderNumber(), p.status(), p.totalAmount(), List.of()); + p.orderNumber(), p.status().name(), p.totalAmount(), List.of()); } } From 9ec181c6660cc72fda82965fd0cb5f1587aabcaf Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:18:21 +0400 Subject: [PATCH 053/175] test(mapper): update OrderMapperTest to pass OrderStatus enum instead of String in OrderProjection --- .../springboottutorial/mapper/OrderMapperTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java b/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java index a14fcf2..952b602 100644 --- a/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java @@ -82,7 +82,7 @@ void _02_ShouldMapProjectionToResponse_WithNullDescriptionAndActiveFromProjectio OrderProjection projection = new OrderProjection( 7L, 3L, "Grace", "Hopper", "+1 202-555-0101", "grace@example.com", "2 Compiler Street", 1L, "Desk", new BigDecimal("200.00"), true, 2L, "Office", - 1, new BigDecimal("200.00"), "CONFIRMED", "ORD-TEST-007"); + 1, new BigDecimal("200.00"), OrderStatus.CONFIRMED, "ORD-TEST-007"); OrderResponse response = orderMapper.toResponse(projection); @@ -105,10 +105,10 @@ void _03_ShouldBuildGroupedResponse_WithOrderedProductLines() { List projections = List.of( new OrderProjection(1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 2L, "Keyboard", new BigDecimal("50.00"), true, - 3L, "Electronics", 2, new BigDecimal("100.00"), "PENDING", "ORD-TEST-001"), + 3L, "Electronics", 2, new BigDecimal("100.00"), OrderStatus.PENDING, "ORD-TEST-001"), new OrderProjection(2L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 4L, "Desk", new BigDecimal("200.00"), true, - 3L, "Electronics", 1, new BigDecimal("200.00"), "PENDING", "ORD-TEST-002")); + 3L, "Electronics", 1, new BigDecimal("200.00"), OrderStatus.PENDING, "ORD-TEST-002")); CustomerOrdersResponse response = orderMapper.toCustomerOrdersResponse( customer, projections, new BigDecimal("300.00")); From 40c83df391175c58b3467c77a7bae2051ac87604 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:18:25 +0400 Subject: [PATCH 054/175] test(service): update CustomerServiceImplTest to pass OrderStatus enum instead of String in OrderProjection --- .../service/impl/CustomerServiceImplTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java index 0a9029f..40b357a 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/CustomerServiceImplTest.java @@ -12,6 +12,7 @@ import com.edgareldy.springboottutorial.dto.customer.CustomerResponse; import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; import com.edgareldy.springboottutorial.entity.Customer; +import com.edgareldy.springboottutorial.entity.OrderStatus; import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.mapper.CustomerMapper; @@ -106,11 +107,11 @@ void _02b_ShouldAttachEachCustomerOrdersWithOneQuery_WhenListingCustomers() { OrderProjection adaKeyboard = new OrderProjection( 1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 1L, "Keyboard", new BigDecimal("19.99"), true, 1L, "Electronics", - 1, new BigDecimal("19.99"), "PENDING", "ORD-TEST-001"); + 1, new BigDecimal("19.99"), OrderStatus.PENDING, "ORD-TEST-001"); OrderProjection adaDesk = new OrderProjection( 2L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 2L, "Desk", new BigDecimal("0.10"), true, 1L, "Electronics", - 2, new BigDecimal("0.20"), "PENDING", "ORD-TEST-002"); + 2, new BigDecimal("0.20"), OrderStatus.PENDING, "ORD-TEST-002"); List adaLines = List.of( new OrderedProductResponse(1L, 1L, "Keyboard", new BigDecimal("19.99"), 1, new BigDecimal("19.99")), new OrderedProductResponse(2L, 2L, "Desk", new BigDecimal("0.10"), 2, new BigDecimal("0.20"))); @@ -150,7 +151,7 @@ void _03_ShouldReturnResponseWithOrderedProducts_WhenCustomerFound() { OrderProjection keyboardOrder = new OrderProjection( 7L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 1L, "Keyboard", new BigDecimal("79.99"), true, 1L, "Electronics", - 2, new BigDecimal("159.98"), "PENDING", "ORD-TEST-007"); + 2, new BigDecimal("159.98"), OrderStatus.PENDING, "ORD-TEST-007"); List lines = List.of( new OrderedProductResponse(7L, 1L, "Keyboard", new BigDecimal("79.99"), 2, new BigDecimal("159.98"))); CustomerResponse detailResponse = new CustomerResponse( From a80cc10cb93fb63ff8c4bb4605a01bdae1b968dc Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:18:31 +0400 Subject: [PATCH 055/175] test(service): update OrderServiceImplTest to pass OrderStatus enum instead of String in OrderProjection --- .../service/impl/OrderServiceImplTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 5171510..295ea5f 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -100,7 +100,7 @@ void _01_ShouldDelegateToProjectedQuery_WhenListingOrders() { OrderProjection projection = new OrderProjection( 1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 1L, "Keyboard", new BigDecimal("50.00"), true, 1L, "Electronics", - 2, new BigDecimal("100.00"), "PENDING", "ORD-HIST-000001"); + 2, new BigDecimal("100.00"), OrderStatus.PENDING, "ORD-HIST-000001"); when(orderRepository.findAllProjected(null, null, pageable)) .thenReturn(new PageImpl<>(List.of(projection), pageable, 1)); when(orderMapper.toResponse(projection)).thenReturn(orderResponse); @@ -118,15 +118,15 @@ void _01b_ShouldGroupOrdersAndSumTotals_WhenListingByCustomer() { OrderProjection adaKeyboard = new OrderProjection( 1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 1L, "Keyboard", new BigDecimal("19.99"), true, 1L, "Electronics", - 1, new BigDecimal("19.99"), "PENDING", "ORD-TEST-001"); + 1, new BigDecimal("19.99"), OrderStatus.PENDING, "ORD-TEST-001"); OrderProjection adaDesk = new OrderProjection( 2L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 2L, "Desk", new BigDecimal("0.10"), true, 1L, "Electronics", - 2, new BigDecimal("0.20"), "PENDING", "ORD-TEST-002"); + 2, new BigDecimal("0.20"), OrderStatus.PENDING, "ORD-TEST-002"); OrderProjection graceDesk = new OrderProjection( 3L, 2L, "Grace", "Hopper", "+1 202-555-0101", "grace@example.com", "2 Compiler Street", 2L, "Desk", new BigDecimal("200.00"), true, 1L, "Electronics", - 1, new BigDecimal("200.00"), "PENDING", "ORD-TEST-003"); + 1, new BigDecimal("200.00"), OrderStatus.PENDING, "ORD-TEST-003"); CustomerOrdersResponse adaEntry = new CustomerOrdersResponse(null, List.of(), new BigDecimal("20.19")); CustomerOrdersResponse graceEntry = new CustomerOrdersResponse(null, List.of(), new BigDecimal("200.00")); when(orderRepository.findCustomersWithOrders(null, null, pageable)) From 82676fa40727cf6237c527bfd8b353a54454d5d7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:22:48 +0400 Subject: [PATCH 056/175] fix(flyway): add V15 migration to drop NOT NULL on legacy orders.total column V14 replaced the old total DOUBLE PRECISION column with total_amount NUMERIC(12,2) and stopped mapping total in the Order entity. New inserts therefore omit total, causing a NOT NULL constraint violation. V15 drops the constraint so Hibernate inserts succeed; the column is kept but considered deprecated. --- .../db/migration/V15__make_orders_total_legacy_nullable.sql | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/main/resources/db/migration/V15__make_orders_total_legacy_nullable.sql diff --git a/src/main/resources/db/migration/V15__make_orders_total_legacy_nullable.sql b/src/main/resources/db/migration/V15__make_orders_total_legacy_nullable.sql new file mode 100644 index 0000000..ea7516d --- /dev/null +++ b/src/main/resources/db/migration/V15__make_orders_total_legacy_nullable.sql @@ -0,0 +1,6 @@ +-- V14 migrated monetary amounts to total_amount (NUMERIC 12,2) and no longer +-- maps the original total column in the Order entity. Drop the NOT NULL +-- constraint so Hibernate inserts succeed without providing a value for this +-- legacy column. The column is kept for schema-level backward compatibility +-- but is considered deprecated. +ALTER TABLE orders ALTER COLUMN total DROP NOT NULL; From 23069309854d9b0d6b54e07c085e5ed3c7f1f22f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:29:52 +0400 Subject: [PATCH 057/175] docs(mapper): fix Javadoc type double -> BigDecimal in CustomerMapper.toResponseWithOrders reference --- .../com/edgareldy/springboottutorial/mapper/CustomerMapper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java index e8ca5c9..6cdd48b 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java @@ -14,7 +14,7 @@ * response methods exist: {@link #toResponse(Customer)} for a customer that * cannot have orders yet (just created), with an empty {@code products} * list and a total of 0, and - * {@link #toResponseWithOrders(Customer, List, double)} which takes the + * {@link #toResponseWithOrders(Customer, List, java.math.BigDecimal)} which takes the * ordered products and their total from the caller. They are resolved by * the service layer via {@code OrderRepository}, since {@link Customer} * itself has no direct association to {@code Order}/{@code Product}. From 2a5c9e3eb9d9266470c0a3c1241b88f3dd4d7aab Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:29:57 +0400 Subject: [PATCH 058/175] docs(controller): update OrderControllerTest Javadoc to remove stale feature/auth reference --- .../springboottutorial/controller/OrderControllerTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index e00aaef..a42c7df 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java @@ -34,8 +34,8 @@ /** * MockMvc integration tests for {@link OrderController}, with - * {@link OrderService} mocked. Security filters are disabled since - * {@code feature/auth} has not defined a {@code SecurityConfig} yet. + * {@link OrderService} mocked. Security filters are disabled to focus on + * controller logic only ({@code addFilters = false}). *

* Created edgar.muhamyangabo on 7/8/26 * Author : edgar.muhamyangabo From 87396e1d9e6b60d9bd1da4834ef2590dd50d9058 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:30:12 +0400 Subject: [PATCH 059/175] test(repository): add tests for existsByCustomerId, existsByProductId and findByCustomerId Three Spring Data derived methods added in this phase had no @DataJpaTest coverage. Each method is exercised with both a matching and a non-matching input so the generated query is actually validated against PostgreSQL. --- .../repository/OrderRepositoryTest.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java index 0ee64cf..a063235 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java @@ -156,6 +156,29 @@ void _04_ShouldLoadCustomerProductAndItems_WhenFindingOrderById() { assertThat(found.get().getItems().get(0).getUnitPrice()).isEqualByComparingTo(new BigDecimal("50.00")); } + @Test + void _05_ShouldReturnTrue_WhenOrderExistsForCustomer() { + assertThat(orderRepository.existsByCustomerId(ada.getId())).isTrue(); + assertThat(orderRepository.existsByCustomerId(ada.getId() + 999L)).isFalse(); + } + + @Test + void _06_ShouldReturnTrue_WhenOrderExistsForProduct() { + assertThat(orderRepository.existsByProductId(keyboard.getId())).isTrue(); + assertThat(orderRepository.existsByProductId(keyboard.getId() + 999L)).isFalse(); + } + + @Test + void _07_ShouldReturnOrdersForCustomer_WhenPagingByCustomerId() { + saveOrderWithItem(ada, desk, 1, new BigDecimal("200.00"), "ORD-TEST-ADA-2"); + + var page = orderRepository.findByCustomerId(ada.getId(), PageRequest.of(0, 10)); + + assertThat(page.getTotalElements()).isEqualTo(2); + assertThat(page.getContent()).allSatisfy(o -> + assertThat(o.getCustomer().getId()).isEqualTo(ada.getId())); + } + private Order saveOrderWithItem(Customer c, Product p, int qty, BigDecimal total, String orderNum) { BigDecimal subtotal = p.getUnitPrice().multiply(BigDecimal.valueOf(qty)); OrderItem item = OrderItem.builder() From bd25468064a5305e92c7e004e814085061876b5e Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 13:30:53 +0400 Subject: [PATCH 060/175] docs(readme): update feature/orders section for e-commerce order domain Documents the multi-product order model (OrderItem with product snapshot, OrderStatus enum, BigDecimal totalAmount, orderNumber), the two Flyway migrations (V14 schema evolution + backfill, V15 legacy column nullable), and the updated endpoint and task checklists. --- README.md | 46 +++++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index f64eb64..867faf7 100644 --- a/README.md +++ b/README.md @@ -402,35 +402,47 @@ Includes `Category` and `Product`, given their direct link in the model. ## feature/orders +### Model + +- `Order` entity: `@ManyToOne` to `Customer` and `Product` (both nullable for historical compatibility), `@OneToMany(cascade = ALL, orphanRemoval = true)` to `OrderItem`, `@Enumerated(EnumType.STRING) OrderStatus status` (default `PENDING`), `BigDecimal totalAmount`, `String orderNumber` (unique, generated as `ORD-` + 8-char UUID prefix on create). +- `OrderItem` entity: product snapshot at order time (`productName`, `unitPrice` as `NUMERIC(12,2)`), `quantity`, `subtotal`; child of `Order` with `@ManyToOne(optional = false)` back-reference. Product snapshot decouples order history from future price changes. +- `OrderStatus` enum: `PENDING`, `CONFIRMED`, `CANCELLED`. +- Migration `V14__evolve_orders_domain.sql`: adds `order_number`, `status`, `total_amount` to `orders`; makes `customer_id`/`product_id` nullable; creates `order_items` table; backfills one `OrderItem` per historical order using the product snapshot; backfills `total_amount` from the legacy `total` column; generates `ORD-HIST-000001`-style order numbers for historical rows. +- Migration `V15__make_orders_total_legacy_nullable.sql`: drops the `NOT NULL` constraint on the legacy `total DOUBLE PRECISION` column, which V14 stopped mapping in the `Order` entity. The column is kept for schema-level backward compatibility but is no longer written by Hibernate. +- All monetary amounts are `BigDecimal` mapped to `NUMERIC(12,2)`. `totalAmount = unitPrice * quantity` computed in `OrderServiceImpl` using `BigDecimal.multiply`, never via floating-point arithmetic. + ### Response shapes -- `OrderResponse` (one order) embeds the customer's contact details (`OrderCustomerResponse`) and the full `ProductResponse`, on both the detail endpoint (`OrderRepository.findByIdWithDetails`, entity fetch join) and the paginated list (`OrderRepository.findAllProjected`, a flat JPQL constructor-expression projection extended with every column both DTOs need, still avoiding N+1 on a page of results). -- `CustomerResponse` (`GET /api/v1/customers` and `GET /api/v1/customers/{id}`) carries the customer's orders: `products`, one line per order (`order_id`, `product_id`, `product_name`, `unit_price`, `quantity`, `total`), and `total`, the sum of those totals. On the paginated list the orders of every customer of the page are loaded with a single `OrderRepository.findAllProjectedByCustomerIds` query (an `IN` on the page's customer ids), not one query per customer, and no JPA relationship is added on `Customer`. -- `GET /api/v1/orders` returns the same lines grouped by customer (`CustomerOrdersResponse`), paginated by customer via `OrderRepository.findCustomersWithOrders`. -- `OrderController` returns `ResponseEntity>`; `OrderRequest`/`OrderResponse` fields exposed in JSON as snake_case via `@JsonProperty` (`customer_id`, `product_id`). +- `OrderResponse` (one order) embeds `OrderCustomerResponse` and the full `ProductResponse`, plus `status` (String), `order_number`, `total_amount` (BigDecimal), and `items` (`List`). Two read paths: `findByIdWithDetails` (entity with `JOIN FETCH` on items, used for detail/create/update) and `findAllProjected` (17-field JPQL constructor-expression projection, used for the paginated list - no N+1). +- `CustomerResponse` carries `products` (one `OrderedProductResponse` per order) and `total` (BigDecimal sum). Loaded with a single `findAllProjectedByCustomerIds` (`IN` on the page's customer ids) for both the list and the detail. +- `GET /api/v1/orders` groups by customer (`CustomerOrdersResponse`), paginated via `findCustomersWithOrders`. +- `OrderController` returns `ResponseEntity>`; snake_case JSON fields via `@JsonProperty`. ### Endpoints | Method | URL | Description | |---|---|---| -| GET | `/api/v1/orders` | Orders grouped by customer: each customer once, with the products they ordered (quantity and total per order) and their overall total. Paginated by customer, filterable by `customerId`/`productId` | -| GET | `/api/v1/orders/{id}` | Order detail | -| POST | `/api/v1/orders` | Create an order (`total` computed automatically) | -| PUT | `/api/v1/orders/{id}` | Update an order | +| GET | `/api/v1/orders` | Orders grouped by customer (quantity and total per order, overall total). Paginated by customer, filterable by `customerId`/`productId` | +| GET | `/api/v1/orders/{id}` | Order detail with items | +| POST | `/api/v1/orders` | Create an order (`totalAmount` and `orderNumber` computed automatically) | +| PUT | `/api/v1/orders/{id}` | Update an order (replaces items, recomputes total) | | DELETE | `/api/v1/orders/{id}` | Delete an order | | GET | `/api/v1/customers/{id}/orders` | Orders for a given customer | ### Tasks -- [x] `Order` entity with `@ManyToOne` to `Customer` and `Product` -- [x] `OrderRepository` with join queries (`@Query` with `JOIN`), DTO projection for lists -- [x] DTOs `OrderRequest` (customerId, productId, quantity) / `OrderResponse` (`OrderCustomerResponse` + full `ProductResponse`), `CustomerOrdersResponse`/`OrderedProductResponse` for the grouped views -- [x] `OrderMapper` -- [x] `OrderService` interface and `OrderServiceImpl` implementation (in `service/impl`): computes `total = quantity * product.unitPrice`, checks that the customer and product exist -- [x] `OrderCreatedEvent` application event published after creation, consumed by `OrderCreatedEventListener` (e.g. business logging, future email notification) -- [x] `OrderController` returns `ResponseEntity>` -- [x] `CustomerResponse` returns the customer's orders and their total on both the list and the detail (see Response shapes above) -- [x] Unit tests (total computation, business rules) and integration tests +- [x] `OrderStatus` enum (`PENDING`, `CONFIRMED`, `CANCELLED`) +- [x] `OrderItem` entity with product snapshot (name + unit price at order time) +- [x] `Order` entity evolved: `totalAmount` (BigDecimal), `orderNumber`, `status`, `items` (cascade + orphanRemoval) +- [x] Migrations `V14` (multi-product schema + backfill) and `V15` (legacy `total` column nullable) +- [x] `OrderItemResponse` DTO, `OrderItemMapper` +- [x] `OrderResponse` updated with `status`, `total_amount`, `order_number`, `items` +- [x] `OrderCreatedEvent` enriched with `totalAmount` and `orderNumber` +- [x] `OrderRepository`: updated projections (17 fields), `findByIdWithDetails` with `JOIN FETCH` on items, `existsByCustomerId`, `existsByProductId`, `findByCustomerId` +- [x] `OrderServiceImpl`: `create`/`update` compute BigDecimal subtotal, generate `orderNumber`, build `OrderItem` before save +- [x] `OrderMapper`: `toResponse(Order)` with status enum-to-String expression; manual `toResponse(OrderProjection)` overload; `toOrderedProducts` helper; `OrderItemMapper` via `uses` +- [x] `CustomerResponse` returns the customer's orders and their total on both the list and the detail +- [x] Unit tests, repository tests (including `existsByCustomerId`, `existsByProductId`, `findByCustomerId`), controller tests, mapper tests ## feature/auth From 460a33dde2413b4b4d3c1de75c2b9ebb78d5f29d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:21:45 +0400 Subject: [PATCH 061/175] feat(flyway): add V16 migration for product_images table --- .../db/migration/V16__create_product_images.sql | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/main/resources/db/migration/V16__create_product_images.sql diff --git a/src/main/resources/db/migration/V16__create_product_images.sql b/src/main/resources/db/migration/V16__create_product_images.sql new file mode 100644 index 0000000..2b294dc --- /dev/null +++ b/src/main/resources/db/migration/V16__create_product_images.sql @@ -0,0 +1,16 @@ +CREATE TABLE product_images ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE, + image_url VARCHAR(500) NOT NULL, + alt_text VARCHAR(255), + is_primary BOOLEAN NOT NULL DEFAULT FALSE, + display_order INT NOT NULL DEFAULT 0, + created_at TIMESTAMP, + updated_at TIMESTAMP +); + +CREATE INDEX idx_product_images_product_id ON product_images(product_id); +-- At most one primary image per product +CREATE UNIQUE INDEX idx_product_images_primary + ON product_images(product_id) + WHERE is_primary = TRUE; From 3fe8bab86eaa8c23329d8130e50383bc045b6e94 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:22:09 +0400 Subject: [PATCH 062/175] feat(entity): add ProductImage entity with audit fields --- .../entity/ProductImage.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java b/src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java new file mode 100644 index 0000000..3f554ad --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java @@ -0,0 +1,73 @@ +package com.edgareldy.springboottutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +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.time.LocalDateTime; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +/** + * JPA entity mapping the {@code product_images} table. Each row holds + * the URL of one image file associated with a product, an optional + * alternative text for accessibility, an ordering hint, and a flag + * indicating whether this is the primary (cover) image. At most one + * image per product may have {@code isPrimary = true}, enforced by a + * partial unique index in the database (V16 migration). + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@Entity +@Table(name = "product_images") +@EntityListeners(AuditingEntityListener.class) +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ProductImage { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "product_id", nullable = false) + private Product product; + + @Column(name = "image_url", nullable = false, length = 500) + private String imageUrl; + + @Column(name = "alt_text", length = 255) + private String altText; + + @Column(name = "is_primary", nullable = false) + private boolean isPrimary; + + @Column(name = "display_order", nullable = false) + private int displayOrder; + + @CreatedDate + @Column(name = "created_at", updatable = false) + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(name = "updated_at") + private LocalDateTime updatedAt; +} From d76fcc5c5ded70171742078e3bb0bb7960fad649 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:23:13 +0400 Subject: [PATCH 063/175] feat(storage): add StorageProperties and StorageConfig for configurable upload directory --- .../config/StorageConfig.java | 20 ++++++++++++++++ .../config/StorageProperties.java | 23 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/config/StorageConfig.java create mode 100644 src/main/java/com/edgareldy/springboottutorial/config/StorageProperties.java diff --git a/src/main/java/com/edgareldy/springboottutorial/config/StorageConfig.java b/src/main/java/com/edgareldy/springboottutorial/config/StorageConfig.java new file mode 100644 index 0000000..e192274 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/config/StorageConfig.java @@ -0,0 +1,20 @@ +package com.edgareldy.springboottutorial.config; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * Registers {@link StorageProperties} so that the {@code app.storage} prefix + * in {@code application.yml} is bound and validated at startup. Keeping the + * registration here rather than on the main application class limits the scope + * of this feature to its own configuration class. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@Configuration +@EnableConfigurationProperties(StorageProperties.class) +public class StorageConfig { +} diff --git a/src/main/java/com/edgareldy/springboottutorial/config/StorageProperties.java b/src/main/java/com/edgareldy/springboottutorial/config/StorageProperties.java new file mode 100644 index 0000000..770dac9 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/config/StorageProperties.java @@ -0,0 +1,23 @@ +package com.edgareldy.springboottutorial.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; + +/** + * Type-safe configuration for the local file storage layer, bound from the + * {@code app.storage} prefix in {@code application.yml}. Registered via + * {@link org.springframework.boot.context.properties.EnableConfigurationProperties} + * on {@link StorageConfig} so the binding is local to this feature without + * requiring a package-level scan. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@ConfigurationProperties(prefix = "app.storage") +public record StorageProperties( + @DefaultValue("./uploads/products") String uploadDir, + @DefaultValue("5") int maxFileSizeMb +) { +} From 759632ac47c43b6f8d728c12f9607626c9033ada Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:23:16 +0400 Subject: [PATCH 064/175] feat(storage): add FileStorageService abstraction --- .../storage/FileStorageService.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/storage/FileStorageService.java diff --git a/src/main/java/com/edgareldy/springboottutorial/storage/FileStorageService.java b/src/main/java/com/edgareldy/springboottutorial/storage/FileStorageService.java new file mode 100644 index 0000000..dbe72db --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/storage/FileStorageService.java @@ -0,0 +1,36 @@ +package com.edgareldy.springboottutorial.storage; + +import org.springframework.web.multipart.MultipartFile; + +/** + * Abstraction over the file storage backend. The default implementation + * writes files to a local directory; a future implementation could delegate + * to an object-storage service (S3, GCS, etc.) without touching the callers. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +public interface FileStorageService { + + /** + * Validates and stores the uploaded file, returning its public URL path + * (e.g. {@code /uploads/products/550e8400-e29b-41d4-a716-446655440000.jpg}). + * + * @param file the uploaded file + * @param subdirectory target subdirectory under the configured upload root + * @return the public URL path of the stored file + * @throws com.edgareldy.springboottutorial.exception.BusinessRuleException + * if the file type or size is not acceptable + */ + String store(MultipartFile file, String subdirectory); + + /** + * Deletes the file identified by its public URL path. Silently ignores + * paths that do not map to an existing file. + * + * @param urlPath the URL path returned by {@link #store} + */ + void delete(String urlPath); +} From 03be458d6745606b1612e033e98d6dbeaadc981e Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:23:21 +0400 Subject: [PATCH 065/175] feat(storage): implement LocalFileStorageService with MIME and size validation Stores uploaded files under the configured upload-dir with a UUID filename. Validates extension (jpg/jpeg/png/webp), MIME type (image/*), and file size against StorageProperties.maxFileSizeMb. Guards against path traversal on both the subdirectory parameter and the delete URL path. --- .../storage/LocalFileStorageService.java | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/storage/LocalFileStorageService.java diff --git a/src/main/java/com/edgareldy/springboottutorial/storage/LocalFileStorageService.java b/src/main/java/com/edgareldy/springboottutorial/storage/LocalFileStorageService.java new file mode 100644 index 0000000..9658a71 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/storage/LocalFileStorageService.java @@ -0,0 +1,129 @@ +package com.edgareldy.springboottutorial.storage; + +import com.edgareldy.springboottutorial.config.StorageProperties; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; +import java.io.IOException; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Set; +import java.util.UUID; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +/** + * {@link FileStorageService} implementation that writes files to a local + * directory on the server's filesystem. The upload root is configured via + * {@link StorageProperties#uploadDir()}. Files are named with a UUID to avoid + * collisions and path-traversal attacks; the original filename is never used + * in the stored path. Acceptable formats are limited to JPEG, PNG, and WebP. + * Files larger than {@link StorageProperties#maxFileSizeMb()} are rejected. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@Service +public class LocalFileStorageService implements FileStorageService { + + private static final Set ALLOWED_EXTENSIONS = Set.of("jpg", "jpeg", "png", "webp"); + private static final Set ALLOWED_CONTENT_TYPES = Set.of( + "image/jpeg", "image/png", "image/webp"); + + private final StorageProperties storageProperties; + + public LocalFileStorageService(StorageProperties storageProperties) { + this.storageProperties = storageProperties; + } + + @Override + public String store(MultipartFile file, String subdirectory) { + validateFile(file); + + String extension = getExtension(file.getOriginalFilename()); + String filename = UUID.randomUUID() + "." + extension; + + Path uploadRoot = Paths.get(storageProperties.uploadDir()).toAbsolutePath().normalize(); + Path targetDir = uploadRoot.resolve(subdirectory).normalize(); + + // Guard against path traversal via the subdirectory parameter + if (!targetDir.startsWith(uploadRoot)) { + throw new BusinessRuleException("Invalid storage subdirectory"); + } + + try { + Files.createDirectories(targetDir); + Path targetFile = targetDir.resolve(filename); + Files.copy(file.getInputStream(), targetFile); + } catch (IOException e) { + throw new BusinessRuleException("Failed to store file: " + e.getMessage()); + } + + return "/uploads/" + subdirectory + "/" + filename; + } + + @Override + public void delete(String urlPath) { + if (urlPath == null || !urlPath.startsWith("/uploads/")) { + return; + } + String relativePath = urlPath.substring("/uploads/".length()); + Path uploadRoot = Paths.get(storageProperties.uploadDir()).toAbsolutePath().normalize(); + Path target = uploadRoot.resolve(relativePath).normalize(); + + // Only delete files that live under the configured upload root + if (!target.startsWith(uploadRoot)) { + return; + } + try { + Files.deleteIfExists(target); + } catch (IOException e) { + // Silently ignore deletion failures + } + } + + private void validateFile(MultipartFile file) { + if (file == null || file.isEmpty()) { + throw new BusinessRuleException("File must not be empty"); + } + + long maxBytes = (long) storageProperties.maxFileSizeMb() * 1024 * 1024; + if (file.getSize() > maxBytes) { + throw new BusinessRuleException( + "File size exceeds the maximum allowed size of " + + storageProperties.maxFileSizeMb() + " MB"); + } + + String extension = getExtension(file.getOriginalFilename()); + if (!ALLOWED_EXTENSIONS.contains(extension)) { + throw new BusinessRuleException( + "File type not allowed. Accepted types: jpg, jpeg, png, webp"); + } + + String contentType = resolveContentType(file); + if (!ALLOWED_CONTENT_TYPES.contains(contentType)) { + throw new BusinessRuleException( + "File MIME type not allowed. Accepted types: image/jpeg, image/png, image/webp"); + } + } + + private String getExtension(String filename) { + if (filename == null || !filename.contains(".")) { + return ""; + } + return filename.substring(filename.lastIndexOf('.') + 1).toLowerCase(); + } + + private String resolveContentType(MultipartFile file) { + String declared = file.getContentType(); + if (declared != null && !declared.isBlank()) { + return declared.toLowerCase(); + } + // Fall back to probing when the browser does not declare a content type + String probed = URLConnection.guessContentTypeFromName( + file.getOriginalFilename() != null ? file.getOriginalFilename() : ""); + return probed != null ? probed.toLowerCase() : ""; + } +} From a3a52004af8cd1ac93f6ac62fc06b08f3e02b307 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:28:50 +0400 Subject: [PATCH 066/175] fix(entity): rename isPrimary to primary in ProductImage to avoid MapStruct boolean getter naming conflict --- .../com/edgareldy/springboottutorial/entity/ProductImage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java b/src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java index 3f554ad..1c76e36 100644 --- a/src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java +++ b/src/main/java/com/edgareldy/springboottutorial/entity/ProductImage.java @@ -58,7 +58,7 @@ public class ProductImage { private String altText; @Column(name = "is_primary", nullable = false) - private boolean isPrimary; + private boolean primary; @Column(name = "display_order", nullable = false) private int displayOrder; From 8e30caeeb28ea1bfebead50c56836e80ae8cea5d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:28:53 +0400 Subject: [PATCH 067/175] feat(dto): add ProductImageResponse DTO --- .../dto/product/ProductImageResponse.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/product/ProductImageResponse.java diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductImageResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductImageResponse.java new file mode 100644 index 0000000..14cd897 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductImageResponse.java @@ -0,0 +1,31 @@ +package com.edgareldy.springboottutorial.dto.product; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Representation of a {@link com.edgareldy.springboottutorial.entity.ProductImage} + * returned by the API. Fields are exposed in snake_case via explicit + * {@link JsonProperty} annotations while the Java record fields remain in + * camelCase, keeping the same convention as the other response DTOs. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +public record ProductImageResponse( + Long id, + + @JsonProperty("image_url") + String imageUrl, + + @JsonProperty("alt_text") + String altText, + + @JsonProperty("is_primary") + boolean primary, + + @JsonProperty("display_order") + int displayOrder +) { +} From 478dcf0f35e767114996528c8dfbc0babc8a336d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:28:56 +0400 Subject: [PATCH 068/175] feat(mapper): add ProductImageMapper --- .../mapper/ProductImageMapper.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/mapper/ProductImageMapper.java diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductImageMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductImageMapper.java new file mode 100644 index 0000000..577d472 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductImageMapper.java @@ -0,0 +1,22 @@ +package com.edgareldy.springboottutorial.mapper; + +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; +import com.edgareldy.springboottutorial.entity.ProductImage; +import org.mapstruct.Mapper; + +/** + * MapStruct mapper converting {@link ProductImage} entities to + * {@link ProductImageResponse} DTOs. Used by {@link ProductImageServiceImpl} + * when returning image metadata and by {@link ProductServiceImpl#findById} + * when building the full product detail response. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@Mapper(componentModel = "spring") +public interface ProductImageMapper { + + ProductImageResponse toResponse(ProductImage productImage); +} From a855bacefb8c1667c2a14ec3a87e42868dccc9ae Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:28:59 +0400 Subject: [PATCH 069/175] feat(repository): add ProductImageRepository --- .../repository/ProductImageRepository.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/repository/ProductImageRepository.java diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/ProductImageRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/ProductImageRepository.java new file mode 100644 index 0000000..7a5072a --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/repository/ProductImageRepository.java @@ -0,0 +1,23 @@ +package com.edgareldy.springboottutorial.repository; + +import com.edgareldy.springboottutorial.entity.ProductImage; +import java.util.List; +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Spring Data repository for {@link ProductImage}. Provides derived queries + * for the two most common access patterns: loading all images of a product + * (ordered by display order) and finding the primary image of a product. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +public interface ProductImageRepository extends JpaRepository { + + List findByProductIdOrderByDisplayOrderAsc(Long productId); + + Optional findByProductIdAndPrimaryTrue(Long productId); +} From 22a9bf3094667ae8e8904aa013ca52187824f70c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:29:33 +0400 Subject: [PATCH 070/175] refactor(mapper): add images mapping to ProductMapper.toResponse and toDetailResponse overload --- .../mapper/ProductMapper.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java index e3facd1..ba0fc19 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java @@ -1,9 +1,11 @@ package com.edgareldy.springboottutorial.mapper; +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; +import java.util.List; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; @@ -15,6 +17,9 @@ * parameter: this mapper only assigns it, so the service never calls a * setter itself. {@code active} is ignored on writes so that create and update * operations cannot inadvertently overwrite the flag via {@link ProductRequest}. + * {@code images} is always set to an empty list by {@link #toResponse(Product)}; + * the detail view uses {@link #toDetailResponse(Product, List)} which accepts + * the caller-provided image list to avoid loading images on the list path. *

* Created edgar.muhamyangabo on 7/4/26 * Author : edgar.muhamyangabo @@ -26,8 +31,20 @@ public interface ProductMapper { @Mapping(source = "category.id", target = "categoryId") @Mapping(source = "category.categoryName", target = "categoryName") + @Mapping(target = "images", expression = "java(java.util.List.of())") ProductResponse toResponse(Product product); + /** + * Builds a full detail {@link ProductResponse} with the provided image list. + * Images are loaded by the service and passed here rather than fetched + * via a lazy association, keeping this mapper free of repository calls. + */ + default ProductResponse toDetailResponse(Product product, List images) { + ProductResponse base = toResponse(product); + return new ProductResponse(base.id(), base.productName(), base.unitPrice(), + base.description(), base.active(), base.categoryId(), base.categoryName(), images); + } + @Mapping(target = "id", ignore = true) @Mapping(target = "category", source = "category") @Mapping(target = "version", ignore = true) From cba722b82eb980d285df24f6b3c98cc1e6595fab Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:34:26 +0400 Subject: [PATCH 071/175] feat(service): add ProductImageService interface --- .../service/ProductImageService.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/service/ProductImageService.java diff --git a/src/main/java/com/edgareldy/springboottutorial/service/ProductImageService.java b/src/main/java/com/edgareldy/springboottutorial/service/ProductImageService.java new file mode 100644 index 0000000..69e65fc --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/ProductImageService.java @@ -0,0 +1,22 @@ +package com.edgareldy.springboottutorial.service; + +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; +import org.springframework.web.multipart.MultipartFile; + +/** + * Contract for product image operations. Callers supply a product id and an + * image file; this service validates ownership, delegates file I/O to + * {@link com.edgareldy.springboottutorial.storage.FileStorageService}, and + * enforces the "at most one primary image per product" invariant. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +public interface ProductImageService { + + ProductImageResponse addImage(Long productId, MultipartFile file, String altText, boolean isPrimary); + + void deleteImage(Long productId, Long imageId); +} From fafdd8c48fa1b976b7efe685e0408dec057f3ca3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:34:28 +0400 Subject: [PATCH 072/175] feat(service): add ProductImageServiceImpl --- .../service/impl/ProductImageServiceImpl.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java new file mode 100644 index 0000000..9024cfa --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java @@ -0,0 +1,76 @@ +package com.edgareldy.springboottutorial.service.impl; + +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; +import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.entity.ProductImage; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.mapper.ProductImageMapper; +import com.edgareldy.springboottutorial.repository.ProductImageRepository; +import com.edgareldy.springboottutorial.repository.ProductRepository; +import com.edgareldy.springboottutorial.service.ProductImageService; +import com.edgareldy.springboottutorial.storage.FileStorageService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +/** + * Default {@link ProductImageService} implementation. File I/O is delegated to + * {@link FileStorageService}, keeping this class free of storage concerns. + * When {@code isPrimary} is true, any existing primary image for the same + * product is cleared first within the same transaction, upholding the + * partial unique index on {@code (product_id) WHERE is_primary = TRUE}. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@Service +@RequiredArgsConstructor +public class ProductImageServiceImpl implements ProductImageService { + + private static final String PRODUCTS_SUBDIR = "products"; + + private final ProductRepository productRepository; + private final ProductImageRepository productImageRepository; + private final FileStorageService fileStorageService; + private final ProductImageMapper productImageMapper; + + @Override + @Transactional + public ProductImageResponse addImage(Long productId, MultipartFile file, String altText, boolean isPrimary) { + Product product = productRepository.findById(productId) + .orElseThrow(() -> new ResourceNotFoundException("Product not found with id " + productId)); + + if (isPrimary) { + productImageRepository.findByProductIdAndPrimaryTrue(productId) + .ifPresent(existing -> { + existing.setPrimary(false); + productImageRepository.save(existing); + }); + } + + String imageUrl = fileStorageService.store(file, PRODUCTS_SUBDIR); + ProductImage image = ProductImage.builder() + .product(product) + .imageUrl(imageUrl) + .altText(altText) + .primary(isPrimary) + .displayOrder(0) + .build(); + return productImageMapper.toResponse(productImageRepository.save(image)); + } + + @Override + @Transactional + public void deleteImage(Long productId, Long imageId) { + ProductImage image = productImageRepository.findById(imageId) + .orElseThrow(() -> new ResourceNotFoundException("Image not found with id " + imageId)); + if (!image.getProduct().getId().equals(productId)) { + throw new ResourceNotFoundException("Image " + imageId + " does not belong to product " + productId); + } + fileStorageService.delete(image.getImageUrl()); + productImageRepository.delete(image); + } +} From 1c4541683c048cfc91a9cf1164fe5a27d4b89a2c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:34:47 +0400 Subject: [PATCH 073/175] refactor(service): load images in ProductServiceImpl.findById via ProductImageRepository --- .../service/impl/ProductServiceImpl.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java index fbc198d..7dde96c 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java @@ -1,17 +1,21 @@ package com.edgareldy.springboottutorial.service.impl; import com.edgareldy.springboottutorial.dto.common.PageResponse; +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.mapper.ProductImageMapper; import com.edgareldy.springboottutorial.mapper.ProductMapper; import com.edgareldy.springboottutorial.repository.CategoryRepository; +import com.edgareldy.springboottutorial.repository.ProductImageRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import com.edgareldy.springboottutorial.repository.specification.ProductSpecifications; import com.edgareldy.springboottutorial.service.ProductService; import java.math.BigDecimal; +import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; @@ -47,6 +51,8 @@ public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; private final CategoryRepository categoryRepository; private final ProductMapper productMapper; + private final ProductImageRepository productImageRepository; + private final ProductImageMapper productImageMapper; @Override public PageResponse findAll( @@ -75,7 +81,12 @@ public PageResponse findAll( public ProductResponse findById(Long id) { Product product = productRepository.findByIdWithCategory(id) .orElseThrow(() -> new ResourceNotFoundException("Product not found with id " + id)); - return productMapper.toResponse(product); + List images = productImageRepository + .findByProductIdOrderByDisplayOrderAsc(id) + .stream() + .map(productImageMapper::toResponse) + .toList(); + return productMapper.toDetailResponse(product, images); } @Override From 171e7421d411850a7c17b2f0366bf3610e9a5dd4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:35:05 +0400 Subject: [PATCH 074/175] refactor(controller): add image upload and delete endpoints to ProductController --- .../controller/ProductController.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java b/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java index 7d0a886..cfa6cb6 100644 --- a/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java +++ b/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java @@ -2,8 +2,10 @@ import com.edgareldy.springboottutorial.dto.common.ApiResponse; import com.edgareldy.springboottutorial.dto.common.PageResponse; +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import com.edgareldy.springboottutorial.service.ProductImageService; import com.edgareldy.springboottutorial.service.ProductService; import jakarta.validation.Valid; import java.math.BigDecimal; @@ -20,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; /** * REST controller exposing CRUD endpoints for products. Delegates every @@ -36,6 +39,7 @@ public class ProductController { private final ProductService productService; + private final ProductImageService productImageService; @GetMapping public ResponseEntity>> findAll( @@ -72,4 +76,23 @@ public ResponseEntity> delete(@PathVariable Long id) { productService.delete(id); return ResponseEntity.ok(ApiResponse.success(null, "Product deleted successfully")); } + + @PostMapping("/{id}/images") + public ResponseEntity> addImage( + @PathVariable Long id, + @RequestParam("file") MultipartFile file, + @RequestParam(value = "altText", required = false) String altText, + @RequestParam(value = "isPrimary", defaultValue = "false") boolean isPrimary) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(ApiResponse.success( + productImageService.addImage(id, file, altText, isPrimary), + "Image uploaded successfully")); + } + + @DeleteMapping("/{id}/images/{imageId}") + public ResponseEntity> deleteImage( + @PathVariable Long id, @PathVariable Long imageId) { + productImageService.deleteImage(id, imageId); + return ResponseEntity.ok(ApiResponse.success(null, "Image deleted successfully")); + } } From 8220c3e410746005ec2d3446aeea90862be74d2b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:37:27 +0400 Subject: [PATCH 075/175] refactor(dto): add images list to ProductResponse and update all call sites ProductResponse gains an 8th field List images. ProductServiceImpl.findById now populates it via ProductImageRepository; the list path (findAll) keeps images empty via the unchanged toResponse(). ProductControllerTest and CategoryControllerTest pass List.of() at every 7-arg constructor site. ProductServiceImplTest and ProductServiceCacheTest gain @Mock/@MockitoBean for ProductImageRepository and ProductImageMapper, and their findById assertions switch from toResponse to toDetailResponse. Grouped with the tests because the record change breaks compilation at every call site, making separate commits meaningless here. --- .../dto/product/ProductResponse.java | 5 ++- .../controller/CategoryControllerTest.java | 2 +- .../controller/ProductControllerTest.java | 42 ++++++++++++++++--- .../service/impl/ProductServiceCacheTest.java | 21 +++++++--- .../service/impl/ProductServiceImplTest.java | 15 +++++-- 5 files changed, 69 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java index 20359f3..8443866 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/product/ProductResponse.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; +import java.util.List; /** * Representation of a {@link com.edgareldy.springboottutorial.entity.Product} @@ -35,6 +36,8 @@ public record ProductResponse( Long categoryId, @JsonProperty("category_name") - String categoryName + String categoryName, + + List images ) { } diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java index 06b790c..6c0d925 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java @@ -75,7 +75,7 @@ void _02_ShouldReturnCategory_WhenCategoryFound() throws Exception { @Test void _03_ShouldIncludeProducts_WhenFindingCategoryById() throws Exception { - ProductResponse keyboard = new ProductResponse(10L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + ProductResponse keyboard = new ProductResponse(10L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); when(categoryService.findById(1L)) .thenReturn(new CategoryResponse(1L, "Electronics", null, null, List.of(keyboard))); diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java index 1b063fe..41a1912 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java @@ -14,9 +14,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.edgareldy.springboottutorial.dto.common.PageResponse; +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.service.ProductImageService; import com.edgareldy.springboottutorial.service.ProductService; import java.math.BigDecimal; import java.util.List; @@ -24,11 +26,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.mock.web.MockMultipartFile; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.http.MediaType; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; + /** * MockMvc integration tests for {@link ProductController}, with * {@link ProductService} mocked. Security filters are disabled since @@ -52,10 +57,13 @@ class ProductControllerTest { @MockitoBean private ProductService productService; + @MockitoBean + private ProductImageService productImageService; + @Test void _01_ShouldPassNullCategoryId_WhenNoFilterGiven() throws Exception { ProductResponse product = - new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); when(productService.findAll(isNull(), isNull(), isNull(), isNull(), any())).thenReturn(page); @@ -67,7 +75,7 @@ void _01_ShouldPassNullCategoryId_WhenNoFilterGiven() throws Exception { @Test void _02_ShouldForwardCategoryFilter_WhenCategoryIdGiven() throws Exception { ProductResponse product = - new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); when(productService.findAll(eq(1L), isNull(), isNull(), isNull(), any())).thenReturn(page); @@ -79,7 +87,7 @@ void _02_ShouldForwardCategoryFilter_WhenCategoryIdGiven() throws Exception { @Test void _03_ShouldForwardNameAndPriceFilters_WhenAdvancedFiltersGiven() throws Exception { ProductResponse product = - new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); when(productService.findAll(isNull(), eq("key"), eq(new BigDecimal("50")), eq(new BigDecimal("100")), any())) .thenReturn(page); @@ -105,7 +113,7 @@ void _04_ShouldReturn404_WhenProductMissing() throws Exception { void _05_ShouldReturn201_WhenCreateRequestValid() throws Exception { ProductRequest request = new ProductRequest(1L, "Keyboard", null, new BigDecimal("79.99")); when(productService.create(any())) - .thenReturn(new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics")); + .thenReturn(new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of())); mockMvc.perform(post("/api/v1/products") .contentType(MediaType.APPLICATION_JSON) @@ -141,7 +149,7 @@ void _08_ShouldReturn200_WhenUpdateRequestValid() throws Exception { ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99")); when(productService.update(eq(1L), any())) .thenReturn(new ProductResponse( - 1L, "Mechanical Keyboard", new BigDecimal("99.99"), null, true, 1L, "Electronics")); + 1L, "Mechanical Keyboard", new BigDecimal("99.99"), null, true, 1L, "Electronics", List.of())); mockMvc.perform(put("/api/v1/products/1") .contentType(MediaType.APPLICATION_JSON) @@ -195,10 +203,32 @@ void _12_ShouldReturn404_WhenProductMissingOnDelete() throws Exception { @Test void _13_ShouldSerializeActiveFalse_WhenProductIsInactive() throws Exception { when(productService.findById(2L)) - .thenReturn(new ProductResponse(2L, "Legacy Keyboard", new BigDecimal("49.99"), "Discontinued model", false, 1L, "Electronics")); + .thenReturn(new ProductResponse(2L, "Legacy Keyboard", new BigDecimal("49.99"), "Discontinued model", false, 1L, "Electronics", List.of())); mockMvc.perform(get("/api/v1/products/2")) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.active").value(false)); } + + @Test + void _14_ShouldReturn201_WhenImageUploaded() throws Exception { + ProductImageResponse imageResponse = new ProductImageResponse(1L, "/uploads/products/uuid.jpg", null, true, 0); + when(productImageService.addImage(eq(1L), any(), any(), eq(true))).thenReturn(imageResponse); + + MockMultipartFile file = new MockMultipartFile( + "file", "photo.jpg", MediaType.IMAGE_JPEG_VALUE, "jpg-bytes".getBytes()); + + mockMvc.perform(multipart("/api/v1/products/1/images") + .file(file) + .param("isPrimary", "true")) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.data.is_primary").value(true)); + } + + @Test + void _15_ShouldReturn200_WhenImageDeleted() throws Exception { + mockMvc.perform(delete("/api/v1/products/1/images/10")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } } diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java index 2f3ffee..df49b68 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java @@ -1,16 +1,20 @@ package com.edgareldy.springboottutorial.service.impl; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import java.util.List; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.mapper.ProductImageMapper; import com.edgareldy.springboottutorial.mapper.ProductMapper; import com.edgareldy.springboottutorial.repository.CategoryRepository; +import com.edgareldy.springboottutorial.repository.ProductImageRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import com.edgareldy.springboottutorial.service.ProductService; import java.math.BigDecimal; @@ -70,6 +74,12 @@ CacheManager cacheManager() { @MockitoBean private ProductMapper productMapper; + @MockitoBean + private ProductImageRepository productImageRepository; + + @MockitoBean + private ProductImageMapper productImageMapper; + @BeforeEach void clearCache() { Cache products = cacheManager.getCache("products"); @@ -88,9 +98,9 @@ private static Product sampleProduct() { void _01_ShouldHitRepositoryOnce_WhenFindByIdCalledTwice() { Product product = sampleProduct(); ProductResponse response = - new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); - when(productMapper.toResponse(product)).thenReturn(response); + when(productMapper.toDetailResponse(eq(product), any())).thenReturn(response); productService.findById(1L); productService.findById(1L); @@ -102,8 +112,9 @@ void _01_ShouldHitRepositoryOnce_WhenFindByIdCalledTwice() { void _02_ShouldEvictCache_WhenProductUpdated() { Product product = sampleProduct(); ProductResponse response = - new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); + when(productMapper.toDetailResponse(eq(product), any())).thenReturn(response); when(productMapper.toResponse(product)).thenReturn(response); when(productRepository.findById(1L)).thenReturn(Optional.of(product)); when(categoryRepository.findById(1L)).thenReturn(Optional.of(product.getCategory())); @@ -120,9 +131,9 @@ void _02_ShouldEvictCache_WhenProductUpdated() { void _03_ShouldEvictCache_WhenProductDeleted() { Product product = sampleProduct(); ProductResponse response = - new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); - when(productMapper.toResponse(product)).thenReturn(response); + when(productMapper.toDetailResponse(eq(product), any())).thenReturn(response); when(productRepository.existsById(1L)).thenReturn(true); productService.findById(1L); diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java index d05bca8..59eb7fa 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImplTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -14,8 +15,10 @@ import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.mapper.ProductImageMapper; import com.edgareldy.springboottutorial.mapper.ProductMapper; import com.edgareldy.springboottutorial.repository.CategoryRepository; +import com.edgareldy.springboottutorial.repository.ProductImageRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import java.math.BigDecimal; import java.util.List; @@ -52,6 +55,12 @@ class ProductServiceImplTest { @Mock private ProductMapper productMapper; + @Mock + private ProductImageRepository productImageRepository; + + @Mock + private ProductImageMapper productImageMapper; + @InjectMocks private ProductServiceImpl productService; @@ -64,7 +73,7 @@ void setUp() { category = Category.builder().id(1L).categoryName("Electronics").build(); product = Product.builder().id(1L).category(category).productName("Keyboard") .unitPrice(new BigDecimal("79.99")).active(true).build(); - productResponse = new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics"); + productResponse = new ProductResponse(1L, "Keyboard", new BigDecimal("79.99"), null, true, 1L, "Electronics", List.of()); } @Test @@ -109,7 +118,7 @@ void _03_ShouldUseSpecification_WhenAdvancedFilterGiven() { @Test void _04_ShouldReturnResponse_WhenProductFound() { when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); - when(productMapper.toResponse(product)).thenReturn(productResponse); + when(productMapper.toDetailResponse(eq(product), anyList())).thenReturn(productResponse); assertThat(productService.findById(1L)).isEqualTo(productResponse); } @@ -148,7 +157,7 @@ void _07_ShouldThrowNotFound_WhenCategoryMissingOnCreate() { void _08_ShouldResolveCategoryAndSave_WhenUpdatingProduct() { ProductRequest request = new ProductRequest(1L, "Mechanical Keyboard", null, new BigDecimal("99.99")); ProductResponse updatedResponse = - new ProductResponse(1L, "Mechanical Keyboard", new BigDecimal("99.99"), null, true, 1L, "Electronics"); + new ProductResponse(1L, "Mechanical Keyboard", new BigDecimal("99.99"), null, true, 1L, "Electronics", List.of()); when(productRepository.findById(1L)).thenReturn(Optional.of(product)); when(categoryRepository.findById(1L)).thenReturn(Optional.of(category)); when(productRepository.save(product)).thenReturn(product); From b57bffa4949a0c962c9d013be31d1d2785a50b7c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:38:09 +0400 Subject: [PATCH 076/175] test(service): add ProductImageServiceImplTest --- .../impl/ProductImageServiceImplTest.java | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java new file mode 100644 index 0000000..c547980 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java @@ -0,0 +1,149 @@ +package com.edgareldy.springboottutorial.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; +import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.entity.ProductImage; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.mapper.ProductImageMapper; +import com.edgareldy.springboottutorial.repository.ProductImageRepository; +import com.edgareldy.springboottutorial.repository.ProductRepository; +import com.edgareldy.springboottutorial.storage.FileStorageService; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.http.MediaType; + +/** + * Unit tests for {@link ProductImageServiceImpl}, with all dependencies mocked. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +@ExtendWith(MockitoExtension.class) +class ProductImageServiceImplTest { + + @Mock + private ProductRepository productRepository; + + @Mock + private ProductImageRepository productImageRepository; + + @Mock + private FileStorageService fileStorageService; + + @Mock + private ProductImageMapper productImageMapper; + + @InjectMocks + private ProductImageServiceImpl productImageService; + + private Product product; + private MockMultipartFile file; + + @BeforeEach + void setUp() { + product = Product.builder().id(1L).productName("Keyboard").build(); + file = new MockMultipartFile( + "file", "photo.jpg", MediaType.IMAGE_JPEG_VALUE, "jpg-bytes".getBytes()); + } + + @Test + void _01_ShouldAddImage_WhenProductExists() { + ProductImage saved = ProductImage.builder().id(10L).product(product) + .imageUrl("/uploads/products/uuid.jpg").primary(false).displayOrder(0).build(); + ProductImageResponse response = new ProductImageResponse(10L, "/uploads/products/uuid.jpg", null, false, 0); + + when(productRepository.findById(1L)).thenReturn(Optional.of(product)); + when(fileStorageService.store(file, "products")).thenReturn("/uploads/products/uuid.jpg"); + when(productImageRepository.save(any(ProductImage.class))).thenReturn(saved); + when(productImageMapper.toResponse(saved)).thenReturn(response); + + ProductImageResponse result = productImageService.addImage(1L, file, null, false); + + assertThat(result).isEqualTo(response); + verify(fileStorageService).store(file, "products"); + } + + @Test + void _02_ShouldThrowNotFound_WhenProductMissingOnAdd() { + when(productRepository.findById(99L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> productImageService.addImage(99L, file, null, false)) + .isInstanceOf(ResourceNotFoundException.class); + + verify(fileStorageService, never()).store(any(), any()); + } + + @Test + void _03_ShouldUnsetOldPrimary_WhenAddingNewPrimaryImage() { + ProductImage existingPrimary = ProductImage.builder().id(5L).product(product) + .imageUrl("/uploads/products/old.jpg").primary(true).displayOrder(0).build(); + ProductImage saved = ProductImage.builder().id(10L).product(product) + .imageUrl("/uploads/products/new.jpg").primary(true).displayOrder(0).build(); + ProductImageResponse response = new ProductImageResponse(10L, "/uploads/products/new.jpg", null, true, 0); + + when(productRepository.findById(1L)).thenReturn(Optional.of(product)); + when(productImageRepository.findByProductIdAndPrimaryTrue(1L)) + .thenReturn(Optional.of(existingPrimary)); + when(productImageRepository.save(existingPrimary)).thenReturn(existingPrimary); + when(fileStorageService.store(file, "products")).thenReturn("/uploads/products/new.jpg"); + when(productImageRepository.save(any(ProductImage.class))).thenReturn(saved); + when(productImageMapper.toResponse(saved)).thenReturn(response); + + productImageService.addImage(1L, file, null, true); + + assertThat(existingPrimary.isPrimary()).isFalse(); + verify(productImageRepository).save(existingPrimary); + } + + @Test + void _04_ShouldDeleteImage_WhenImageBelongsToProduct() { + ProductImage image = ProductImage.builder().id(10L).product(product) + .imageUrl("/uploads/products/uuid.jpg").build(); + + when(productImageRepository.findById(10L)).thenReturn(Optional.of(image)); + + productImageService.deleteImage(1L, 10L); + + verify(fileStorageService).delete("/uploads/products/uuid.jpg"); + verify(productImageRepository).delete(image); + } + + @Test + void _05_ShouldThrowNotFound_WhenImageMissingOnDelete() { + when(productImageRepository.findById(99L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> productImageService.deleteImage(1L, 99L)) + .isInstanceOf(ResourceNotFoundException.class); + + verify(fileStorageService, never()).delete(any()); + } + + @Test + void _06_ShouldThrowNotFound_WhenImageDoesNotBelongToProduct() { + Product otherProduct = Product.builder().id(99L).productName("Mouse").build(); + ProductImage image = ProductImage.builder().id(10L).product(otherProduct) + .imageUrl("/uploads/products/uuid.jpg").build(); + + when(productImageRepository.findById(10L)).thenReturn(Optional.of(image)); + + assertThatThrownBy(() -> productImageService.deleteImage(1L, 10L)) + .isInstanceOf(ResourceNotFoundException.class); + + verify(fileStorageService, never()).delete(any()); + } +} From 5a984db0fd61c8c3566ced3fb34028eb46912bcb Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:38:09 +0400 Subject: [PATCH 077/175] test(storage): add LocalFileStorageServiceTest --- .../storage/LocalFileStorageServiceTest.java | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java b/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java new file mode 100644 index 0000000..d2ed58e --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java @@ -0,0 +1,111 @@ +package com.edgareldy.springboottutorial.storage; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.edgareldy.springboottutorial.config.StorageProperties; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; + +/** + * Unit tests for {@link LocalFileStorageService}. Uses JUnit 5's + * {@link TempDir} to get an isolated directory for each test class run, + * avoiding leftover files from one test affecting another. + *

+ * Created edgar.muhamyangabo on 11/17/26 + * Author : edgar.muhamyangabo + * Date : 11/17/26 + * Project : spring-boot-tutorial + */ +class LocalFileStorageServiceTest { + + @TempDir + Path tempDir; + + private LocalFileStorageService storageService; + + @BeforeEach + void setUp() { + StorageProperties props = new StorageProperties(tempDir.toString(), 5); + storageService = new LocalFileStorageService(props); + } + + @Test + void _01_ShouldStoreFile_WhenValidJpeg() { + MockMultipartFile file = new MockMultipartFile( + "file", "photo.jpg", MediaType.IMAGE_JPEG_VALUE, "jpg-bytes".getBytes()); + + String url = storageService.store(file, "products"); + + assertThat(url).startsWith("/uploads/products/").endsWith(".jpg"); + // Verify the file actually landed on disk + String filename = url.substring("/uploads/products/".length()); + assertThat(Files.exists(tempDir.resolve("products").resolve(filename))).isTrue(); + } + + @Test + void _02_ShouldRejectFile_WhenExtensionNotAllowed() { + MockMultipartFile gif = new MockMultipartFile( + "file", "animation.gif", "image/gif", "gif-bytes".getBytes()); + + assertThatThrownBy(() -> storageService.store(gif, "products")) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("File type not allowed"); + } + + @Test + void _03_ShouldRejectFile_WhenTooLarge() { + // 6 MB > 5 MB limit + byte[] oversized = new byte[6 * 1024 * 1024]; + MockMultipartFile file = new MockMultipartFile( + "file", "big.jpg", MediaType.IMAGE_JPEG_VALUE, oversized); + + assertThatThrownBy(() -> storageService.store(file, "products")) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("exceeds the maximum"); + } + + @Test + void _04_ShouldRejectFile_WhenEmpty() { + MockMultipartFile empty = new MockMultipartFile( + "file", "empty.jpg", MediaType.IMAGE_JPEG_VALUE, new byte[0]); + + assertThatThrownBy(() -> storageService.store(empty, "products")) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("must not be empty"); + } + + @Test + void _05_ShouldRejectSubdirectory_WhenPathTraversalAttempted() { + MockMultipartFile file = new MockMultipartFile( + "file", "photo.jpg", MediaType.IMAGE_JPEG_VALUE, "jpg-bytes".getBytes()); + + assertThatThrownBy(() -> storageService.store(file, "../secret")) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("Invalid storage subdirectory"); + } + + @Test + void _06_ShouldDeleteFile_WhenItExists() throws Exception { + MockMultipartFile file = new MockMultipartFile( + "file", "photo.jpg", MediaType.IMAGE_JPEG_VALUE, "jpg-bytes".getBytes()); + String url = storageService.store(file, "products"); + + storageService.delete(url); + + String filename = url.substring("/uploads/products/".length()); + assertThat(Files.exists(tempDir.resolve("products").resolve(filename))).isFalse(); + } + + @Test + void _07_ShouldIgnoreDelete_WhenUrlDoesNotStartWithUploads() { + // Should not throw + storageService.delete("/static/logo.png"); + } +} From bc86c4508df5e3f6ad796bff67ef270c7cb54997 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:38:20 +0400 Subject: [PATCH 078/175] feat(config): add app.storage configuration to application.yml --- src/main/resources/application.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ba46ca5..28cdd82 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -7,3 +7,8 @@ spring: server: port: 8080 + +app: + storage: + upload-dir: ${APP_STORAGE_UPLOAD_DIR:./uploads/products} + max-file-size-mb: 5 From 3badcc667d607f52e917c0c0d4a495adf259bc8b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:38:21 +0400 Subject: [PATCH 079/175] chore: add APP_STORAGE_UPLOAD_DIR to .env.example --- .env.example | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.env.example b/.env.example index 1b37200..fcc3748 100644 --- a/.env.example +++ b/.env.example @@ -17,3 +17,5 @@ MAIL_HOST=mailhog MAIL_PORT=1025 MAIL_SMTP_AUTH=false MAIL_SMTP_STARTTLS=false + +APP_STORAGE_UPLOAD_DIR=./uploads/products From e87feb06d993731e3f690295dd5db15589ce9867 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:39:10 +0400 Subject: [PATCH 080/175] docs(readme): add feature/product-images section Documents the new branch: V16 migration, ProductImage entity, FileStorageService abstraction with LocalFileStorageService, ProductImageService, updated ProductResponse (images populated on detail only), endpoints POST/DELETE /{id}/images. Includes configuration notes explaining the primary-flag naming convention, V16 numbering rationale, and the cache behaviour when images are added or removed. --- README.md | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/README.md b/README.md index a4cc7d9..532cacc 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ Repository: https://github.com/EdgarEldy/spring-boot-tutorial - [Spring AOP](#spring-aop) - [feature/core-architecture](#featurecore-architecture) - [feature/products](#featureproducts) +- [feature/product-images](#featureproduct-images) - [feature/customers](#featurecustomers) - [feature/orders](#featureorders) - [feature/auth](#featureauth) @@ -373,6 +374,61 @@ Includes `Category` and `Product`, given their direct link in the model. - **`minPrice`/`maxPrice` query parameters and `unitPrice` throughout the stack use `BigDecimal`.** `ProductSpecifications.priceBetween`, `ProductService.findAll`, `ProductController.findAll` and all DTOs have been updated from `Float`/`float` to `BigDecimal` to prevent rounding at the HTTP deserialization boundary. - **`Product.active` is not writable from `ProductRequest`.** `ProductMapper.toEntity` and `updateEntityFromRequest` both ignore `active` to prevent a create/update call from accidentally clearing the flag. Activation and deactivation are managed separately. +## feature/product-images + +Adds image upload and management for products. Branches from `feature/products` and is +independent of `feature/orders`. Introduces a local file storage abstraction that can be +replaced by S3 or any other backend by swapping the `FileStorageService` implementation. + +### Endpoints + +| Method | URL | Description | +|---|---|---| +| POST | `/api/v1/products/{id}/images` | Upload an image for a product (multipart/form-data) | +| DELETE | `/api/v1/products/{id}/images/{imageId}` | Remove an image from a product | + +`GET /api/v1/products/{id}` now includes an `images` array in the response (empty on the +paginated list, populated on the detail endpoint). + +### Tasks + +- [x] Migration `V16__create_product_images.sql`: `product_images` table with `is_primary` + partial unique index (`WHERE is_primary = TRUE`), `ON DELETE CASCADE` to products +- [x] `ProductImage` entity with `@ManyToOne(LAZY)` to `Product`, JPA auditing +- [x] `StorageProperties` (`@ConfigurationProperties(prefix = "app.storage")`) and `StorageConfig` +- [x] `FileStorageService` interface + `LocalFileStorageService` implementation + (UUID filenames, extension and MIME type validation, size limit, path traversal guard) +- [x] `ProductImageRepository` with `findByProductIdOrderByDisplayOrderAsc` and `findByProductIdAndPrimaryTrue` +- [x] `ProductImageResponse` DTO (snake_case JSON via `@JsonProperty`) +- [x] `ProductImageMapper` +- [x] `ProductImageService` interface + `ProductImageServiceImpl`: upload, primary-flag swap, ownership check on delete +- [x] `ProductServiceImpl.findById` updated to load images and delegate to `ProductMapper.toDetailResponse` +- [x] `ProductResponse` gains `List images` (empty on list, populated on detail) +- [x] `ProductController` gains `POST /{id}/images` and `DELETE /{id}/images/{imageId}` endpoints +- [x] Tests: `ProductImageServiceImplTest`, `LocalFileStorageServiceTest`, image endpoint tests in `ProductControllerTest` + +### Configuration notes + +- **`app.storage.upload-dir`** defaults to `./uploads/products` (overridable via `APP_STORAGE_UPLOAD_DIR`). + In a Docker deployment, mount a persistent volume at that path so uploaded files survive container restarts. +- **`app.storage.max-file-size-mb`** is set to 5. Accepted formats: `jpg`, `jpeg`, `png`, `webp`. +- **`ProductResponse.images` is populated only on `GET /api/v1/products/{id}`.** The paginated list + (`findAll`) uses `ProductMapper.toResponse`, which always returns an empty list, keeping list + requests free of an N+1 on `product_images`. The detail endpoint loads images via + `ProductImageRepository.findByProductIdOrderByDisplayOrderAsc` and passes the list to + `ProductMapper.toDetailResponse`. +- **`findById` result is cached (`@Cacheable("products")`) including the image list.** A cache eviction + on `update`/`delete` ensures stale image data does not linger, but adding or removing an image does + not evict the product cache. The product detail will serve the cached (stale) image list until the + cache entry expires (TTL from `CacheConfig`). This is an accepted simplification for this tutorial. +- **`boolean primary` on `ProductImage` (column `is_primary`).** Lombok generates `isPrimary()` + as the getter (JavaBeans convention), which MapStruct maps as property `primary`, matching the + record component name in `ProductImageResponse`. Naming the field `isPrimary` would have caused a + mismatch and an unmapped-property warning. +- **Migration is `V16`, not `V15`.** `V14` and `V15` are reserved for `feature/orders` (this branch + does not depend on `feature/orders`). Using `V16` avoids a Flyway conflict when both branches + merge into an integration branch. + ## feature/customers ### Endpoints From d282ca5ca9c84462a6c9e576c21c70018e7758e2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:40:57 +0400 Subject: [PATCH 081/175] fix(test): remove redundant save(existingPrimary) stub in ProductImageServiceImplTest._03_ --- .../service/impl/ProductImageServiceImplTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java index c547980..4029ab7 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java @@ -99,7 +99,6 @@ void _03_ShouldUnsetOldPrimary_WhenAddingNewPrimaryImage() { when(productRepository.findById(1L)).thenReturn(Optional.of(product)); when(productImageRepository.findByProductIdAndPrimaryTrue(1L)) .thenReturn(Optional.of(existingPrimary)); - when(productImageRepository.save(existingPrimary)).thenReturn(existingPrimary); when(fileStorageService.store(file, "products")).thenReturn("/uploads/products/new.jpg"); when(productImageRepository.save(any(ProductImage.class))).thenReturn(saved); when(productImageMapper.toResponse(saved)).thenReturn(response); From 20fe2d549c488ff35b6572c5a41389ec560dbeb8 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:48:04 +0400 Subject: [PATCH 082/175] fix(service): evict products cache on addImage and deleteImage in ProductImageServiceImpl --- .../service/impl/ProductImageServiceImpl.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java index 9024cfa..8bb9ebd 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java @@ -10,6 +10,7 @@ import com.edgareldy.springboottutorial.service.ProductImageService; import com.edgareldy.springboottutorial.storage.FileStorageService; import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -39,6 +40,7 @@ public class ProductImageServiceImpl implements ProductImageService { @Override @Transactional + @CacheEvict(value = "products", key = "#productId") public ProductImageResponse addImage(Long productId, MultipartFile file, String altText, boolean isPrimary) { Product product = productRepository.findById(productId) .orElseThrow(() -> new ResourceNotFoundException("Product not found with id " + productId)); @@ -64,6 +66,7 @@ public ProductImageResponse addImage(Long productId, MultipartFile file, String @Override @Transactional + @CacheEvict(value = "products", key = "#productId") public void deleteImage(Long productId, Long imageId) { ProductImage image = productImageRepository.findById(imageId) .orElseThrow(() -> new ResourceNotFoundException("Image not found with id " + imageId)); From 59111380d1bec16e2cfd96e88f451c691d1f06be Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:48:37 +0400 Subject: [PATCH 083/175] test(controller): add error case tests for image endpoints in ProductControllerTest --- .../controller/ProductControllerTest.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java index 41a1912..fad81da 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java @@ -17,6 +17,7 @@ import com.edgareldy.springboottutorial.dto.product.ProductImageResponse; import com.edgareldy.springboottutorial.dto.product.ProductRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.service.ProductImageService; import com.edgareldy.springboottutorial.service.ProductService; @@ -231,4 +232,40 @@ void _15_ShouldReturn200_WhenImageDeleted() throws Exception { .andExpect(status().isOk()) .andExpect(jsonPath("$.success").value(true)); } + + @Test + void _16_ShouldReturn404_WhenProductNotFoundOnAddImage() throws Exception { + when(productImageService.addImage(eq(99L), any(), any(), eq(false))) + .thenThrow(new ResourceNotFoundException("Product not found with id 99")); + + MockMultipartFile file = new MockMultipartFile( + "file", "photo.jpg", MediaType.IMAGE_JPEG_VALUE, "jpg-bytes".getBytes()); + + mockMvc.perform(multipart("/api/v1/products/99/images").file(file)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + void _17_ShouldReturn422_WhenImageFileInvalidOnAdd() throws Exception { + when(productImageService.addImage(eq(1L), any(), any(), eq(false))) + .thenThrow(new BusinessRuleException("File type not allowed")); + + MockMultipartFile file = new MockMultipartFile( + "file", "photo.jpg", MediaType.IMAGE_JPEG_VALUE, "jpg-bytes".getBytes()); + + mockMvc.perform(multipart("/api/v1/products/1/images").file(file)) + .andExpect(status().isUnprocessableEntity()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + void _18_ShouldReturn404_WhenImageNotFoundOnDelete() throws Exception { + doThrow(new ResourceNotFoundException("Image not found with id 99")) + .when(productImageService).deleteImage(1L, 99L); + + mockMvc.perform(delete("/api/v1/products/1/images/99")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.success").value(false)); + } } From c45fd7d2bc7c5ec3ffb7f74e28dfa00db222c537 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:48:57 +0400 Subject: [PATCH 084/175] test(service): add test for addImage when no previous primary exists --- .../impl/ProductImageServiceImplTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java index 4029ab7..4dbcd72 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java @@ -132,6 +132,24 @@ void _05_ShouldThrowNotFound_WhenImageMissingOnDelete() { verify(fileStorageService, never()).delete(any()); } + @Test + void _07_ShouldAddImageAsPrimary_WhenNoPreviousPrimaryExists() { + ProductImage saved = ProductImage.builder().id(10L).product(product) + .imageUrl("/uploads/products/uuid.jpg").primary(true).displayOrder(0).build(); + ProductImageResponse response = new ProductImageResponse(10L, "/uploads/products/uuid.jpg", null, true, 0); + + when(productRepository.findById(1L)).thenReturn(Optional.of(product)); + when(productImageRepository.findByProductIdAndPrimaryTrue(1L)).thenReturn(Optional.empty()); + when(fileStorageService.store(file, "products")).thenReturn("/uploads/products/uuid.jpg"); + when(productImageRepository.save(any(ProductImage.class))).thenReturn(saved); + when(productImageMapper.toResponse(saved)).thenReturn(response); + + ProductImageResponse result = productImageService.addImage(1L, file, null, true); + + assertThat(result).isEqualTo(response); + verify(productImageRepository).findByProductIdAndPrimaryTrue(1L); + } + @Test void _06_ShouldThrowNotFound_WhenImageDoesNotBelongToProduct() { Product otherProduct = Product.builder().id(99L).productName("Mouse").build(); From e7219bfa671496186f1e24c4b6a823365f8ca8fa Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 18:48:57 +0400 Subject: [PATCH 085/175] test(storage): add MIME type mismatch test to LocalFileStorageServiceTest --- .../storage/LocalFileStorageServiceTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java b/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java index d2ed58e..13f7617 100644 --- a/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java @@ -108,4 +108,15 @@ void _07_ShouldIgnoreDelete_WhenUrlDoesNotStartWithUploads() { // Should not throw storageService.delete("/static/logo.png"); } + + @Test + void _08_ShouldRejectFile_WhenMimeTypeMismatch() { + // .jpg extension (allowed) but image/gif content-type (not allowed) + MockMultipartFile file = new MockMultipartFile( + "file", "photo.jpg", "image/gif", "gif-bytes".getBytes()); + + assertThatThrownBy(() -> storageService.store(file, "products")) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("MIME type not allowed"); + } } From 365ee5420777e31e937bdc5f5f34a765646d77e2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Tue, 17 Nov 2026 19:25:08 +0400 Subject: [PATCH 086/175] test(controller): add GET /orders/{id} 200 happy-path test to OrderControllerTest The code-reviewer found that the only test for GET /api/v1/orders/{id} was the 404 path. The 200 path is now covered by _03_, asserting the three fields introduced in this phase: order_number, status and total_amount. The former _03_ (404) is renumbered _03b_. --- .../controller/OrderControllerTest.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index a42c7df..f0c9021 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java @@ -104,7 +104,19 @@ void _02_ShouldForwardFilters_WhenCustomerAndProductGiven() throws Exception { } @Test - void _03_ShouldReturn404_WhenOrderMissing() throws Exception { + void _03_ShouldReturn200_WhenOrderFound() throws Exception { + when(orderService.findById(1L)).thenReturn(sampleResponse()); + + mockMvc.perform(get("/api/v1/orders/1")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.order_number").value("ORD-TEST-0001")) + .andExpect(jsonPath("$.data.status").value("PENDING")) + .andExpect(jsonPath("$.data.total_amount").value(100.00)) + .andExpect(jsonPath("$.data.items").isArray()); + } + + @Test + void _03b_ShouldReturn404_WhenOrderMissing() throws Exception { when(orderService.findById(99L)).thenThrow(new ResourceNotFoundException("Order not found with id 99")); mockMvc.perform(get("/api/v1/orders/99")) From 9b24a93eafc5775babecc3f1fd3acae843e30775 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:46:42 +0400 Subject: [PATCH 087/175] feat(flyway): add V16 migration for carts and cart_items tables Creates two tables: carts (one row per AppUser, enforced by UNIQUE on user_id and ON DELETE CASCADE) and cart_items (one row per product per cart, enforced by the composite unique constraint uq_cart_product). cart_items.product_id is NOT NULL with no ON DELETE CASCADE: removing a product from the catalogue while it sits in a cart will be blocked by the FK, forcing an explicit removal from the cart first. --- .../db/migration/V16__create_cart_tables.sql | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/main/resources/db/migration/V16__create_cart_tables.sql diff --git a/src/main/resources/db/migration/V16__create_cart_tables.sql b/src/main/resources/db/migration/V16__create_cart_tables.sql new file mode 100644 index 0000000..3cfbe9f --- /dev/null +++ b/src/main/resources/db/migration/V16__create_cart_tables.sql @@ -0,0 +1,17 @@ +CREATE TABLE carts ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + user_id BIGINT NOT NULL UNIQUE REFERENCES app_users(id) ON DELETE CASCADE, + created_at TIMESTAMP, + updated_at TIMESTAMP +); + +CREATE TABLE cart_items ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + cart_id BIGINT NOT NULL REFERENCES carts(id) ON DELETE CASCADE, + product_id BIGINT NOT NULL REFERENCES products(id), + quantity INT NOT NULL CHECK (quantity > 0), + CONSTRAINT uq_cart_product UNIQUE (cart_id, product_id) +); + +CREATE INDEX idx_cart_items_cart_id ON cart_items(cart_id); +CREATE INDEX idx_cart_items_product_id ON cart_items(product_id); From 5b0a61911a044ad45cb9a2d447d1d0ba7b55958b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:47:04 +0400 Subject: [PATCH 088/175] feat(entity): add Cart entity One Cart per AppUser (UNIQUE on user_id). Items are owned via OneToMany(cascade=ALL, orphanRemoval=true) so removing an item from the list is enough to delete it. JPA auditing via @CreatedDate/@LastModifiedDate records when the cart was first created and last modified (a new item added counts as a modification). --- .../springboottutorial/entity/Cart.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/entity/Cart.java diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/Cart.java b/src/main/java/com/edgareldy/springboottutorial/entity/Cart.java new file mode 100644 index 0000000..714f553 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/entity/Cart.java @@ -0,0 +1,67 @@ +package com.edgareldy.springboottutorial.entity; + +import com.edgareldy.springboottutorial.entity.user.AppUser; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +/** + * Persistent shopping cart tied to a single AppUser. Each user has at most + * one cart (enforced by the UNIQUE constraint on user_id). Cart items are + * owned via cascade ALL with orphan removal, so removing an item from the + * list deletes it from the database. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@Entity +@Table(name = "carts") +@EntityListeners(AuditingEntityListener.class) +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Cart { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false, unique = true) + private AppUser user; + + @Builder.Default + @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, orphanRemoval = true) + private List items = new ArrayList<>(); + + @CreatedDate + @Column(updatable = false) + private LocalDateTime createdAt; + + @LastModifiedDate + private LocalDateTime updatedAt; +} From 1856790a2b259bb45c0d63536b93960ab658bead Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:47:08 +0400 Subject: [PATCH 089/175] feat(entity): add CartItem entity Links a Cart to a Product with a quantity. The DB enforces that each product appears at most once per cart (uq_cart_product), so the service increments quantity on a duplicate add rather than inserting a second row. --- .../springboottutorial/entity/CartItem.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/entity/CartItem.java diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/CartItem.java b/src/main/java/com/edgareldy/springboottutorial/entity/CartItem.java new file mode 100644 index 0000000..f3f3d60 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/entity/CartItem.java @@ -0,0 +1,52 @@ +package com.edgareldy.springboottutorial.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 lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * One line in a shopping cart, linking a product to a quantity. The + * combination (cart_id, product_id) is unique in the database, so adding + * the same product twice increments the quantity rather than creating a + * second row. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@Entity +@Table(name = "cart_items") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class CartItem { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "cart_id", nullable = false) + private Cart cart; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "product_id", nullable = false) + private Product product; + + @Column(nullable = false) + private int quantity; +} From bdb361264d4a22bbb02ade3139b4c6dec5c4bf51 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:47:32 +0400 Subject: [PATCH 090/175] feat(dto): add CartItemRequest and CartItemUpdateRequest DTOs CartItemRequest carries productId and quantity for adding an item to the cart. No userId field: the authenticated user is always resolved from the SecurityContext in the controller, never from the payload. CartItemUpdateRequest carries only the new quantity for a PATCH update. Both records use Bean Validation (@NotNull, @Positive) so the controller gets a 400 response without any manual checks. --- .../dto/cart/CartItemRequest.java | 22 +++++++++++++++++++ .../dto/cart/CartItemUpdateRequest.java | 18 +++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemUpdateRequest.java diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java new file mode 100644 index 0000000..fbca586 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java @@ -0,0 +1,22 @@ +package com.edgareldy.springboottutorial.dto.cart; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; + +/** + * Request payload to add a product to the authenticated user's cart. + * No userId field: the user is always resolved from the SecurityContext. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public record CartItemRequest( + @NotNull(message = "Product ID must not be null") + Long productId, + + @NotNull(message = "Quantity must not be null") + @Positive(message = "Quantity must be positive") + Integer quantity +) {} diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemUpdateRequest.java b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemUpdateRequest.java new file mode 100644 index 0000000..4fcee81 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemUpdateRequest.java @@ -0,0 +1,18 @@ +package com.edgareldy.springboottutorial.dto.cart; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; + +/** + * Request payload to update the quantity of an existing cart item. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public record CartItemUpdateRequest( + @NotNull(message = "Quantity must not be null") + @Positive(message = "Quantity must be positive") + Integer quantity +) {} From 1b7797f244af470eaaba76925316ecaee39e5b60 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:47:36 +0400 Subject: [PATCH 091/175] feat(dto): add CartItemResponse and CartResponse DTOs CartItemResponse exposes id, product_id, product_name, unit_price, quantity and subtotal (computed field). CartResponse exposes the cart id, the list of items, and the grand total. JSON keys use snake_case via @JsonProperty on the two-word fields, keeping Java field names in camelCase for consistent MapStruct mapping. --- .../dto/cart/CartItemResponse.java | 30 +++++++++++++++++++ .../dto/cart/CartResponse.java | 19 ++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemResponse.java create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/cart/CartResponse.java diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemResponse.java new file mode 100644 index 0000000..b218e97 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemResponse.java @@ -0,0 +1,30 @@ +package com.edgareldy.springboottutorial.dto.cart; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; + +/** + * Response DTO for a single cart item. The subtotal is computed by the + * mapper as quantity * unitPrice and serialised as a JSON number. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public record CartItemResponse( + Long id, + + @JsonProperty("product_id") + Long productId, + + @JsonProperty("product_name") + String productName, + + @JsonProperty("unit_price") + BigDecimal unitPrice, + + Integer quantity, + + BigDecimal subtotal +) {} diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartResponse.java b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartResponse.java new file mode 100644 index 0000000..5cf28de --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartResponse.java @@ -0,0 +1,19 @@ +package com.edgareldy.springboottutorial.dto.cart; + +import java.math.BigDecimal; +import java.util.List; + +/** + * Response DTO for the authenticated user's shopping cart. The total is + * the sum of all item subtotals and is computed by the mapper. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public record CartResponse( + Long id, + List items, + BigDecimal total +) {} From 66da525c0c2d96e67cf9fcc0a52b5774d862834c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:48:08 +0400 Subject: [PATCH 092/175] feat(mapper): add CartMapper toItemResponse maps CartItem to CartItemResponse, pulling productId/Name/ unitPrice from the associated Product and computing subtotal inline as unitPrice * quantity via a MapStruct expression. toItemResponseList delegates to toItemResponse for each element. toResponse is a default method that calls toItemResponseList then sums subtotals for the cart total. Using a default method here (same pattern as ProductMapper.toDetailResponse) avoids the limitation that @AfterMapping cannot mutate an immutable record. --- .../springboottutorial/mapper/CartMapper.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/mapper/CartMapper.java diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/CartMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/CartMapper.java new file mode 100644 index 0000000..beaa908 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/CartMapper.java @@ -0,0 +1,44 @@ +package com.edgareldy.springboottutorial.mapper; + +import com.edgareldy.springboottutorial.dto.cart.CartItemResponse; +import com.edgareldy.springboottutorial.dto.cart.CartResponse; +import com.edgareldy.springboottutorial.entity.Cart; +import com.edgareldy.springboottutorial.entity.CartItem; +import java.math.BigDecimal; +import java.util.List; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +/** + * MapStruct mapper converting {@link Cart} and {@link CartItem} entities to + * their response DTOs. The {@code subtotal} per item and the cart {@code total} + * are computed fields: MapStruct cannot derive them automatically, so + * {@code toItemResponse} uses an inline expression and {@code toResponse} is + * a {@code default} method that sums the mapped item subtotals. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@Mapper(componentModel = "spring") +public interface CartMapper { + + @Mapping(target = "productId", source = "product.id") + @Mapping(target = "productName", source = "product.productName") + @Mapping(target = "unitPrice", source = "product.unitPrice") + @Mapping(target = "subtotal", + expression = "java(item.getProduct().getUnitPrice()" + + ".multiply(java.math.BigDecimal.valueOf(item.getQuantity())))") + CartItemResponse toItemResponse(CartItem item); + + List toItemResponseList(List items); + + default CartResponse toResponse(Cart cart) { + List items = toItemResponseList(cart.getItems()); + BigDecimal total = items.stream() + .map(CartItemResponse::subtotal) + .reduce(BigDecimal.ZERO, BigDecimal::add); + return new CartResponse(cart.getId(), items, total); + } +} From 31ace03f7a2df5a4d2a982b42338ba0e6968a2cd Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:48:19 +0400 Subject: [PATCH 093/175] feat(repository): add CartRepository Extends JpaRepository with two custom finders. Both carry @EntityGraph(attributePaths = {"items", "items.product"}) to load the full item list in a single query, avoiding LazyInitializationException when the mapper traverses item.getProduct() outside of a transaction. --- .../repository/CartRepository.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/repository/CartRepository.java diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/CartRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/CartRepository.java new file mode 100644 index 0000000..ea6e6ee --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/repository/CartRepository.java @@ -0,0 +1,26 @@ +package com.edgareldy.springboottutorial.repository; + +import com.edgareldy.springboottutorial.entity.Cart; +import java.util.Optional; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Spring Data repository for {@link Cart} entities. The two finder methods + * both eager-load the items and their associated products in a single query, + * preventing LazyInitializationException when the mapper accesses the item + * list outside the original persistence context. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public interface CartRepository extends JpaRepository { + + @EntityGraph(attributePaths = {"items", "items.product"}) + Optional findByUserId(Long userId); + + @EntityGraph(attributePaths = {"items", "items.product"}) + Optional findByUserUsername(String username); +} From 145875dfbd364863bb94658f9c51e9971c7b5eff Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:48:23 +0400 Subject: [PATCH 094/175] feat(repository): add CartItemRepository Single custom finder: findByCartIdAndProductId, used by CartServiceImpl to detect when a product is already in the cart so it can increment the quantity rather than insert a duplicate row. --- .../repository/CartItemRepository.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java new file mode 100644 index 0000000..798c03d --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java @@ -0,0 +1,18 @@ +package com.edgareldy.springboottutorial.repository; + +import com.edgareldy.springboottutorial.entity.CartItem; +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Spring Data repository for {@link CartItem} entities. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public interface CartItemRepository extends JpaRepository { + + Optional findByCartIdAndProductId(Long cartId, Long productId); +} From f555747fce393b3ad3d5bd17dfbc71becd18d3e1 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:49:05 +0400 Subject: [PATCH 095/175] feat(service): add CartService interface Defines the five cart operations (getCart, addItem, updateItem, removeItem, clearCart). All methods take username (from SecurityContext) rather than userId to enforce the invariant that the caller never controls which user's cart is modified. --- .../service/CartService.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/service/CartService.java diff --git a/src/main/java/com/edgareldy/springboottutorial/service/CartService.java b/src/main/java/com/edgareldy/springboottutorial/service/CartService.java new file mode 100644 index 0000000..d72df84 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/CartService.java @@ -0,0 +1,28 @@ +package com.edgareldy.springboottutorial.service; + +import com.edgareldy.springboottutorial.dto.cart.CartItemRequest; +import com.edgareldy.springboottutorial.dto.cart.CartItemUpdateRequest; +import com.edgareldy.springboottutorial.dto.cart.CartResponse; + +/** + * Contract for shopping-cart operations. All methods receive the username + * of the authenticated user (resolved from the SecurityContext by the + * controller), never a userId from the HTTP payload. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public interface CartService { + + CartResponse getCart(String username); + + CartResponse addItem(String username, CartItemRequest request); + + CartResponse updateItem(String username, Long itemId, CartItemUpdateRequest request); + + CartResponse removeItem(String username, Long itemId); + + CartResponse clearCart(String username); +} From 5aba208fee8aadad2879d9ff6ed069dcd9091a36 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:49:12 +0400 Subject: [PATCH 096/175] feat(service): add CartServiceImpl with active product check and quantity management Key behaviours: - getOrCreateCart: the cart is created on the first addItem call, never eagerly. getCart returns an in-memory empty Cart if none exists. - addItem: rejects inactive products (BusinessRuleException 422); if the product is already in the cart the quantity is incremented rather than inserting a duplicate row (detected via CartItemRepository lookup). - updateItem / removeItem: verify the item belongs to the caller's cart before mutating, raising ResourceNotFoundException (404) otherwise. - clearCart: removes all items via orphan removal. After each write the cart is re-loaded via CartRepository (EntityGraph) so the returned CartResponse reflects the persisted state. --- .../service/impl/CartServiceImpl.java | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java new file mode 100644 index 0000000..4affd92 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java @@ -0,0 +1,146 @@ +package com.edgareldy.springboottutorial.service.impl; + +import com.edgareldy.springboottutorial.dto.cart.CartItemRequest; +import com.edgareldy.springboottutorial.dto.cart.CartItemUpdateRequest; +import com.edgareldy.springboottutorial.dto.cart.CartResponse; +import com.edgareldy.springboottutorial.entity.Cart; +import com.edgareldy.springboottutorial.entity.CartItem; +import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.mapper.CartMapper; +import com.edgareldy.springboottutorial.repository.AppUserRepository; +import com.edgareldy.springboottutorial.repository.CartItemRepository; +import com.edgareldy.springboottutorial.repository.CartRepository; +import com.edgareldy.springboottutorial.repository.ProductRepository; +import com.edgareldy.springboottutorial.service.CartService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Default implementation of {@link CartService}. Each user has at most one + * cart, created lazily on the first item add. The user is always identified + * by username (from the SecurityContext), never by a userId supplied in the + * HTTP payload. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@Service +@RequiredArgsConstructor +public class CartServiceImpl implements CartService { + + private final CartRepository cartRepository; + private final CartItemRepository cartItemRepository; + private final ProductRepository productRepository; + private final AppUserRepository appUserRepository; + private final CartMapper cartMapper; + + @Override + @Transactional(readOnly = true) + public CartResponse getCart(String username) { + AppUser user = getUserOrThrow(username); + Cart cart = cartRepository.findByUserId(user.getId()) + .orElseGet(() -> Cart.builder().user(user).build()); + return cartMapper.toResponse(cart); + } + + @Override + @Transactional + public CartResponse addItem(String username, CartItemRequest request) { + AppUser user = getUserOrThrow(username); + Product product = getActiveProductOrThrow(request.productId()); + Cart cart = getOrCreateCart(user); + + cartItemRepository.findByCartIdAndProductId(cart.getId(), product.getId()) + .ifPresentOrElse( + existing -> existing.setQuantity(existing.getQuantity() + request.quantity()), + () -> { + CartItem item = CartItem.builder() + .cart(cart) + .product(product) + .quantity(request.quantity()) + .build(); + cart.getItems().add(item); + } + ); + Cart saved = cartRepository.save(cart); + Cart loaded = cartRepository.findByUserId(user.getId()).orElse(saved); + return cartMapper.toResponse(loaded); + } + + @Override + @Transactional + public CartResponse updateItem(String username, Long itemId, CartItemUpdateRequest request) { + AppUser user = getUserOrThrow(username); + Cart cart = getCartOrThrow(user); + CartItem item = getItemBelongingToCart(cart, itemId); + item.setQuantity(request.quantity()); + cartRepository.save(cart); + Cart loaded = cartRepository.findByUserId(user.getId()).orElse(cart); + return cartMapper.toResponse(loaded); + } + + @Override + @Transactional + public CartResponse removeItem(String username, Long itemId) { + AppUser user = getUserOrThrow(username); + Cart cart = getCartOrThrow(user); + CartItem item = getItemBelongingToCart(cart, itemId); + cart.getItems().remove(item); + cartRepository.save(cart); + Cart loaded = cartRepository.findByUserId(user.getId()).orElse(cart); + return cartMapper.toResponse(loaded); + } + + @Override + @Transactional + public CartResponse clearCart(String username) { + AppUser user = getUserOrThrow(username); + Cart cart = getCartOrThrow(user); + cart.getItems().clear(); + cartRepository.save(cart); + Cart loaded = cartRepository.findByUserId(user.getId()).orElse(cart); + return cartMapper.toResponse(loaded); + } + + private AppUser getUserOrThrow(String username) { + return appUserRepository.findByUsername(username) + .orElseThrow(() -> new ResourceNotFoundException( + "User not found with username: " + username)); + } + + private Product getActiveProductOrThrow(Long productId) { + Product product = productRepository.findByIdWithCategory(productId) + .orElseThrow(() -> new ResourceNotFoundException( + "Product not found with id " + productId)); + if (!product.isActive()) { + throw new BusinessRuleException( + "Product with id " + productId + " is not active and cannot be added to cart"); + } + return product; + } + + private Cart getOrCreateCart(AppUser user) { + return cartRepository.findByUserId(user.getId()) + .orElseGet(() -> cartRepository.save(Cart.builder().user(user).build())); + } + + private Cart getCartOrThrow(AppUser user) { + return cartRepository.findByUserId(user.getId()) + .orElseThrow(() -> new ResourceNotFoundException( + "Cart not found for user: " + user.getUsername())); + } + + private CartItem getItemBelongingToCart(Cart cart, Long itemId) { + return cart.getItems().stream() + .filter(i -> i.getId().equals(itemId)) + .findFirst() + .orElseThrow(() -> new ResourceNotFoundException( + "Cart item not found with id " + itemId)); + } +} From 246804215ad95aa057233ade11cdcf76f8d77e15 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:49:35 +0400 Subject: [PATCH 097/175] feat(controller): add CartController with 5 cart endpoints GET /api/v1/cart - view the cart (empty cart for new users) POST /api/v1/cart/items - add a product (201 Created) PATCH /api/v1/cart/items/{id} - update quantity DELETE /api/v1/cart/items/{id} - remove one item DELETE /api/v1/cart/items - clear all items The user is resolved exclusively from @AuthenticationPrincipal UserDetails (username fed to CartService) - never from a path variable or payload, so a user cannot modify another user's cart. --- .../controller/CartController.java | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/controller/CartController.java diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/CartController.java b/src/main/java/com/edgareldy/springboottutorial/controller/CartController.java new file mode 100644 index 0000000..dcb09b7 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/controller/CartController.java @@ -0,0 +1,95 @@ +package com.edgareldy.springboottutorial.controller; + +import com.edgareldy.springboottutorial.dto.cart.CartItemRequest; +import com.edgareldy.springboottutorial.dto.cart.CartItemUpdateRequest; +import com.edgareldy.springboottutorial.dto.cart.CartResponse; +import com.edgareldy.springboottutorial.dto.common.ApiResponse; +import com.edgareldy.springboottutorial.service.CartService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * REST controller exposing the authenticated user's shopping cart. + * All endpoints require the USER role (enforced by SecurityConfig). The + * user identity is always taken from the SecurityContext via + * {@code @AuthenticationPrincipal UserDetails}, never from the payload. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@RestController +@RequestMapping("/api/v1/cart") +@RequiredArgsConstructor +@Tag(name = "Cart", description = "Shopping cart management for authenticated users") +public class CartController { + + private final CartService cartService; + + @GetMapping + @Operation(summary = "Get the authenticated user's cart") + public ResponseEntity> getCart( + @AuthenticationPrincipal UserDetails userDetails) { + return ResponseEntity.ok( + ApiResponse.success(cartService.getCart(userDetails.getUsername()), + "Cart retrieved successfully")); + } + + @PostMapping("/items") + @Operation(summary = "Add an item to the cart") + public ResponseEntity> addItem( + @AuthenticationPrincipal UserDetails userDetails, + @Valid @RequestBody CartItemRequest request) { + return ResponseEntity.status(HttpStatus.CREATED) + .body(ApiResponse.success( + cartService.addItem(userDetails.getUsername(), request), + "Item added to cart")); + } + + @PatchMapping("/items/{itemId}") + @Operation(summary = "Update the quantity of a cart item") + public ResponseEntity> updateItem( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable Long itemId, + @Valid @RequestBody CartItemUpdateRequest request) { + return ResponseEntity.ok( + ApiResponse.success( + cartService.updateItem(userDetails.getUsername(), itemId, request), + "Cart item updated")); + } + + @DeleteMapping("/items/{itemId}") + @Operation(summary = "Remove a single item from the cart") + public ResponseEntity> removeItem( + @AuthenticationPrincipal UserDetails userDetails, + @PathVariable Long itemId) { + return ResponseEntity.ok( + ApiResponse.success( + cartService.removeItem(userDetails.getUsername(), itemId), + "Cart item removed")); + } + + @DeleteMapping("/items") + @Operation(summary = "Clear all items from the cart") + public ResponseEntity> clearCart( + @AuthenticationPrincipal UserDetails userDetails) { + return ResponseEntity.ok( + ApiResponse.success(cartService.clearCart(userDetails.getUsername()), + "Cart cleared")); + } +} From bfc0580a7313496fbf4ec97b7bbcc9727180b341 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:49:55 +0400 Subject: [PATCH 098/175] refactor(security): protect /api/v1/cart/** with ROLE_USER in SecurityConfig Cart endpoints are intentionally user-facing: only authenticated users with the USER role may manage their own cart. The rule is inserted before the anyRequest().authenticated() catch-all so it takes precedence. ADMIN users who also hold USER (the typical setup after user-management seeding) can access the cart as well. --- .../com/edgareldy/springboottutorial/config/SecurityConfig.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java index eb5ba60..7bc4dda 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java @@ -94,6 +94,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/api/v1/customers/**", "/api/v1/orders/**") .hasRole("ADMIN") + .requestMatchers("/api/v1/cart/**") + .hasRole("USER") .anyRequest() .authenticated()) .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); From 9adb85f3d2d02fe0201c4428f8dbdcffc86f0ae0 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:51:48 +0400 Subject: [PATCH 099/175] test(service): add CartServiceImplTest Covers all CartServiceImpl public methods with Mockito mocks: - getCart: existing cart returned; no-cart path returns empty in-memory cart - addItem: new cart created on first add; duplicate product increments quantity - addItem: inactive product rejected with BusinessRuleException - addItem: missing product rejected with ResourceNotFoundException - updateItem: quantity changed; item not in cart raises ResourceNotFoundException - removeItem: item removed from list (orphan removal path) - clearCart: all items removed --- .../service/impl/CartServiceImplTest.java | 211 ++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java new file mode 100644 index 0000000..6d71468 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java @@ -0,0 +1,211 @@ +package com.edgareldy.springboottutorial.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.edgareldy.springboottutorial.dto.cart.CartItemRequest; +import com.edgareldy.springboottutorial.dto.cart.CartItemUpdateRequest; +import com.edgareldy.springboottutorial.dto.cart.CartItemResponse; +import com.edgareldy.springboottutorial.dto.cart.CartResponse; +import com.edgareldy.springboottutorial.entity.Cart; +import com.edgareldy.springboottutorial.entity.CartItem; +import com.edgareldy.springboottutorial.entity.Category; +import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.mapper.CartMapper; +import com.edgareldy.springboottutorial.repository.AppUserRepository; +import com.edgareldy.springboottutorial.repository.CartItemRepository; +import com.edgareldy.springboottutorial.repository.CartRepository; +import com.edgareldy.springboottutorial.repository.ProductRepository; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +/** + * Unit tests for {@link CartServiceImpl}, with all collaborators mocked. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@ExtendWith(MockitoExtension.class) +class CartServiceImplTest { + + @Mock private CartRepository cartRepository; + @Mock private CartItemRepository cartItemRepository; + @Mock private ProductRepository productRepository; + @Mock private AppUserRepository appUserRepository; + @Mock private CartMapper cartMapper; + + @InjectMocks + private CartServiceImpl cartService; + + private AppUser user; + private Product product; + private Cart cart; + private CartItem cartItem; + private CartResponse emptyResponse; + private CartResponse filledResponse; + + @BeforeEach + void setUp() { + Category category = Category.builder().id(1L).categoryName("Electronics").build(); + user = AppUser.builder().id(1L).username("alice").email("alice@example.com").build(); + product = Product.builder() + .id(1L).productName("Keyboard").unitPrice(new BigDecimal("79.99")) + .category(category).active(true).build(); + cart = Cart.builder().id(1L).user(user).items(new ArrayList<>()).build(); + cartItem = CartItem.builder().id(1L).cart(cart).product(product).quantity(2).build(); + emptyResponse = new CartResponse(1L, List.of(), BigDecimal.ZERO); + filledResponse = new CartResponse(1L, + List.of(new CartItemResponse(1L, 1L, "Keyboard", + new BigDecimal("79.99"), 2, new BigDecimal("159.98"))), + new BigDecimal("159.98")); + } + + @Test + void getCart_ShouldReturnExistingCart() { + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(1L)).thenReturn(Optional.of(cart)); + when(cartMapper.toResponse(cart)).thenReturn(emptyResponse); + + CartResponse result = cartService.getCart("alice"); + + assertThat(result).isEqualTo(emptyResponse); + } + + @Test + void getCart_ShouldReturnEmptyCart_WhenNoneExists() { + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(1L)).thenReturn(Optional.empty()); + + CartResponse result = cartService.getCart("alice"); + + // in-memory empty cart is returned, mapper called with a transient Cart + verify(cartMapper).toResponse(any(Cart.class)); + assertThat(result).isNull(); // mapper is mocked, returns null by default + } + + @Test + void addItem_ShouldCreateNewCartAndAddItem_WhenNoCartExists() { + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); + // getOrCreateCart: first call returns empty, so save is called + when(cartRepository.findByUserId(1L)) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + when(cartItemRepository.findByCartIdAndProductId(any(), eq(1L))).thenReturn(Optional.empty()); + when(cartMapper.toResponse(cart)).thenReturn(filledResponse); + + CartResponse result = cartService.addItem("alice", new CartItemRequest(1L, 2)); + + assertThat(result).isEqualTo(filledResponse); + verify(cartRepository).save(any(Cart.class)); + } + + @Test + void addItem_ShouldIncrementQuantity_WhenProductAlreadyInCart() { + cart.getItems().add(cartItem); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); + when(cartRepository.findByUserId(1L)).thenReturn(Optional.of(cart)); + when(cartItemRepository.findByCartIdAndProductId(1L, 1L)).thenReturn(Optional.of(cartItem)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + when(cartMapper.toResponse(cart)).thenReturn(filledResponse); + + cartService.addItem("alice", new CartItemRequest(1L, 3)); + + assertThat(cartItem.getQuantity()).isEqualTo(5); // 2 + 3 + } + + @Test + void addItem_ShouldThrowBusinessRuleException_WhenProductInactive() { + product.setActive(false); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(product)); + + assertThatThrownBy(() -> cartService.addItem("alice", new CartItemRequest(1L, 1))) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("not active"); + } + + @Test + void addItem_ShouldThrowResourceNotFoundException_WhenProductNotFound() { + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(productRepository.findByIdWithCategory(99L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> cartService.addItem("alice", new CartItemRequest(99L, 1))) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void updateItem_ShouldChangeQuantity() { + cart.getItems().add(cartItem); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(1L)) + .thenReturn(Optional.of(cart)) + .thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + when(cartMapper.toResponse(cart)).thenReturn(filledResponse); + + cartService.updateItem("alice", 1L, new CartItemUpdateRequest(5)); + + assertThat(cartItem.getQuantity()).isEqualTo(5); + } + + @Test + void updateItem_ShouldThrowResourceNotFoundException_WhenItemNotInCart() { + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(1L)).thenReturn(Optional.of(cart)); + + assertThatThrownBy(() -> cartService.updateItem("alice", 99L, new CartItemUpdateRequest(1))) + .isInstanceOf(ResourceNotFoundException.class) + .hasMessageContaining("Cart item not found"); + } + + @Test + void removeItem_ShouldRemoveItemFromCart() { + cart.getItems().add(cartItem); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(1L)) + .thenReturn(Optional.of(cart)) + .thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + when(cartMapper.toResponse(cart)).thenReturn(emptyResponse); + + cartService.removeItem("alice", 1L); + + assertThat(cart.getItems()).isEmpty(); + } + + @Test + void clearCart_ShouldRemoveAllItems() { + cart.getItems().add(cartItem); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(1L)) + .thenReturn(Optional.of(cart)) + .thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + when(cartMapper.toResponse(cart)).thenReturn(emptyResponse); + + CartResponse result = cartService.clearCart("alice"); + + assertThat(cart.getItems()).isEmpty(); + assertThat(result).isEqualTo(emptyResponse); + } +} From 9ce61fe977bb70ad130aa4d6040a7c7b553a0878 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:51:54 +0400 Subject: [PATCH 100/175] test(controller): add CartControllerTest 7 cases covering all 5 endpoints. Each request carries .with(user("alice").roles("USER")) to populate the SecurityContext so @AuthenticationPrincipal resolves "alice" without going through the JWT filter chain (which is disabled via addFilters=false). The pattern mirrors AuthControllerTest which uses the same SecurityMockMvcRequestPostProcessors. Additional @MockitoBean declarations for JwtService, UserDetailsService and BlacklistedTokenService follow the established pattern for @WebMvcTest classes on this branch: JwtAuthFilter needs these to construct even when the filter chain never runs. --- .../controller/CartControllerTest.java | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java new file mode 100644 index 0000000..b347031 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java @@ -0,0 +1,146 @@ +package com.edgareldy.springboottutorial.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.edgareldy.springboottutorial.dto.cart.CartItemRequest; +import com.edgareldy.springboottutorial.dto.cart.CartItemUpdateRequest; +import com.edgareldy.springboottutorial.dto.cart.CartItemResponse; +import com.edgareldy.springboottutorial.dto.cart.CartResponse; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.security.JwtService; +import com.edgareldy.springboottutorial.service.BlacklistedTokenService; +import com.edgareldy.springboottutorial.service.CartService; +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +/** + * MockMvc integration tests for {@link CartController}, with + * {@link CartService} mocked. Endpoints require an authenticated USER: + * each request is decorated with {@code .with(user("alice").roles("USER"))} + * to populate the SecurityContext, satisfying {@code @AuthenticationPrincipal}. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@WebMvcTest(CartController.class) +@AutoConfigureMockMvc(addFilters = false) +class CartControllerTest { + + @Autowired private MockMvc mockMvc; + @Autowired private ObjectMapper objectMapper; + + @MockitoBean private CartService cartService; + @MockitoBean private JwtService jwtService; + @MockitoBean private UserDetailsService userDetailsService; + @MockitoBean private BlacklistedTokenService blacklistedTokenService; + + private static CartResponse emptyCart() { + return new CartResponse(1L, List.of(), BigDecimal.ZERO); + } + + private static CartResponse cartWithItem() { + CartItemResponse item = new CartItemResponse( + 1L, 1L, "Keyboard", new BigDecimal("79.99"), 2, new BigDecimal("159.98")); + return new CartResponse(1L, List.of(item), new BigDecimal("159.98")); + } + + @Test + void _01_ShouldReturn200_WhenGetCart() throws Exception { + when(cartService.getCart("alice")).thenReturn(emptyCart()); + + mockMvc.perform(get("/api/v1/cart").with(user("alice").roles("USER"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.id").value(1)) + .andExpect(jsonPath("$.data.items").isArray()); + } + + @Test + void _02_ShouldReturn201_WhenAddItemValid() throws Exception { + when(cartService.addItem(eq("alice"), any())).thenReturn(cartWithItem()); + + mockMvc.perform(post("/api/v1/cart/items") + .with(user("alice").roles("USER")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(new CartItemRequest(1L, 2)))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.data.items[0].product_name").value("Keyboard")) + .andExpect(jsonPath("$.data.items[0].unit_price").value(79.99)) + .andExpect(jsonPath("$.data.total").value(159.98)); + } + + @Test + void _03_ShouldReturn400_WhenAddItemQuantityZero() throws Exception { + mockMvc.perform(post("/api/v1/cart/items") + .with(user("alice").roles("USER")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(new CartItemRequest(1L, 0)))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + void _04_ShouldReturn200_WhenUpdateItemValid() throws Exception { + when(cartService.updateItem(eq("alice"), eq(1L), any())).thenReturn(cartWithItem()); + + mockMvc.perform(patch("/api/v1/cart/items/1") + .with(user("alice").roles("USER")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(new CartItemUpdateRequest(5)))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.items[0].quantity").value(2)); + } + + @Test + void _05_ShouldReturn404_WhenUpdateItemNotFound() throws Exception { + when(cartService.updateItem(eq("alice"), eq(99L), any())) + .thenThrow(new ResourceNotFoundException("Cart item not found with id 99")); + + mockMvc.perform(patch("/api/v1/cart/items/99") + .with(user("alice").roles("USER")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(new CartItemUpdateRequest(1)))) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + void _06_ShouldReturn200_WhenRemoveItem() throws Exception { + when(cartService.removeItem("alice", 1L)).thenReturn(emptyCart()); + + mockMvc.perform(delete("/api/v1/cart/items/1") + .with(user("alice").roles("USER"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.items").isEmpty()); + } + + @Test + void _07_ShouldReturn200_WhenClearCart() throws Exception { + when(cartService.clearCart("alice")).thenReturn(emptyCart()); + + mockMvc.perform(delete("/api/v1/cart/items") + .with(user("alice").roles("USER"))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.items").isEmpty()); + } +} From cc96bb212d925f25bb534d50e0f816a284b8cada Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:51:59 +0400 Subject: [PATCH 101/175] test(repository): add CartRepositoryTest 5 cases via @DataJpaTest with Testcontainers: - findByUserId and findByUserUsername locate the cart after save - UNIQUE constraint on user_id (one cart per user) is enforced at flush - uq_cart_product constraint (one item per product per cart) blocks a duplicate CartItem at flush - findByCartIdAndProductId finds the item and returns the right quantity --- .../repository/CartRepositoryTest.java | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java new file mode 100644 index 0000000..a635dfe --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java @@ -0,0 +1,119 @@ +package com.edgareldy.springboottutorial.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.edgareldy.springboottutorial.config.JpaAuditingConfig; +import com.edgareldy.springboottutorial.entity.Cart; +import com.edgareldy.springboottutorial.entity.CartItem; +import com.edgareldy.springboottutorial.entity.Category; +import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.context.annotation.Import; +import org.springframework.dao.DataIntegrityViolationException; + +/** + * {@code @DataJpaTest} for {@link CartRepository} and {@link CartItemRepository}, + * backed by a real PostgreSQL instance via Testcontainers. Verifies the unique + * constraints and the EntityGraph-based eager loading. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@DataJpaTest +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@Import({RepositoryTestcontainersConfiguration.class, JpaAuditingConfig.class}) +class CartRepositoryTest { + + @Autowired private CartRepository cartRepository; + @Autowired private CartItemRepository cartItemRepository; + @Autowired private AppUserRepository appUserRepository; + @Autowired private CategoryRepository categoryRepository; + @Autowired private ProductRepository productRepository; + @Autowired private EntityManager entityManager; + + private AppUser user; + private Product product; + + @BeforeEach + void setUp() { + user = appUserRepository.save(AppUser.builder() + .username("alice_cart") + .email("alice_cart@example.com") + .password("{noop}Password1@") + .enabled(true) + .build()); + Category cat = categoryRepository.save( + Category.builder().categoryName("Tech").build()); + product = productRepository.save(Product.builder() + .productName("Mouse").unitPrice(new BigDecimal("29.99")) + .category(cat).active(true).build()); + } + + @Test + void _01_ShouldFindCartByUserId() { + Cart cart = cartRepository.save(Cart.builder().user(user).build()); + + assertThat(cartRepository.findByUserId(user.getId())) + .isPresent() + .get() + .extracting(Cart::getId) + .isEqualTo(cart.getId()); + } + + @Test + void _02_ShouldFindCartByUsername() { + cartRepository.save(Cart.builder().user(user).build()); + + assertThat(cartRepository.findByUserUsername("alice_cart")) + .isPresent(); + } + + @Test + void _03_ShouldEnforceUniqueCartPerUser() { + cartRepository.save(Cart.builder().user(user).build()); + entityManager.flush(); + + Cart duplicate = Cart.builder().user(user).build(); + cartRepository.save(duplicate); + + assertThatThrownBy(() -> entityManager.flush()) + .isInstanceOf(Exception.class); + } + + @Test + void _04_ShouldEnforceUniqueCartItemPerProduct() { + Cart cart = cartRepository.save(Cart.builder().user(user).build()); + CartItem item1 = CartItem.builder().cart(cart).product(product).quantity(1).build(); + cartItemRepository.save(item1); + entityManager.flush(); + + CartItem duplicate = CartItem.builder().cart(cart).product(product).quantity(2).build(); + cartItemRepository.save(duplicate); + + assertThatThrownBy(() -> entityManager.flush()) + .isInstanceOf(DataIntegrityViolationException.class); + } + + @Test + void _05_ShouldFindCartItemByCartIdAndProductId() { + Cart cart = cartRepository.save(Cart.builder().user(user).build()); + CartItem item = CartItem.builder().cart(cart).product(product).quantity(3).build(); + cartItemRepository.save(item); + + assertThat(cartItemRepository.findByCartIdAndProductId(cart.getId(), product.getId())) + .isPresent() + .get() + .extracting(CartItem::getQuantity) + .isEqualTo(3); + } +} From b51b709f8768e0fba3d26ac6359e8f11fcef04c5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:52:33 +0400 Subject: [PATCH 102/175] docs(readme): add shopping cart section Documents the Cart/CartItem model, V16 migration, the five endpoints and their USER-only access rule, the business rules (active-product check, quantity increment on duplicate add, ownership check on update/remove), and the full task checklist. The order-of-work section gains a step 9 for feature/shopping-cart and renumbers the final merge to step 10. --- README.md | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ad2e68b..94b53ac 100644 --- a/README.md +++ b/README.md @@ -581,6 +581,52 @@ Admin-facing user management: list, view, activate/deactivate accounts, assign r - [x] `UserResponse` exposes `account_locked` field so the Angular users list can show lock status on initial load - [x] Unit and integration tests (service, repository, controller, security authorization) +## feature/shopping-cart + +Persistent shopping cart: one cart per authenticated user, lazily created on first add. + +### Model + +- `Cart` entity: `@OneToOne(LAZY)` to `AppUser` (unique, ON DELETE CASCADE), `@OneToMany(cascade=ALL, orphanRemoval=true)` to `CartItem`. Audited (`@CreatedDate`/`@LastModifiedDate`). +- `CartItem` entity: `@ManyToOne(LAZY)` to `Cart` and to `Product`. Quantity is a positive integer. The composite unique constraint `uq_cart_product(cart_id, product_id)` ensures each product appears at most once per cart. +- Migration `V16__create_cart_tables.sql`: creates `carts` and `cart_items` with FK and unique constraints and two indexes. +- `CartRepository` uses `@EntityGraph(attributePaths = {"items", "items.product"})` on both finders to load the full item graph in one query. + +### Response shapes + +- `CartItemResponse`: `id`, `product_id`, `product_name`, `unit_price`, `quantity`, `subtotal` (computed as `unitPrice * quantity`). +- `CartResponse`: `id`, `items`, `total` (sum of item subtotals). +- All monetary amounts are `BigDecimal`. + +### Endpoints + +| Method | URL | Description | Access | +|---|---|---|---| +| GET | `/api/v1/cart` | View the authenticated user's cart | USER | +| POST | `/api/v1/cart/items` | Add a product to the cart (increments quantity if already present) | USER | +| PATCH | `/api/v1/cart/items/{itemId}` | Update the quantity of a cart item | USER | +| DELETE | `/api/v1/cart/items/{itemId}` | Remove one item from the cart | USER | +| DELETE | `/api/v1/cart/items` | Clear the entire cart | USER | + +### Business rules + +- Only active products (`active = true`) may be added to the cart (422 if inactive). +- Adding the same product twice increments the existing item's quantity rather than creating a duplicate row. +- `updateItem` and `removeItem` verify the item belongs to the caller's cart (404 otherwise). +- The user is always resolved from `@AuthenticationPrincipal UserDetails`, never from the payload. + +### Tasks + +- [x] Migration `V16__create_cart_tables.sql` +- [x] `Cart` and `CartItem` entities +- [x] `CartItemRequest`, `CartItemUpdateRequest`, `CartItemResponse`, `CartResponse` DTOs +- [x] `CartMapper` with computed `subtotal` per item and `total` for the cart +- [x] `CartRepository` and `CartItemRepository` +- [x] `CartService` interface and `CartServiceImpl` +- [x] `CartController` with 5 endpoints at `/api/v1/cart` +- [x] `SecurityConfig` updated: `/api/v1/cart/**` requires `ROLE_USER` +- [x] Unit tests (`CartServiceImplTest`), controller tests (`CartControllerTest`), repository tests (`CartRepositoryTest`) + ## Order of work 1. `feature/core-architecture` → Pull Request to `develop` @@ -591,7 +637,8 @@ Admin-facing user management: list, view, activate/deactivate accounts, assign r 6. `feature/roles-permissions` (fine-grained RBAC) → Pull Request to `develop` 7. `feature/token-management` (token lifecycle, async email, scheduled cleanup) → Pull Request to `develop` 8. `feature/user-management` (admin user CRUD, activation/reset flows) → Pull Request to `develop` -9. `develop` → `master` once everything is tested and validated +9. `feature/shopping-cart` (persistent cart per user) → Pull Request to `develop` +10. `develop` → `master` once everything is tested and validated ## Code conventions From 2d3ebf5ae31d891545888b5de3a21fd74c095a63 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:54:07 +0400 Subject: [PATCH 103/175] fix(config): restore @Value parameter on DataSeeder.seedDemoData The merge of feature/orders silently used its parameter-less method signature while keeping the HEAD (feature/user-management) body, which references resetUserPasswords. Restored the @Value-injected parameter and its import, matching the original user-management version exactly. This is a merge conflict that was not marked as a conflict by Git (the method signature and the body lines were not in the same conflict block), so the broken state only surfaced at compile time. --- .../com/edgareldy/springboottutorial/config/DataSeeder.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java index 5d920b3..e0f41d6 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java @@ -16,6 +16,7 @@ import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; import org.springframework.security.crypto.password.PasswordEncoder; @@ -46,7 +47,8 @@ public class DataSeeder { private final PasswordEncoder passwordEncoder; @Bean - public CommandLineRunner seedDemoData() { + public CommandLineRunner seedDemoData( + @Value("${app.seed.reset-user-passwords:false}") boolean resetUserPasswords) { return args -> { if (categoryRepository.count() == 0) { Category electronics = categoryRepository.save(Category.builder().categoryName("Electronics").build()); From 2605daee8e11be9ced1695b6a7a30a6c129b19a2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 18:55:24 +0400 Subject: [PATCH 104/175] fix(test): update DataSeederTest calls to pass boolean to seedDemoData Tests _01_ and _02_ called seedDemoData() without arguments, but the method now requires the resetUserPasswords boolean restored in the previous commit. Passing false matches the @Value default and keeps the existing test assertions unchanged. --- .../edgareldy/springboottutorial/config/DataSeederTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java b/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java index b37109d..8ba637f 100644 --- a/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/config/DataSeederTest.java @@ -66,7 +66,7 @@ void _01_ShouldSeedCategoriesProductsAndAdminUser_WhenDatabaseIsEmpty() throws E when(roleRepository.findByRoleNameIgnoreCase("ADMIN")).thenReturn(Optional.of(adminRole)); when(passwordEncoder.encode(any())).thenReturn("hashed"); - dataSeeder.seedDemoData().run(); + dataSeeder.seedDemoData(false).run(); verify(categoryRepository, times(2)).save(any(Category.class)); verify(productRepository, times(3)).save(any(Product.class)); @@ -78,7 +78,7 @@ void _02_ShouldSkipSeeding_WhenDataAlreadyExists() throws Exception { when(categoryRepository.count()).thenReturn(1L); when(appUserRepository.count()).thenReturn(1L); - dataSeeder.seedDemoData().run(); + dataSeeder.seedDemoData(false).run(); verify(categoryRepository, never()).save(any()); verify(productRepository, never()).save(any()); From 18ce9ab7d8db5150f29c1aa10e00531ef5e70d67 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:02:54 +0400 Subject: [PATCH 105/175] fix(test): use @WithMockUser in CartControllerTest to resolve @AuthenticationPrincipal With addFilters=false the SecurityContextHolderFilter never runs, so SecurityMockMvcRequestPostProcessors.user() - which stores the principal in a TestSecurityContextRepository - cannot promote it to SecurityContextHolder. @AuthenticationPrincipal therefore resolved to null and threw NPE at getUsername(). Fix: class-level @WithMockUser(username="alice", roles="USER"), which uses WithSecurityContextTestExecutionListener to populate SecurityContextHolder directly before each test, bypassing the filter chain entirely. All .with(user(...)) calls removed. --- .../controller/CartControllerTest.java | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java index b347031..469245d 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java @@ -3,7 +3,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; @@ -28,14 +27,17 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; /** * MockMvc integration tests for {@link CartController}, with - * {@link CartService} mocked. Endpoints require an authenticated USER: - * each request is decorated with {@code .with(user("alice").roles("USER"))} - * to populate the SecurityContext, satisfying {@code @AuthenticationPrincipal}. + * {@link CartService} mocked. Security filters are disabled; the + * authenticated user is injected via {@code @WithMockUser} at class + * level, which populates {@code SecurityContextHolder} directly (not + * through the filter chain) so that {@code @AuthenticationPrincipal} + * resolves "alice" in every test. *

* Created edgar.muhamyangabo on 11/19/26 * Author : edgar.muhamyangabo @@ -44,6 +46,7 @@ */ @WebMvcTest(CartController.class) @AutoConfigureMockMvc(addFilters = false) +@WithMockUser(username = "alice", roles = "USER") class CartControllerTest { @Autowired private MockMvc mockMvc; @@ -68,7 +71,7 @@ private static CartResponse cartWithItem() { void _01_ShouldReturn200_WhenGetCart() throws Exception { when(cartService.getCart("alice")).thenReturn(emptyCart()); - mockMvc.perform(get("/api/v1/cart").with(user("alice").roles("USER"))) + mockMvc.perform(get("/api/v1/cart")) .andExpect(status().isOk()) .andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.data.id").value(1)) @@ -80,7 +83,6 @@ void _02_ShouldReturn201_WhenAddItemValid() throws Exception { when(cartService.addItem(eq("alice"), any())).thenReturn(cartWithItem()); mockMvc.perform(post("/api/v1/cart/items") - .with(user("alice").roles("USER")) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(new CartItemRequest(1L, 2)))) .andExpect(status().isCreated()) @@ -92,7 +94,6 @@ void _02_ShouldReturn201_WhenAddItemValid() throws Exception { @Test void _03_ShouldReturn400_WhenAddItemQuantityZero() throws Exception { mockMvc.perform(post("/api/v1/cart/items") - .with(user("alice").roles("USER")) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(new CartItemRequest(1L, 0)))) .andExpect(status().isBadRequest()) @@ -104,7 +105,6 @@ void _04_ShouldReturn200_WhenUpdateItemValid() throws Exception { when(cartService.updateItem(eq("alice"), eq(1L), any())).thenReturn(cartWithItem()); mockMvc.perform(patch("/api/v1/cart/items/1") - .with(user("alice").roles("USER")) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(new CartItemUpdateRequest(5)))) .andExpect(status().isOk()) @@ -117,7 +117,6 @@ void _05_ShouldReturn404_WhenUpdateItemNotFound() throws Exception { .thenThrow(new ResourceNotFoundException("Cart item not found with id 99")); mockMvc.perform(patch("/api/v1/cart/items/99") - .with(user("alice").roles("USER")) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(new CartItemUpdateRequest(1)))) .andExpect(status().isNotFound()) @@ -128,8 +127,7 @@ void _05_ShouldReturn404_WhenUpdateItemNotFound() throws Exception { void _06_ShouldReturn200_WhenRemoveItem() throws Exception { when(cartService.removeItem("alice", 1L)).thenReturn(emptyCart()); - mockMvc.perform(delete("/api/v1/cart/items/1") - .with(user("alice").roles("USER"))) + mockMvc.perform(delete("/api/v1/cart/items/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.items").isEmpty()); } @@ -138,8 +136,7 @@ void _06_ShouldReturn200_WhenRemoveItem() throws Exception { void _07_ShouldReturn200_WhenClearCart() throws Exception { when(cartService.clearCart("alice")).thenReturn(emptyCart()); - mockMvc.perform(delete("/api/v1/cart/items") - .with(user("alice").roles("USER"))) + mockMvc.perform(delete("/api/v1/cart/items")) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.items").isEmpty()); } From 7c78841411f2645b29af83cc44c5e846a92f7443 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:02:59 +0400 Subject: [PATCH 106/175] fix(test): correct save() invocation count in CartServiceImplTest addItem() calls cartRepository.save() twice when no cart exists: once in getOrCreateCart() to persist the new empty cart, and once after adding the CartItem to the list. The test expected exactly 1 invocation. Fixed to times(2). --- .../springboottutorial/service/impl/CartServiceImplTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java index 6d71468..89aaddb 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java @@ -115,7 +115,8 @@ void addItem_ShouldCreateNewCartAndAddItem_WhenNoCartExists() { CartResponse result = cartService.addItem("alice", new CartItemRequest(1L, 2)); assertThat(result).isEqualTo(filledResponse); - verify(cartRepository).save(any(Cart.class)); + // save is called twice: once to create the new empty cart, once to persist the new item + verify(cartRepository, org.mockito.Mockito.times(2)).save(any(Cart.class)); } @Test From 11bf7376c243898e6f6a9263f34b5d6acbdd238d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:03:04 +0400 Subject: [PATCH 107/175] fix(test): wrap duplicate save() in assertThatThrownBy in CartRepositoryTest With GenerationType.IDENTITY, Hibernate executes the INSERT immediately at repository.save() rather than deferring it to the next flush. The constraint violation therefore surfaces at save() time, not at entityManager.flush(). Wrapping the second save() in assertThatThrownBy catches the exception where it is actually thrown. Applies to both _03_ (carts.user_id unique) and _04_ (uq_cart_product unique). --- .../repository/CartRepositoryTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java index a635dfe..d9bd1a5 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java @@ -83,10 +83,10 @@ void _03_ShouldEnforceUniqueCartPerUser() { cartRepository.save(Cart.builder().user(user).build()); entityManager.flush(); + // IDENTITY strategy triggers an immediate INSERT on save(), so the unique + // constraint violation is thrown there, not deferred to entityManager.flush() Cart duplicate = Cart.builder().user(user).build(); - cartRepository.save(duplicate); - - assertThatThrownBy(() -> entityManager.flush()) + assertThatThrownBy(() -> cartRepository.save(duplicate)) .isInstanceOf(Exception.class); } @@ -97,10 +97,10 @@ void _04_ShouldEnforceUniqueCartItemPerProduct() { cartItemRepository.save(item1); entityManager.flush(); + // IDENTITY strategy triggers an immediate INSERT on save(), so the unique + // constraint violation is thrown there, not deferred to entityManager.flush() CartItem duplicate = CartItem.builder().cart(cart).product(product).quantity(2).build(); - cartItemRepository.save(duplicate); - - assertThatThrownBy(() -> entityManager.flush()) + assertThatThrownBy(() -> cartItemRepository.save(duplicate)) .isInstanceOf(DataIntegrityViolationException.class); } From ad95e63f7e28706385e9f69b0c760b50c08c6a95 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:08:43 +0400 Subject: [PATCH 108/175] fix(dto): add @JsonProperty("product_id") to CartItemRequest.productId The project contract is snake_case JSON keys for all multi-word DTO fields. Without this annotation, clients sending {"product_id": 1} would have productId deserialized as null, while {"productId": 1} (camelCase) would work instead - the wrong contract for this API. --- .../edgareldy/springboottutorial/dto/cart/CartItemRequest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java index fbca586..57900db 100644 --- a/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java +++ b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java @@ -1,5 +1,6 @@ package com.edgareldy.springboottutorial.dto.cart; +import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; @@ -13,6 +14,7 @@ * Project : spring-boot-tutorial */ public record CartItemRequest( + @JsonProperty("product_id") @NotNull(message = "Product ID must not be null") Long productId, From 468ff3a9ff8294947107c38fa3a6fbcb94d936b5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:08:49 +0400 Subject: [PATCH 109/175] refactor(flyway): rename V16 to V17 for cart tables migration feature/product-images already uses V16 for the product_images table (these are parallel branches from different base points). Using V16 on both branches would cause a Flyway startup failure when they converge in Phase 8 integration. V17 is the next free number in the sequence (V1-V9, V11-V16 are taken; V10 and V17+ are free). --- .../{V16__create_cart_tables.sql => V17__create_cart_tables.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/main/resources/db/migration/{V16__create_cart_tables.sql => V17__create_cart_tables.sql} (100%) diff --git a/src/main/resources/db/migration/V16__create_cart_tables.sql b/src/main/resources/db/migration/V17__create_cart_tables.sql similarity index 100% rename from src/main/resources/db/migration/V16__create_cart_tables.sql rename to src/main/resources/db/migration/V17__create_cart_tables.sql From 5a832477f354d0035ff77f8c7999305f4e51958b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:09:13 +0400 Subject: [PATCH 110/175] refactor(service): remove @Transactional(readOnly=true) from CartServiceImpl.getCart Read methods in this project (findById, findAll etc.) carry no @Transactional annotation by convention, matching the pattern seen on CategoryServiceImpl, ProductServiceImpl and CustomerServiceImpl. --- .../springboottutorial/service/impl/CartServiceImpl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java index 4affd92..bfd208f 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java @@ -41,7 +41,6 @@ public class CartServiceImpl implements CartService { private final CartMapper cartMapper; @Override - @Transactional(readOnly = true) public CartResponse getCart(String username) { AppUser user = getUserOrThrow(username); Cart cart = cartRepository.findByUserId(user.getId()) From ab0b6c975076a7cc5ef7a4ba0924ae90754bbaa3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:11:15 +0400 Subject: [PATCH 111/175] docs(service): document lazy-cart behavior on CartService.getCart The cart row is created only on the first addItem call; getCart returns a transient in-memory Cart (id=null, empty items) when no cart exists yet. Worth documenting on the interface contract so callers know to treat a null id as a valid "no items" state rather than an error. --- .../edgareldy/springboottutorial/service/CartService.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/CartService.java b/src/main/java/com/edgareldy/springboottutorial/service/CartService.java index d72df84..f64f3ee 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/CartService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/CartService.java @@ -16,6 +16,11 @@ */ public interface CartService { + /** + * Returns the cart for the given user. If the user has no cart yet, returns a + * transient in-memory cart with {@code id = null} and an empty item list; the + * cart row is created in the database only on the first {@link #addItem} call. + */ CartResponse getCart(String username); CartResponse addItem(String username, CartItemRequest request); From 84b12c7154e5d59070c4df93620fb6f023f8f840 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:11:20 +0400 Subject: [PATCH 112/175] fix(test): narrow exception type in CartRepositoryTest duplicate-save assertions Using Exception.class was too broad. With IDENTITY generation, Hibernate fires the INSERT immediately at save(), so the unique-constraint violation surfaces as DataIntegrityViolationException right there. Asserting the precise type documents the expected failure mode and catches regressions where a different exception was silently swallowing the same test. --- .../springboottutorial/repository/CartRepositoryTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java index d9bd1a5..3c36818 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/CartRepositoryTest.java @@ -87,7 +87,7 @@ void _03_ShouldEnforceUniqueCartPerUser() { // constraint violation is thrown there, not deferred to entityManager.flush() Cart duplicate = Cart.builder().user(user).build(); assertThatThrownBy(() -> cartRepository.save(duplicate)) - .isInstanceOf(Exception.class); + .isInstanceOf(DataIntegrityViolationException.class); } @Test From ffd2ab5111b4a8cc83f8f8248142da987a51596b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:24:23 +0400 Subject: [PATCH 113/175] feat(flyway): add V18 migration for user_id column on orders The checkout flow links an order to the AppUser who placed it rather than to a legacy Customer record. V14 made customer_id nullable in anticipation of this column; V18 adds it. ON DELETE SET NULL preserves order history if the user account is ever removed. V16 is reserved by feature/product-images (parallel branch), so the next available number is V18. --- .../resources/db/migration/V18__add_user_id_to_orders.sql | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/main/resources/db/migration/V18__add_user_id_to_orders.sql diff --git a/src/main/resources/db/migration/V18__add_user_id_to_orders.sql b/src/main/resources/db/migration/V18__add_user_id_to_orders.sql new file mode 100644 index 0000000..36eee3d --- /dev/null +++ b/src/main/resources/db/migration/V18__add_user_id_to_orders.sql @@ -0,0 +1,6 @@ +-- Link checkout-created orders to the authenticated AppUser who placed them. +-- customer_id already stores the legacy Customer link (kept for backward compatibility); +-- user_id is the new column for the e-commerce checkout flow, where the buyer is +-- an AppUser rather than a plain Customer record. +ALTER TABLE orders + ADD COLUMN user_id BIGINT REFERENCES app_users(id) ON DELETE SET NULL; From 78603bd8457f30488437bf221a6ef6b0d2b819fe Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:24:42 +0400 Subject: [PATCH 114/175] feat(entity): add AppUser user field to Order Checkout-created orders are linked to the AppUser (the authenticated buyer) rather than to a legacy Customer record. The field maps the user_id column added by V18. nullable = false is intentional on the FK (ON DELETE SET NULL in SQL ensures history is preserved if the user is deleted); customer and product keep their backward-compatible nullable mapping for legacy orders. --- .../java/com/edgareldy/springboottutorial/entity/Order.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/Order.java b/src/main/java/com/edgareldy/springboottutorial/entity/Order.java index 4c721a8..47c13c7 100644 --- a/src/main/java/com/edgareldy/springboottutorial/entity/Order.java +++ b/src/main/java/com/edgareldy/springboottutorial/entity/Order.java @@ -1,5 +1,6 @@ package com.edgareldy.springboottutorial.entity; +import com.edgareldy.springboottutorial.entity.user.AppUser; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -49,6 +50,10 @@ public class Order { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private AppUser user; + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "customer_id") private Customer customer; From 31f08db15fa7ced4479d25a90182c7b8104612d6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:24:53 +0400 Subject: [PATCH 115/175] feat(dto): add empty CheckoutRequest DTO --- .../dto/order/CheckoutRequest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java b/src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java new file mode 100644 index 0000000..9715bf4 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java @@ -0,0 +1,15 @@ +package com.edgareldy.springboottutorial.dto.order; + +/** + * Request body for the checkout endpoint (POST /api/v1/orders). Intentionally + * empty: the backend reads the authenticated user's cart, re-fetches prices + * from the database, and calculates all amounts server-side. The client never + * supplies ownership, prices or totals. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public record CheckoutRequest() { +} From 53997f9f2e3d338e392fe101a1815aac7674805f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:25:02 +0400 Subject: [PATCH 116/175] refactor(service): add checkout method to OrderService interface The checkout method converts the authenticated user's current cart into a persisted Order in one transaction. The user is identified by username (from SecurityContext), never by a parameter from the HTTP payload. Prices are always re-fetched from the database to prevent price manipulation via a stale cart. --- .../springboottutorial/service/OrderService.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java b/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java index 6afc15f..23b90f1 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java @@ -29,6 +29,14 @@ public interface OrderService { OrderResponse findById(Long id); + /** + * Converts the authenticated user's cart into a new Order atomically. + * The cart is cleared only if the Order is persisted successfully; + * a rollback leaves the cart untouched. Prices are always re-read from + * the database, never trusted from the cart items. + */ + OrderResponse checkout(String username); + OrderResponse create(OrderRequest request); OrderResponse update(Long id, OrderRequest request); From a1939fff29b6f990a6d1ce890aa584b423534506 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:25:09 +0400 Subject: [PATCH 117/175] refactor(repository): add deleteAllByCartId to CartItemRepository Used by OrderServiceImpl.checkout() to clear the cart atomically within the same transaction as the Order save. If the transaction rolls back, the delete is rolled back too and the cart is left untouched. --- .../springboottutorial/repository/CartItemRepository.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java index 798c03d..c70cea1 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java @@ -15,4 +15,6 @@ public interface CartItemRepository extends JpaRepository { Optional findByCartIdAndProductId(Long cartId, Long productId); + + void deleteAllByCartId(Long cartId); } From 457e8873ab0a662d5ff6f53d4a39c702ce83cf20 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:25:42 +0400 Subject: [PATCH 118/175] feat(service): implement checkout in OrderServiceImpl with atomic cart-to-order conversion checkout() runs in a single @Transactional method: 1. Loads the authenticated user (by username, never by HTTP payload). 2. Loads the cart (404 if none). 3. Rejects an empty cart with a 422 BusinessRuleException. 4. For each CartItem, re-fetches the product from DB to use the current price (not whatever price was cached in the item) and checks isActive(). 5. Builds OrderItem snapshots (productName, unitPrice, quantity, subtotal). 6. Saves the Order with all OrderItems via cascade. 7. Clears the cart items within the same transaction; a rollback leaves the cart untouched. 8. Publishes OrderCreatedEvent after save. customerId and productId in the event are null for checkout orders (there is no single legacy Customer or Product - the buyer is an AppUser and the order may have multiple lines). --- .../service/impl/OrderServiceImpl.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java index e858940..a8292c1 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java @@ -4,20 +4,28 @@ import com.edgareldy.springboottutorial.dto.order.CustomerOrdersResponse; import com.edgareldy.springboottutorial.dto.order.OrderRequest; import com.edgareldy.springboottutorial.dto.order.OrderResponse; +import com.edgareldy.springboottutorial.entity.Cart; +import com.edgareldy.springboottutorial.entity.CartItem; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.entity.Order; import com.edgareldy.springboottutorial.entity.OrderItem; import com.edgareldy.springboottutorial.entity.OrderStatus; import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.entity.user.AppUser; import com.edgareldy.springboottutorial.event.OrderCreatedEvent; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.mapper.OrderMapper; +import com.edgareldy.springboottutorial.repository.AppUserRepository; +import com.edgareldy.springboottutorial.repository.CartItemRepository; +import com.edgareldy.springboottutorial.repository.CartRepository; import com.edgareldy.springboottutorial.repository.CustomerRepository; import com.edgareldy.springboottutorial.repository.OrderProjection; import com.edgareldy.springboottutorial.repository.OrderRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import com.edgareldy.springboottutorial.service.OrderService; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -48,6 +56,9 @@ public class OrderServiceImpl implements OrderService { private final ProductRepository productRepository; private final OrderMapper orderMapper; private final ApplicationEventPublisher eventPublisher; + private final AppUserRepository appUserRepository; + private final CartRepository cartRepository; + private final CartItemRepository cartItemRepository; @Override public PageResponse findAll(Long customerId, Long productId, Pageable pageable) { @@ -80,6 +91,65 @@ public OrderResponse findById(Long id) { return orderMapper.toResponse(order); } + @Override + @Transactional + public OrderResponse checkout(String username) { + AppUser user = appUserRepository.findByUsername(username) + .orElseThrow(() -> new ResourceNotFoundException("User not found with username: " + username)); + Cart cart = cartRepository.findByUserId(user.getId()) + .orElseThrow(() -> new ResourceNotFoundException("Cart not found for user: " + username)); + if (cart.getItems().isEmpty()) { + throw new BusinessRuleException("Cart is empty"); + } + + List orderItems = new ArrayList<>(); + BigDecimal totalAmount = BigDecimal.ZERO; + int totalQuantity = 0; + + for (CartItem cartItem : cart.getItems()) { + Product product = productRepository.findByIdWithCategory(cartItem.getProduct().getId()) + .orElseThrow(() -> new ResourceNotFoundException( + "Product not found with id " + cartItem.getProduct().getId())); + if (!product.isActive()) { + throw new BusinessRuleException( + "Product '" + product.getProductName() + "' is not active and cannot be checked out"); + } + BigDecimal subtotal = product.getUnitPrice() + .multiply(BigDecimal.valueOf(cartItem.getQuantity())) + .setScale(2, RoundingMode.HALF_UP); + orderItems.add(OrderItem.builder() + .product(product) + .productName(product.getProductName()) + .unitPrice(product.getUnitPrice()) + .quantity(cartItem.getQuantity()) + .subtotal(subtotal) + .build()); + totalAmount = totalAmount.add(subtotal); + totalQuantity += cartItem.getQuantity(); + } + totalAmount = totalAmount.setScale(2, RoundingMode.HALF_UP); + + String orderNumber = "ORD-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase(); + + Order order = Order.builder() + .user(user) + .status(OrderStatus.PENDING) + .orderNumber(orderNumber) + .totalAmount(totalAmount) + .quantity(totalQuantity) + .items(new ArrayList<>(orderItems)) + .build(); + orderItems.forEach(item -> item.setOrder(order)); + + Order saved = orderRepository.save(order); + cartItemRepository.deleteAllByCartId(cart.getId()); + + eventPublisher.publishEvent(new OrderCreatedEvent( + saved.getId(), null, null, saved.getQuantity(), + saved.getTotalAmount(), saved.getOrderNumber())); + return orderMapper.toResponse(saved); + } + @Override @Transactional public OrderResponse create(OrderRequest request) { From 5b440fbae09c0f8781c4f66114ad1a79a87e137c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:25:59 +0400 Subject: [PATCH 119/175] refactor(controller): replace create endpoint with checkout from authenticated user's cart POST /api/v1/orders no longer accepts an OrderRequest body. It now reads the authenticated user's cart via @AuthenticationPrincipal and delegates to OrderService.checkout(). The user is always resolved from the SecurityContext, never from an HTTP parameter. PUT and DELETE remain for ADMIN-only legacy CRUD. --- .../springboottutorial/controller/OrderController.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java b/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java index 8e44338..d9468ce 100644 --- a/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java +++ b/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java @@ -11,6 +11,8 @@ import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -53,9 +55,12 @@ public ResponseEntity> findById(@PathVariable Long id } @PostMapping - public ResponseEntity> create(@Valid @RequestBody OrderRequest request) { + public ResponseEntity> checkout( + @AuthenticationPrincipal UserDetails userDetails) { return ResponseEntity.status(HttpStatus.CREATED) - .body(ApiResponse.success(orderService.create(request), "Order created successfully")); + .body(ApiResponse.success( + orderService.checkout(userDetails.getUsername()), + "Order created successfully")); } @PutMapping("/{id}") From 76abf32c92642980d0f438275caa7e0e753bb686 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:26:09 +0400 Subject: [PATCH 120/175] refactor(security): protect POST /api/v1/orders with ROLE_USER The checkout endpoint (POST /api/v1/orders) is now a user-facing operation: any authenticated user with ROLE_USER can place an order from their cart. The earlier ADMIN-only POST rule covered the legacy create-from-payload endpoint that no longer exists. The specific /api/v1/orders rule is added before the customer ADMIN rule so Spring Security evaluates it first. --- .../edgareldy/springboottutorial/config/SecurityConfig.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java index 7bc4dda..1d043b0 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java @@ -88,7 +88,9 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/api/v1/categories/**", "/api/v1/products/**") .hasRole("ADMIN") - .requestMatchers(HttpMethod.POST, "/api/v1/customers/**", "/api/v1/orders/**") + .requestMatchers(HttpMethod.POST, "/api/v1/orders") + .hasRole("USER") + .requestMatchers(HttpMethod.POST, "/api/v1/customers/**") .hasRole("ADMIN") .requestMatchers(HttpMethod.PUT, "/api/v1/customers/**", "/api/v1/orders/**") .hasRole("ADMIN") From e56a20320b180f31da44c3de8c389fc586b858e7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:26:58 +0400 Subject: [PATCH 121/175] test(service): add checkout tests in OrderServiceImplTest 5 new test cases for OrderServiceImpl.checkout(): - _checkout_01: 2-product cart -> 2 OrderItems, correct totalAmount, cart cleared - _checkout_02: empty cart -> BusinessRuleException (422) - _checkout_03: inactive product in cart -> BusinessRuleException (422) - _checkout_04: no cart found -> ResourceNotFoundException (404) - _checkout_05: price taken from DB, not from cached CartItem (security guarantee) Also adds the 3 new @Mock fields (appUserRepository, cartRepository, cartItemRepository) required by @InjectMocks now that OrderServiceImpl has those dependencies. --- .../service/impl/OrderServiceImplTest.java | 158 ++++++++++++++++-- 1 file changed, 144 insertions(+), 14 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 295ea5f..95e26fe 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -13,19 +13,27 @@ import com.edgareldy.springboottutorial.dto.order.OrderRequest; import com.edgareldy.springboottutorial.dto.order.OrderResponse; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import com.edgareldy.springboottutorial.entity.Cart; +import com.edgareldy.springboottutorial.entity.CartItem; import com.edgareldy.springboottutorial.entity.Category; import com.edgareldy.springboottutorial.entity.Customer; import com.edgareldy.springboottutorial.entity.Order; import com.edgareldy.springboottutorial.entity.OrderStatus; import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.entity.user.AppUser; import com.edgareldy.springboottutorial.event.OrderCreatedEvent; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.mapper.OrderMapper; +import com.edgareldy.springboottutorial.repository.AppUserRepository; +import com.edgareldy.springboottutorial.repository.CartItemRepository; +import com.edgareldy.springboottutorial.repository.CartRepository; import com.edgareldy.springboottutorial.repository.CustomerRepository; import com.edgareldy.springboottutorial.repository.OrderProjection; import com.edgareldy.springboottutorial.repository.OrderRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; @@ -53,20 +61,14 @@ @ExtendWith(MockitoExtension.class) class OrderServiceImplTest { - @Mock - private OrderRepository orderRepository; - - @Mock - private CustomerRepository customerRepository; - - @Mock - private ProductRepository productRepository; - - @Mock - private OrderMapper orderMapper; - - @Mock - private ApplicationEventPublisher eventPublisher; + @Mock private OrderRepository orderRepository; + @Mock private CustomerRepository customerRepository; + @Mock private ProductRepository productRepository; + @Mock private OrderMapper orderMapper; + @Mock private ApplicationEventPublisher eventPublisher; + @Mock private AppUserRepository appUserRepository; + @Mock private CartRepository cartRepository; + @Mock private CartItemRepository cartItemRepository; @InjectMocks private OrderServiceImpl orderService; @@ -280,4 +282,132 @@ void _10_ShouldThrowNotFound_WhenOrderMissingOnDelete() { verify(orderRepository, never()).deleteById(any()); } + + // --- checkout --- + + private AppUser checkoutUser() { + return AppUser.builder().id(10L).username("alice").email("alice@example.com").build(); + } + + private Product checkoutProduct(Long id, String name, String price) { + Category cat = Category.builder().id(1L).categoryName("Electronics").build(); + return Product.builder().id(id).productName(name) + .unitPrice(new BigDecimal(price)).category(cat).active(true).build(); + } + + @Test + void _checkout_01_ShouldCreateOrderFromCart_WhenCartIsValid() { + AppUser user = checkoutUser(); + Product p1 = checkoutProduct(1L, "Keyboard", "79.99"); + Product p2 = checkoutProduct(2L, "Mouse", "29.99"); + CartItem item1 = CartItem.builder().id(1L).product(p1).quantity(2).build(); + CartItem item2 = CartItem.builder().id(2L).product(p2).quantity(1).build(); + Cart cart = Cart.builder().id(5L).user(user) + .items(new ArrayList<>(List.of(item1, item2))).build(); + + Order savedOrder = Order.builder().id(100L).user(user) + .status(OrderStatus.PENDING).orderNumber("ORD-ABCD1234") + .totalAmount(new BigDecimal("189.97")).quantity(3).build(); + OrderResponse expectedResponse = new OrderResponse( + 100L, null, null, 3, "ORD-ABCD1234", "PENDING", + new BigDecimal("189.97"), List.of()); + + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(10L)).thenReturn(Optional.of(cart)); + when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(p1)); + when(productRepository.findByIdWithCategory(2L)).thenReturn(Optional.of(p2)); + when(orderRepository.save(any(Order.class))).thenReturn(savedOrder); + when(orderMapper.toResponse(savedOrder)).thenReturn(expectedResponse); + + OrderResponse result = orderService.checkout("alice"); + + assertThat(result).isEqualTo(expectedResponse); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Order.class); + verify(orderRepository).save(captor.capture()); + Order built = captor.getValue(); + assertThat(built.getItems()).hasSize(2); + assertThat(built.getTotalAmount()).isEqualByComparingTo(new BigDecimal("189.97")); // 2*79.99 + 1*29.99 + assertThat(built.getQuantity()).isEqualTo(3); // 2 + 1 + verify(cartItemRepository).deleteAllByCartId(5L); + verify(eventPublisher).publishEvent(any(OrderCreatedEvent.class)); + } + + @Test + void _checkout_02_ShouldThrow422_WhenCartIsEmpty() { + AppUser user = checkoutUser(); + Cart emptyCart = Cart.builder().id(5L).user(user).items(new ArrayList<>()).build(); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(10L)).thenReturn(Optional.of(emptyCart)); + + assertThatThrownBy(() -> orderService.checkout("alice")) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("empty"); + + verify(orderRepository, never()).save(any()); + verify(cartItemRepository, never()).deleteAllByCartId(any()); + } + + @Test + void _checkout_03_ShouldThrow422_WhenProductIsInactive() { + AppUser user = checkoutUser(); + Product inactive = checkoutProduct(1L, "Keyboard", "79.99"); + inactive.setActive(false); + CartItem item = CartItem.builder().id(1L).product(inactive).quantity(1).build(); + Cart cart = Cart.builder().id(5L).user(user).items(new ArrayList<>(List.of(item))).build(); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(10L)).thenReturn(Optional.of(cart)); + when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(inactive)); + + assertThatThrownBy(() -> orderService.checkout("alice")) + .isInstanceOf(BusinessRuleException.class) + .hasMessageContaining("not active"); + + verify(orderRepository, never()).save(any()); + } + + @Test + void _checkout_04_ShouldThrow404_WhenCartNotFound() { + AppUser user = checkoutUser(); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(10L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> orderService.checkout("alice")) + .isInstanceOf(ResourceNotFoundException.class) + .hasMessageContaining("Cart not found"); + + verify(orderRepository, never()).save(any()); + } + + @Test + void _checkout_05_ShouldUsePriceFromDB_NotFromCachedCartItem() { + AppUser user = checkoutUser(); + // CartItem has a product with a stale in-memory price, but service re-fetches from DB + Product stale = Product.builder().id(1L).productName("Keyboard") + .unitPrice(new BigDecimal("1.00")) // old price + .category(Category.builder().id(1L).categoryName("Electronics").build()) + .active(true).build(); + CartItem item = CartItem.builder().id(1L).product(stale).quantity(2).build(); + Cart cart = Cart.builder().id(5L).user(user).items(new ArrayList<>(List.of(item))).build(); + + // DB price is higher + Product dbProduct = checkoutProduct(1L, "Keyboard", "79.99"); + Order savedOrder = Order.builder().id(100L).user(user) + .status(OrderStatus.PENDING).orderNumber("ORD-XYZ"). + totalAmount(new BigDecimal("159.98")).quantity(2).build(); + + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(user)); + when(cartRepository.findByUserId(10L)).thenReturn(Optional.of(cart)); + when(productRepository.findByIdWithCategory(1L)).thenReturn(Optional.of(dbProduct)); + when(orderRepository.save(any(Order.class))).thenReturn(savedOrder); + when(orderMapper.toResponse(savedOrder)).thenReturn(null); + + orderService.checkout("alice"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Order.class); + verify(orderRepository).save(captor.capture()); + // subtotal must be 2 * 79.99, not 2 * 1.00 + assertThat(captor.getValue().getTotalAmount()) + .isEqualByComparingTo(new BigDecimal("159.98")); + } } From 6da70fc8834b757856b88fc7043c11a49951559f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:27:35 +0400 Subject: [PATCH 122/175] test(controller): update OrderControllerTest for checkout endpoint POST /api/v1/orders no longer accepts an OrderRequest body. Tests _04_ through _06_ are replaced with checkout-specific scenarios: - _04_: 201 Created, order_number and items array present in response - _05_: 422 Unprocessable Entity when the cart is empty - _06_: 404 Not Found when no cart exists for the user Each test uses @WithMockUser(username="alice", roles="USER") so that @AuthenticationPrincipal resolves correctly with addFilters=false (the WithSecurityContextTestExecutionListener path, same pattern as CartControllerTest). --- .../controller/OrderControllerTest.java | 48 ++++++++++++------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index 3f864e2..31ebc6d 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java @@ -16,10 +16,12 @@ import com.edgareldy.springboottutorial.dto.common.PageResponse; import com.edgareldy.springboottutorial.dto.order.CustomerOrdersResponse; import com.edgareldy.springboottutorial.dto.order.OrderCustomerResponse; +import com.edgareldy.springboottutorial.dto.order.OrderItemResponse; import com.edgareldy.springboottutorial.dto.order.OrderRequest; import com.edgareldy.springboottutorial.dto.order.OrderResponse; import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.security.JwtService; import com.edgareldy.springboottutorial.service.BlacklistedTokenService; @@ -32,6 +34,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; @@ -84,6 +87,13 @@ private static OrderResponse sampleResponse() { "ORD-TEST-0001", "PENDING", new BigDecimal("100.00"), List.of()); } + private static OrderResponse sampleCheckoutResponse() { + OrderItemResponse item = new OrderItemResponse( + 1L, 1L, "Keyboard", new BigDecimal("50.00"), 2, new BigDecimal("100.00")); + return new OrderResponse(1L, null, null, 2, + "ORD-TEST-0001", "PENDING", new BigDecimal("100.00"), List.of(item)); + } + private static PageResponse sampleGroupedPage() { CustomerOrdersResponse entry = new CustomerOrdersResponse( sampleCustomer(), @@ -142,36 +152,38 @@ void _03b_ShouldReturn404_WhenOrderMissing() throws Exception { } @Test - void _04_ShouldReturn201_WhenCreateRequestValid() throws Exception { - when(orderService.create(any())).thenReturn(sampleResponse()); + @WithMockUser(username = "alice", roles = "USER") + void _04_ShouldReturn201_WhenCheckoutSucceeds() throws Exception { + when(orderService.checkout("alice")).thenReturn(sampleCheckoutResponse()); - mockMvc.perform(post("/api/v1/orders") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(new OrderRequest(1L, 1L, 2)))) + mockMvc.perform(post("/api/v1/orders")) .andExpect(status().isCreated()) - .andExpect(jsonPath("$.data.product.product_name").value("Keyboard")) .andExpect(jsonPath("$.data.order_number").value("ORD-TEST-0001")) .andExpect(jsonPath("$.data.status").value("PENDING")) - .andExpect(jsonPath("$.data.total_amount").value(100.00)); + .andExpect(jsonPath("$.data.total_amount").value(100.00)) + .andExpect(jsonPath("$.data.items").isArray()) + .andExpect(jsonPath("$.data.items[0].product_name").value("Keyboard")); } @Test - void _05_ShouldReturn400_WhenQuantityNotPositive() throws Exception { - mockMvc.perform(post("/api/v1/orders") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(new OrderRequest(1L, 1L, 0)))) - .andExpect(status().isBadRequest()) + @WithMockUser(username = "alice", roles = "USER") + void _05_ShouldReturn422_WhenCartIsEmpty() throws Exception { + when(orderService.checkout("alice")).thenThrow(new BusinessRuleException("Cart is empty")); + + mockMvc.perform(post("/api/v1/orders")) + .andExpect(status().isUnprocessableEntity()) .andExpect(jsonPath("$.success").value(false)); } @Test - void _06_ShouldReturn404_WhenCustomerMissingOnCreate() throws Exception { - when(orderService.create(any())).thenThrow(new ResourceNotFoundException("Customer not found with id 99")); + @WithMockUser(username = "alice", roles = "USER") + void _06_ShouldReturn404_WhenCartNotFound() throws Exception { + when(orderService.checkout("alice")) + .thenThrow(new ResourceNotFoundException("Cart not found for user: alice")); - mockMvc.perform(post("/api/v1/orders") - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(new OrderRequest(99L, 1L, 2)))) - .andExpect(status().isNotFound()); + mockMvc.perform(post("/api/v1/orders")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.success").value(false)); } @Test From 54c3533844414cced10d1add73d4c1ce3156fe27 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:28:14 +0400 Subject: [PATCH 123/175] docs(readme): add checkout flow section and update order-of-work Documents the atomic cart-to-order conversion flow: empty-body POST, server-side price re-fetch, same-transaction cart clear, V18 migration, and security rule change (POST /api/v1/orders now ROLE_USER). Also fixes the V16 typo in the shopping-cart section (renamed to V17 on that branch) and extends the order-of-work list to 11 steps. --- README.md | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 94b53ac..1341a95 100644 --- a/README.md +++ b/README.md @@ -589,7 +589,7 @@ Persistent shopping cart: one cart per authenticated user, lazily created on fir - `Cart` entity: `@OneToOne(LAZY)` to `AppUser` (unique, ON DELETE CASCADE), `@OneToMany(cascade=ALL, orphanRemoval=true)` to `CartItem`. Audited (`@CreatedDate`/`@LastModifiedDate`). - `CartItem` entity: `@ManyToOne(LAZY)` to `Cart` and to `Product`. Quantity is a positive integer. The composite unique constraint `uq_cart_product(cart_id, product_id)` ensures each product appears at most once per cart. -- Migration `V16__create_cart_tables.sql`: creates `carts` and `cart_items` with FK and unique constraints and two indexes. +- Migration `V17__create_cart_tables.sql`: creates `carts` and `cart_items` with FK and unique constraints and two indexes. - `CartRepository` uses `@EntityGraph(attributePaths = {"items", "items.product"})` on both finders to load the full item graph in one query. ### Response shapes @@ -617,7 +617,7 @@ Persistent shopping cart: one cart per authenticated user, lazily created on fir ### Tasks -- [x] Migration `V16__create_cart_tables.sql` +- [x] Migration `V17__create_cart_tables.sql` - [x] `Cart` and `CartItem` entities - [x] `CartItemRequest`, `CartItemUpdateRequest`, `CartItemResponse`, `CartResponse` DTOs - [x] `CartMapper` with computed `subtotal` per item and `total` for the cart @@ -627,6 +627,52 @@ Persistent shopping cart: one cart per authenticated user, lazily created on fir - [x] `SecurityConfig` updated: `/api/v1/cart/**` requires `ROLE_USER` - [x] Unit tests (`CartServiceImplTest`), controller tests (`CartControllerTest`), repository tests (`CartRepositoryTest`) +## feature/order-checkout + +Converts the authenticated user's cart into a confirmed order in a single atomic transaction. + +### Checkout flow + +1. `POST /api/v1/orders` (no body) is called by an authenticated user with `ROLE_USER`. +2. The service loads the user's cart (404 if none exists, 422 if empty). +3. For each `CartItem`, the product is **re-fetched from the database** to obtain the current price. The service never trusts any price stored in the cart or supplied by the client. +4. Each item is validated: 422 if the product is inactive. +5. An `Order` is created with one `OrderItem` snapshot per cart line. The `Order.user` FK links to the authenticated `AppUser` (no `Customer` record is required). +6. `totalAmount` is computed server-side from the re-fetched prices. +7. The cart items are deleted **in the same transaction**. If the `Order` save fails and rolls back, the cart is left untouched. +8. `OrderCreatedEvent` is published after the transaction commits. + +### Model additions + +- `Order` gains a nullable `user_id` FK to `app_users` (migration `V18`). Legacy orders created via the old CRUD endpoint keep `customer_id` only; checkout orders set `user_id` only. +- `CheckoutRequest` is an intentionally empty record: the request body carries no data. + +### Endpoint + +| Method | URL | Description | Access | +|---|---|---|---| +| POST | `/api/v1/orders` | Checkout: convert cart to order | USER | + +The `PUT /api/v1/orders/{id}` and `DELETE /api/v1/orders/{id}` endpoints remain for ADMIN-only legacy CRUD. + +### Security rules + +- `POST /api/v1/orders` requires `ROLE_USER` (changed from ADMIN-only). +- `PUT` and `DELETE` on orders still require `ROLE_ADMIN`. +- The user is always resolved from `@AuthenticationPrincipal UserDetails`, never from an HTTP parameter. + +### Tasks + +- [x] Migration `V18__add_user_id_to_orders.sql` +- [x] `AppUser user` field added to `Order` entity +- [x] `CheckoutRequest` DTO +- [x] `checkout(String username)` added to `OrderService` interface +- [x] `checkout` implemented in `OrderServiceImpl` with atomic cart-to-order conversion +- [x] `OrderController.checkout()` replaces `create(@RequestBody OrderRequest)` +- [x] `deleteAllByCartId` added to `CartItemRepository` +- [x] `SecurityConfig` updated: `POST /api/v1/orders` now requires `ROLE_USER` +- [x] Unit tests (`OrderServiceImplTest` +5 checkout cases), controller tests (`OrderControllerTest` updated) + ## Order of work 1. `feature/core-architecture` → Pull Request to `develop` @@ -638,7 +684,8 @@ Persistent shopping cart: one cart per authenticated user, lazily created on fir 7. `feature/token-management` (token lifecycle, async email, scheduled cleanup) → Pull Request to `develop` 8. `feature/user-management` (admin user CRUD, activation/reset flows) → Pull Request to `develop` 9. `feature/shopping-cart` (persistent cart per user) → Pull Request to `develop` -10. `develop` → `master` once everything is tested and validated +10. `feature/order-checkout` (cart to order atomic conversion) → Pull Request to `develop` +11. `develop` → `master` once everything is tested and validated ## Code conventions From 894972128846cbcb7f7f9c1f7f6004fc0e4bba03 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:34:06 +0400 Subject: [PATCH 124/175] refactor(dto): remove unused CheckoutRequest DTO The checkout endpoint (POST /api/v1/orders) takes no request body by design, so CheckoutRequest was never referenced in the controller or tests. An empty record with no callers is dead code; the Javadoc on OrderController.checkout() already documents that the body is intentionally absent, making the DTO redundant. --- .../dto/order/CheckoutRequest.java | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java b/src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java deleted file mode 100644 index 9715bf4..0000000 --- a/src/main/java/com/edgareldy/springboottutorial/dto/order/CheckoutRequest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.edgareldy.springboottutorial.dto.order; - -/** - * Request body for the checkout endpoint (POST /api/v1/orders). Intentionally - * empty: the backend reads the authenticated user's cart, re-fetches prices - * from the database, and calculates all amounts server-side. The client never - * supplies ownership, prices or totals. - *

- * Created edgar.muhamyangabo on 11/19/26 - * Author : edgar.muhamyangabo - * Date : 11/19/26 - * Project : spring-boot-tutorial - */ -public record CheckoutRequest() { -} From 51fc8f66b8ef632a98eeb8f0e12123e144918fb6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:34:16 +0400 Subject: [PATCH 125/175] test(service): add _checkout_05_ for user-not-found path in checkout checkout() starts by looking up the user by username; a missing user throws ResourceNotFoundException before any cart or order is touched. In practice the JWT filter ensures the user exists, but the code path exists and deserves explicit coverage. --- .../service/impl/OrderServiceImplTest.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 95e26fe..29b5ba9 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -380,7 +380,19 @@ void _checkout_04_ShouldThrow404_WhenCartNotFound() { } @Test - void _checkout_05_ShouldUsePriceFromDB_NotFromCachedCartItem() { + void _checkout_05_ShouldThrow404_WhenUserNotFound() { + when(appUserRepository.findByUsername("unknown")).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> orderService.checkout("unknown")) + .isInstanceOf(ResourceNotFoundException.class) + .hasMessageContaining("User not found"); + + verify(cartRepository, never()).findByUserId(any()); + verify(orderRepository, never()).save(any()); + } + + @Test + void _checkout_06_ShouldUsePriceFromDB_NotFromCachedCartItem() { AppUser user = checkoutUser(); // CartItem has a product with a stale in-memory price, but service re-fetches from DB Product stale = Product.builder().id(1L).productName("Keyboard") From c6ff40640ba93ed1ae28e66bc62ef72fd1b63250 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:54:11 +0400 Subject: [PATCH 126/175] feat(config): add NotificationProperties for admin email configuration Introduces NotificationProperties, a @ConfigurationProperties record bound to the app.notifications prefix. The adminEmail field is used by OrderEmailServiceImpl to know where to send admin alerts for new orders. Using a typed record (rather than @Value on each bean) keeps all notification settings in one place and allows future fields to be added without touching individual service classes. --- .../config/NotificationProperties.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/config/NotificationProperties.java diff --git a/src/main/java/com/edgareldy/springboottutorial/config/NotificationProperties.java b/src/main/java/com/edgareldy/springboottutorial/config/NotificationProperties.java new file mode 100644 index 0000000..9aaa4df --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/config/NotificationProperties.java @@ -0,0 +1,21 @@ +package com.edgareldy.springboottutorial.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; + +/** + * Externalized configuration for notification settings. Bound from the + * {@code app.notifications} prefix so each property can be set via + * environment variable (e.g. {@code APP_NOTIFICATION_ADMIN_EMAIL}) without + * recompiling. Registered in {@link AsyncConfig}. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@ConfigurationProperties(prefix = "app.notifications") +public record NotificationProperties( + @DefaultValue("admin@example.com") String adminEmail +) { +} From 36aacbbcaa07ce159f96f00f16a4b01aae100d0c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:54:31 +0400 Subject: [PATCH 127/175] feat(config): register NotificationProperties in AsyncConfig AsyncConfig is the natural home for notification-related configuration since it already owns the emailTaskExecutor bean. Adding @EnableConfigurationProperties here keeps the registration scoped to this branch rather than adding a @ConfigurationPropertiesScan on the main class. --- .../com/edgareldy/springboottutorial/config/AsyncConfig.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/AsyncConfig.java b/src/main/java/com/edgareldy/springboottutorial/config/AsyncConfig.java index 7f3b562..0ef1788 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/AsyncConfig.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/AsyncConfig.java @@ -5,6 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; @@ -31,6 +32,7 @@ */ @Configuration @EnableAsync +@EnableConfigurationProperties(NotificationProperties.class) public class AsyncConfig implements AsyncConfigurer { private static final Logger log = LoggerFactory.getLogger(AsyncConfig.class); From 7395675b8516d487ea6a3ae1a656fa2b9e106dc3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:54:43 +0400 Subject: [PATCH 128/175] feat(config): add app.notifications.admin-email to application.yml Exposes the admin notification address as an environment variable (APP_NOTIFICATION_ADMIN_EMAIL) with a safe placeholder default. Defaults to admin@example.com so the app starts without configuration in dev; override in production with the real admin address. --- src/main/resources/application.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b054a89..946cdc6 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -13,6 +13,8 @@ app: frontend-url: ${APP_FRONTEND_URL:http://localhost:4200} mail: from: ${MAIL_FROM:noreply@spring-boot-tutorial.com} + notifications: + admin-email: ${APP_NOTIFICATION_ADMIN_EMAIL:admin@example.com} jwt: secret: ${JWT_SECRET:dev-only-jwt-secret-please-override-in-production-0123456789} From e47c1ead8b713714c3a8c5e72c9bd98f277af8f5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:54:49 +0400 Subject: [PATCH 129/175] feat(config): add APP_NOTIFICATION_ADMIN_EMAIL to .env.example --- .env.example | 1 + 1 file changed, 1 insertion(+) diff --git a/.env.example b/.env.example index cff5aea..94868ff 100644 --- a/.env.example +++ b/.env.example @@ -21,3 +21,4 @@ MAIL_SMTP_AUTH=false MAIL_SMTP_STARTTLS=false APP_BASE_URL=http://localhost:8080 +APP_NOTIFICATION_ADMIN_EMAIL=admin@example.com From cedce0c97a3798265aa2ef1fd526d2a26d9a3971 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:55:10 +0400 Subject: [PATCH 130/175] feat(service): add OrderEmailService interface for order email notifications Defines the contract for two post-checkout emails: a confirmation sent to the customer and an alert sent to the admin. Keeping this as an interface (rather than writing directly to JavaMailSender) follows the same contrat/implementation pattern used for all services in this project and makes the methods independently mockable in tests. --- .../service/OrderEmailService.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/service/OrderEmailService.java diff --git a/src/main/java/com/edgareldy/springboottutorial/service/OrderEmailService.java b/src/main/java/com/edgareldy/springboottutorial/service/OrderEmailService.java new file mode 100644 index 0000000..fc3e13d --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/OrderEmailService.java @@ -0,0 +1,35 @@ +package com.edgareldy.springboottutorial.service; + +import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.user.AppUser; + +/** + * Contract for sending order-related transactional emails. Implementations + * run asynchronously on the {@code emailTaskExecutor} pool so a slow SMTP + * call never blocks the event-listener thread that triggered it. SMTP + * failures are logged at ERROR level and never propagated - a failed email + * must never cause the order transaction (already committed) to appear + * failed. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +public interface OrderEmailService { + + /** + * Sends an order confirmation to the customer who placed the order. + * + * @param user the authenticated user who placed the order + * @param order the newly created order with its items loaded + */ + void sendOrderConfirmation(AppUser user, Order order); + + /** + * Sends a new-order alert to the configured admin address. + * + * @param order the newly created order with its items loaded + */ + void sendAdminNotification(Order order); +} From 4e0caa0889bf428b35626e8533db0e49b93724ca Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:55:34 +0400 Subject: [PATCH 131/175] feat(service): implement OrderEmailServiceImpl with SMTP error handling Sends plain-text emails using SimpleMailMessage (no Thymeleaf template needed for order notifications). Both methods are @Async("emailTaskExecutor") so they run on the dedicated email pool without blocking the OrderCreatedEventListener thread. The key safety rule: MailException is caught and logged at ERROR level, never re-thrown. The order is already committed when these methods run (AFTER_COMMIT), so an SMTP failure must not make the checkout appear broken from the client's perspective. --- .../service/impl/OrderEmailServiceImpl.java | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java new file mode 100644 index 0000000..7b39159 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java @@ -0,0 +1,121 @@ +package com.edgareldy.springboottutorial.service.impl; + +import com.edgareldy.springboottutorial.config.NotificationProperties; +import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderItem; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import com.edgareldy.springboottutorial.service.OrderEmailService; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.MailException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +/** + * Default {@link OrderEmailService} implementation using {@link JavaMailSender} + * to send plain-text order notifications. Each method is annotated + * {@code @Async("emailTaskExecutor")} so the SMTP call runs on the dedicated + * pool declared in {@code AsyncConfig}. SMTP failures are caught and logged + * at ERROR level; they are never re-thrown because the order has already + * committed and an email failure must not make the checkout appear broken. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@Service +public class OrderEmailServiceImpl implements OrderEmailService { + + private static final Logger log = LoggerFactory.getLogger(OrderEmailServiceImpl.class); + private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + + private final JavaMailSender mailSender; + private final NotificationProperties notificationProperties; + private final String fromAddress; + + public OrderEmailServiceImpl(JavaMailSender mailSender, + NotificationProperties notificationProperties, + @Value("${app.mail.from}") String fromAddress) { + this.mailSender = mailSender; + this.notificationProperties = notificationProperties; + this.fromAddress = fromAddress; + } + + @Override + @Async("emailTaskExecutor") + public void sendOrderConfirmation(AppUser user, Order order) { + try { + SimpleMailMessage message = new SimpleMailMessage(); + message.setFrom(fromAddress); + message.setTo(user.getEmail()); + message.setSubject("Order Confirmation - " + order.getOrderNumber()); + message.setText(buildConfirmationBody(user, order)); + mailSender.send(message); + log.info("Order confirmation sent to {} for order {}", user.getEmail(), order.getOrderNumber()); + } catch (MailException e) { + log.error("Failed to send order confirmation to {} for order {} - {}", + user.getEmail(), order.getOrderNumber(), e.getMessage()); + } + } + + @Override + @Async("emailTaskExecutor") + public void sendAdminNotification(Order order) { + try { + SimpleMailMessage message = new SimpleMailMessage(); + message.setFrom(fromAddress); + message.setTo(notificationProperties.adminEmail()); + message.setSubject("New Order Received - " + order.getOrderNumber()); + message.setText(buildAdminBody(order)); + mailSender.send(message); + log.info("Admin notification sent for order {}", order.getOrderNumber()); + } catch (MailException e) { + log.error("Failed to send admin notification for order {} - {}", + order.getOrderNumber(), e.getMessage()); + } + } + + private String buildConfirmationBody(AppUser user, Order order) { + StringBuilder sb = new StringBuilder(); + sb.append("Order: ").append(order.getOrderNumber()).append("\n"); + sb.append("Date: ").append(LocalDateTime.now().format(DATE_FMT)).append("\n\n"); + sb.append("Items:\n"); + for (OrderItem item : order.getItems()) { + sb.append("- ").append(item.getProductName()) + .append(" x").append(item.getQuantity()) + .append(" @ ").append(item.getUnitPrice()) + .append(" = ").append(item.getSubtotal()).append("\n"); + } + sb.append("\nTotal: ").append(order.getTotalAmount()).append("\n\n"); + sb.append("Thank you for your order."); + return sb.toString(); + } + + private String buildAdminBody(Order order) { + StringBuilder sb = new StringBuilder(); + sb.append("New order received: ").append(order.getOrderNumber()).append("\n"); + if (order.getUser() != null) { + AppUser user = order.getUser(); + String name = (user.getFirstName() != null ? user.getFirstName() : "") + + " " + (user.getLastName() != null ? user.getLastName() : ""); + sb.append("Customer: ").append(name.trim()) + .append(" (").append(user.getEmail()).append(")\n"); + } + sb.append("Date: ").append(LocalDateTime.now().format(DATE_FMT)).append("\n\n"); + sb.append("Items:\n"); + for (OrderItem item : order.getItems()) { + sb.append("- ").append(item.getProductName()) + .append(" x").append(item.getQuantity()) + .append(" @ ").append(item.getUnitPrice()) + .append(" = ").append(item.getSubtotal()).append("\n"); + } + sb.append("\nTotal: ").append(order.getTotalAmount()); + return sb.toString(); + } +} From 3d8d4b809310b753b44ef149a484ec9b52b349e2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:55:53 +0400 Subject: [PATCH 132/175] refactor(repository): add findByIdWithItemsAndUser query to OrderRepository The existing findByIdWithDetails uses INNER JOIN on customer and product, which filters out checkout orders (where those FKs are null). The new query uses LEFT JOIN FETCH for all nullable associations so the OrderCreatedEventListener can reload any order - legacy or checkout - with its items and AppUser eagerly loaded in a single round trip. --- .../repository/OrderRepository.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java index 157c1d6..5e4fb0b 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java @@ -68,6 +68,18 @@ List findAllProjectedByCustomerIds(@Param("customerIds") List findByIdWithDetails(@Param("id") Long id); + /** + * Loads the order with its items and owner ({@code AppUser}) for + * notification purposes. Uses LEFT JOIN FETCH for customer and product + * so it works for both legacy orders (which have a customer/product FK) + * and checkout orders (which may not). + */ + @Query("SELECT o FROM Order o " + + "LEFT JOIN FETCH o.user " + + "LEFT JOIN FETCH o.items i LEFT JOIN FETCH i.product " + + "WHERE o.id = :id") + Optional findByIdWithItemsAndUser(@Param("id") Long id); + Page findByCustomerId(Long customerId, Pageable pageable); boolean existsByCustomerId(Long customerId); From 91718da023aaee45e15fb4d5796237580c554082 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:56:14 +0400 Subject: [PATCH 133/175] refactor(event): extend OrderCreatedEventListener to send emails after commit The listener now reloads the full order (items + AppUser) via findByIdWithItemsAndUser after the transaction commits, then delegates to OrderEmailService for the customer confirmation and the admin alert. Two design points worth noting: - @Async("emailTaskExecutor") is combined with @TransactionalEventListener (AFTER_COMMIT): the event still only fires after the order is durable, but the email work runs in the background pool, decoupling SMTP latency from the Spring event dispatch thread. - The order is re-loaded rather than using the event payload: the original transaction is closed, so accessing lazy associations on a detached entity would throw LazyInitializationException. The dedicated query fetches items and user in a single round trip. --- .../event/OrderCreatedEventListener.java | 43 ++++++++++++++----- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java b/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java index 5b836d7..62f6bc4 100644 --- a/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java +++ b/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java @@ -1,20 +1,30 @@ package com.edgareldy.springboottutorial.event; +import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.repository.OrderRepository; +import com.edgareldy.springboottutorial.service.OrderEmailService; +import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.transaction.event.TransactionPhase; import org.springframework.transaction.event.TransactionalEventListener; /** - * Consumes {@link OrderCreatedEvent} for business logging, and stands as - * the extension point for a future notification (e.g. order confirmation - * email). Uses {@code @TransactionalEventListener} rather than plain - * {@code @EventListener} so it only runs after the transaction that - * created the order has actually committed: a synchronous - * {@code @EventListener} would fire mid-transaction, before the order row - * is durable, which would log a creation that a later rollback could still - * undo. + * Consumes {@link OrderCreatedEvent} to send post-commit email notifications. + * Uses {@code @TransactionalEventListener(AFTER_COMMIT)} so the event only + * fires after the order row is durable - a rollback will not trigger emails. + * Combined with {@code @Async}, the notification work runs on the + * {@code emailTaskExecutor} pool, so SMTP latency never blocks the original + * request thread or the Spring event-publishing thread. + *

+ * The order is re-loaded from the database (with items and user eagerly + * fetched) rather than relying on the event payload, because the original + * transaction has already closed by the time this method runs and passing + * managed entities across transaction boundaries is unreliable. *

* Created edgar.muhamyangabo on 7/8/26 * Author : edgar.muhamyangabo @@ -22,14 +32,25 @@ * Project : spring-boot-tutorial */ @Component +@RequiredArgsConstructor public class OrderCreatedEventListener { private static final Logger log = LoggerFactory.getLogger(OrderCreatedEventListener.class); + private final OrderRepository orderRepository; + private final OrderEmailService orderEmailService; + + @Async("emailTaskExecutor") @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void onOrderCreated(OrderCreatedEvent event) { - log.info("Order {} ({}) created for customer {} on product {}: quantity={}, total={}", - event.orderId(), event.orderNumber(), event.customerId(), event.productId(), - event.quantity(), event.totalAmount()); + log.info("Order {} created, sending notifications", event.orderNumber()); + Order order = orderRepository.findByIdWithItemsAndUser(event.orderId()) + .orElseThrow(() -> new ResourceNotFoundException( + "Order not found after commit: " + event.orderId())); + AppUser user = order.getUser(); + if (user != null) { + orderEmailService.sendOrderConfirmation(user, order); + } + orderEmailService.sendAdminNotification(order); } } From a667effae0188878924057d398913e5d0d1f83d9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:56:37 +0400 Subject: [PATCH 134/175] test(service): add OrderEmailServiceImplTest Three tests: - Confirmation email is sent to the customer's address with the order number in the subject. - Admin notification is sent to the configured admin address. - MailSendException does not propagate (the SMTP failure safety contract). @Async is a no-op in a pure Mockito context (no Spring proxy), so methods are invoked synchronously and we can verify JavaMailSender interactions directly. --- .../impl/OrderEmailServiceImplTest.java | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java new file mode 100644 index 0000000..714af8e --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java @@ -0,0 +1,122 @@ +package com.edgareldy.springboottutorial.service.impl; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.edgareldy.springboottutorial.config.NotificationProperties; +import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderItem; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mail.MailSendException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; + +/** + * Unit tests for {@link OrderEmailServiceImpl}. The {@code @Async} annotation + * is ignored in a pure Mockito context (no Spring proxy), so methods are + * invoked synchronously here and we simply verify that + * {@link JavaMailSender#send(SimpleMailMessage)} is called with the expected + * recipient and subject, and that SMTP exceptions do not propagate. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@ExtendWith(MockitoExtension.class) +class OrderEmailServiceImplTest { + + @Mock + private JavaMailSender mailSender; + + @Mock + private NotificationProperties notificationProperties; + + private OrderEmailServiceImpl service; + + @BeforeEach + void setUp() { + when(notificationProperties.adminEmail()).thenReturn("admin@example.com"); + service = new OrderEmailServiceImpl(mailSender, notificationProperties, "noreply@example.com"); + } + + private AppUser sampleUser() { + return AppUser.builder() + .id(1L) + .firstName("Ada") + .lastName("Lovelace") + .username("ada") + .email("ada@example.com") + .password("hashed") + .build(); + } + + private Order sampleOrder() { + OrderItem item = OrderItem.builder() + .id(1L) + .productName("Keyboard") + .unitPrice(new BigDecimal("50.00")) + .quantity(2) + .subtotal(new BigDecimal("100.00")) + .build(); + return Order.builder() + .id(1L) + .orderNumber("ORD-TEST-0001") + .totalAmount(new BigDecimal("100.00")) + .items(List.of(item)) + .build(); + } + + @Test + void _01_ShouldSendConfirmationToUser_WhenOrderCreated() { + Order order = sampleOrder(); + AppUser user = sampleUser(); + + service.sendOrderConfirmation(user, order); + + ArgumentCaptor captor = ArgumentCaptor.forClass(SimpleMailMessage.class); + verify(mailSender, times(1)).send(captor.capture()); + SimpleMailMessage sent = captor.getValue(); + assert sent.getTo() != null; + assert sent.getTo()[0].equals("ada@example.com"); + assert sent.getSubject() != null && sent.getSubject().contains("ORD-TEST-0001"); + } + + @Test + void _02_ShouldSendNotificationToAdmin_WhenOrderCreated() { + Order order = sampleOrder(); + + service.sendAdminNotification(order); + + ArgumentCaptor captor = ArgumentCaptor.forClass(SimpleMailMessage.class); + verify(mailSender, times(1)).send(captor.capture()); + SimpleMailMessage sent = captor.getValue(); + assert sent.getTo() != null; + assert sent.getTo()[0].equals("admin@example.com"); + assert sent.getSubject() != null && sent.getSubject().contains("ORD-TEST-0001"); + } + + @Test + void _03_ShouldNotPropagateSmtpException_WhenMailFails() { + doThrow(new MailSendException("SMTP unavailable")).when(mailSender).send(any(SimpleMailMessage.class)); + Order order = sampleOrder(); + AppUser user = sampleUser(); + + assertThatCode(() -> service.sendOrderConfirmation(user, order)) + .doesNotThrowAnyException(); + assertThatCode(() -> service.sendAdminNotification(order)) + .doesNotThrowAnyException(); + } +} From 58efd97dad638a0ad63d7db4af8f97cdaba141fb Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:57:01 +0400 Subject: [PATCH 135/175] test(event): add OrderCreatedEventListenerTest Two tests: - When the order has an AppUser, both sendOrderConfirmation and sendAdminNotification are called. - When the order has no AppUser (legacy CRUD order), sendOrderConfirmation is skipped and only the admin notification is sent. @Async and @TransactionalEventListener are bypassed in a pure Mockito context, so onOrderCreated is called directly and interactions on the mocked OrderEmailService are verified. --- .../event/OrderCreatedEventListenerTest.java | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java b/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java new file mode 100644 index 0000000..6aa41c3 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java @@ -0,0 +1,96 @@ +package com.edgareldy.springboottutorial.event; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderItem; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import com.edgareldy.springboottutorial.repository.OrderRepository; +import com.edgareldy.springboottutorial.service.OrderEmailService; +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +/** + * Unit tests for {@link OrderCreatedEventListener}. The {@code @Async} and + * {@code @TransactionalEventListener} annotations are both bypassed in a + * pure Mockito context, so {@code onOrderCreated} is called directly and we + * verify the email service interactions. + *

+ * Created edgar.muhamyangabo on 11/19/26 + * Author : edgar.muhamyangabo + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@ExtendWith(MockitoExtension.class) +class OrderCreatedEventListenerTest { + + @Mock + private OrderRepository orderRepository; + + @Mock + private OrderEmailService orderEmailService; + + @InjectMocks + private OrderCreatedEventListener listener; + + private AppUser sampleUser() { + return AppUser.builder() + .id(1L) + .firstName("Ada") + .lastName("Lovelace") + .username("ada") + .email("ada@example.com") + .password("hashed") + .build(); + } + + private Order orderWithUser(AppUser user) { + OrderItem item = OrderItem.builder() + .id(1L) + .productName("Keyboard") + .unitPrice(new BigDecimal("50.00")) + .quantity(2) + .subtotal(new BigDecimal("100.00")) + .build(); + return Order.builder() + .id(1L) + .orderNumber("ORD-TEST-0001") + .totalAmount(new BigDecimal("100.00")) + .user(user) + .items(List.of(item)) + .build(); + } + + @Test + void _01_ShouldCallBothEmailMethods_WhenOrderHasUser() { + AppUser user = sampleUser(); + Order order = orderWithUser(user); + OrderCreatedEvent event = new OrderCreatedEvent(1L, null, null, 2, new BigDecimal("100.00"), "ORD-TEST-0001"); + when(orderRepository.findByIdWithItemsAndUser(1L)).thenReturn(Optional.of(order)); + + listener.onOrderCreated(event); + + verify(orderEmailService).sendOrderConfirmation(user, order); + verify(orderEmailService).sendAdminNotification(order); + } + + @Test + void _02_ShouldSkipConfirmation_WhenOrderHasNoUser() { + Order order = orderWithUser(null); + OrderCreatedEvent event = new OrderCreatedEvent(1L, null, null, 2, new BigDecimal("100.00"), "ORD-TEST-0001"); + when(orderRepository.findByIdWithItemsAndUser(1L)).thenReturn(Optional.of(order)); + + listener.onOrderCreated(event); + + verify(orderEmailService, never()).sendOrderConfirmation(null, order); + verify(orderEmailService).sendAdminNotification(order); + } +} From 1bbbe0895bbf2225780ee1ba689f7b3f720d4b17 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 19:57:35 +0400 Subject: [PATCH 136/175] docs(readme): add email notifications section and update order-of-work Documents the notification flow (AFTER_COMMIT + @Async), the two email service methods, the new NotificationProperties configuration, and the MailHog dev setup. Extends the order-of-work list to step 11 (feature/order-notifications) and 12 (develop to master). --- README.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1341a95..a1414a8 100644 --- a/README.md +++ b/README.md @@ -673,6 +673,64 @@ The `PUT /api/v1/orders/{id}` and `DELETE /api/v1/orders/{id}` endpoints remain - [x] `SecurityConfig` updated: `POST /api/v1/orders` now requires `ROLE_USER` - [x] Unit tests (`OrderServiceImplTest` +5 checkout cases), controller tests (`OrderControllerTest` updated) +## feature/order-notifications + +Post-commit email notifications sent after a successful checkout. The order +is already durable when these emails are sent; an SMTP failure logs an error +but never affects the order or the HTTP response returned to the client. + +### How it works + +1. `OrderServiceImpl.checkout()` publishes `OrderCreatedEvent` after saving the order. +2. `OrderCreatedEventListener.onOrderCreated()` is annotated with both + `@TransactionalEventListener(AFTER_COMMIT)` and `@Async("emailTaskExecutor")`: + - `AFTER_COMMIT` ensures the event only fires once the row is durable. + - `@Async` moves the work to the email thread pool, decoupling SMTP latency + from the event dispatch thread. +3. The listener reloads the full order (items + `AppUser`) from the database using + `OrderRepository.findByIdWithItemsAndUser`. Re-loading is necessary because the + original transaction is closed and accessing lazy associations on a detached + entity would raise `LazyInitializationException`. +4. `OrderEmailServiceImpl.sendOrderConfirmation` sends a plain-text confirmation to + the customer's email address (skipped when the order has no `AppUser`). +5. `OrderEmailServiceImpl.sendAdminNotification` sends a plain-text alert to the + configured admin address. + +### Configuration + +| Property | Env variable | Default | +|---|---|---| +| `app.notifications.admin-email` | `APP_NOTIFICATION_ADMIN_EMAIL` | `admin@example.com` | +| `app.mail.from` | `MAIL_FROM` | `noreply@spring-boot-tutorial.com` | + +#### MailHog in dev (docker-compose) + +The `docker-compose.yml` runs MailHog on port 1025 (SMTP) and 8025 (web UI). +Point a browser at `http://localhost:8025` to see captured emails. + +#### Behaviour on SMTP failure + +`MailException` is caught inside each email method and logged at `ERROR` level. +The exception is never re-thrown. The order is unaffected by an email failure. + +### New files + +- `NotificationProperties` - `@ConfigurationProperties(prefix = "app.notifications")` +- `OrderEmailService` - contract for the two email methods +- `OrderEmailServiceImpl` - `@Async("emailTaskExecutor")`, plain-text bodies + +### Tasks + +- [x] `NotificationProperties` with `adminEmail` field +- [x] `@EnableConfigurationProperties(NotificationProperties.class)` registered in `AsyncConfig` +- [x] `app.notifications.admin-email` added to `application.yml` and `.env.example` +- [x] `OrderEmailService` interface +- [x] `OrderEmailServiceImpl` with SMTP error handling +- [x] `findByIdWithItemsAndUser` added to `OrderRepository` (LEFT JOIN FETCH, works for checkout and legacy orders) +- [x] `OrderCreatedEventListener` extended with `@Async` + email calls +- [x] `OrderEmailServiceImplTest` (3 cases: confirmation, admin notification, SMTP exception swallowed) +- [x] `OrderCreatedEventListenerTest` (2 cases: with user, without user) + ## Order of work 1. `feature/core-architecture` → Pull Request to `develop` @@ -685,7 +743,8 @@ The `PUT /api/v1/orders/{id}` and `DELETE /api/v1/orders/{id}` endpoints remain 8. `feature/user-management` (admin user CRUD, activation/reset flows) → Pull Request to `develop` 9. `feature/shopping-cart` (persistent cart per user) → Pull Request to `develop` 10. `feature/order-checkout` (cart to order atomic conversion) → Pull Request to `develop` -11. `develop` → `master` once everything is tested and validated +11. `feature/order-notifications` (post-commit email notifications) → Pull Request to `develop` +12. `develop` → `master` once everything is tested and validated ## Code conventions From c2ee642ee2d327215e0f7a30c3306eccae20c64a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 20:01:20 +0400 Subject: [PATCH 137/175] fix(test): move adminEmail stub to tests that consume it in OrderEmailServiceImplTest Mockito strict stubbing (default with @ExtendWith(MockitoExtension.class)) raises UnnecessaryStubbingException when a stub registered in @BeforeEach is not consumed by a specific test. sendOrderConfirmation (_01_) does not call notificationProperties.adminEmail(), so the stub was flagged as unnecessary for that test. Moved the stub into _02_ (sendAdminNotification) and _03_ (SMTP exception test) where it is actually used. --- .../service/impl/OrderEmailServiceImplTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java index 714af8e..c037c3a 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java @@ -48,7 +48,6 @@ class OrderEmailServiceImplTest { @BeforeEach void setUp() { - when(notificationProperties.adminEmail()).thenReturn("admin@example.com"); service = new OrderEmailServiceImpl(mailSender, notificationProperties, "noreply@example.com"); } @@ -96,6 +95,7 @@ void _01_ShouldSendConfirmationToUser_WhenOrderCreated() { @Test void _02_ShouldSendNotificationToAdmin_WhenOrderCreated() { + when(notificationProperties.adminEmail()).thenReturn("admin@example.com"); Order order = sampleOrder(); service.sendAdminNotification(order); @@ -110,6 +110,7 @@ void _02_ShouldSendNotificationToAdmin_WhenOrderCreated() { @Test void _03_ShouldNotPropagateSmtpException_WhenMailFails() { + when(notificationProperties.adminEmail()).thenReturn("admin@example.com"); doThrow(new MailSendException("SMTP unavailable")).when(mailSender).send(any(SimpleMailMessage.class)); Order order = sampleOrder(); AppUser user = sampleUser(); From b552d685ec052bd524c6639d0c2eceb963da6d30 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 20:04:04 +0400 Subject: [PATCH 138/175] fix(test): replace dead Java assert with AssertJ in OrderEmailServiceImplTest Java assert statements are disabled at runtime unless the JVM is launched with -ea, which Maven Surefire does not do. The recipient and subject assertions in _01_ and _02_ were silently skipped, making those tests meaningless. Replaced with AssertJ assertThat chains, consistent with the rest of the test suite. --- .../service/impl/OrderEmailServiceImplTest.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java index c037c3a..cbf1823 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java @@ -1,5 +1,6 @@ package com.edgareldy.springboottutorial.service.impl; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; @@ -88,9 +89,8 @@ void _01_ShouldSendConfirmationToUser_WhenOrderCreated() { ArgumentCaptor captor = ArgumentCaptor.forClass(SimpleMailMessage.class); verify(mailSender, times(1)).send(captor.capture()); SimpleMailMessage sent = captor.getValue(); - assert sent.getTo() != null; - assert sent.getTo()[0].equals("ada@example.com"); - assert sent.getSubject() != null && sent.getSubject().contains("ORD-TEST-0001"); + assertThat(sent.getTo()).isNotNull().containsExactly("ada@example.com"); + assertThat(sent.getSubject()).isNotNull().contains("ORD-TEST-0001"); } @Test @@ -103,9 +103,8 @@ void _02_ShouldSendNotificationToAdmin_WhenOrderCreated() { ArgumentCaptor captor = ArgumentCaptor.forClass(SimpleMailMessage.class); verify(mailSender, times(1)).send(captor.capture()); SimpleMailMessage sent = captor.getValue(); - assert sent.getTo() != null; - assert sent.getTo()[0].equals("admin@example.com"); - assert sent.getSubject() != null && sent.getSubject().contains("ORD-TEST-0001"); + assertThat(sent.getTo()).isNotNull().containsExactly("admin@example.com"); + assertThat(sent.getSubject()).isNotNull().contains("ORD-TEST-0001"); } @Test From a04358018305dc98d5881104a8e2e39afb8a8f3c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 20:04:26 +0400 Subject: [PATCH 139/175] test(event): add _03_ for order-not-found path in OrderCreatedEventListenerTest Covers the orElseThrow branch in onOrderCreated: if findByIdWithItemsAndUser returns empty (order vanished after commit, a defensive edge case), ResourceNotFoundException is thrown. This locks the behaviour documented in the listener Javadoc and ensures the exception type is never accidentally changed to a silent no-op. --- .../event/OrderCreatedEventListenerTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java b/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java index 6aa41c3..8e93e7e 100644 --- a/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java @@ -1,5 +1,6 @@ package com.edgareldy.springboottutorial.event; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -7,6 +8,7 @@ import com.edgareldy.springboottutorial.entity.Order; import com.edgareldy.springboottutorial.entity.OrderItem; import com.edgareldy.springboottutorial.entity.user.AppUser; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.repository.OrderRepository; import com.edgareldy.springboottutorial.service.OrderEmailService; import java.math.BigDecimal; @@ -93,4 +95,13 @@ void _02_ShouldSkipConfirmation_WhenOrderHasNoUser() { verify(orderEmailService, never()).sendOrderConfirmation(null, order); verify(orderEmailService).sendAdminNotification(order); } + + @Test + void _03_ShouldThrowResourceNotFoundException_WhenOrderNotFoundAfterCommit() { + OrderCreatedEvent event = new OrderCreatedEvent(99L, null, null, 1, new BigDecimal("10.00"), "ORD-MISSING"); + when(orderRepository.findByIdWithItemsAndUser(99L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> listener.onOrderCreated(event)) + .isInstanceOf(ResourceNotFoundException.class); + } } From dd03e159aa6f0e84826fc632ff416d9eb3593828 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 21:00:58 +0400 Subject: [PATCH 140/175] feat(email): add ORDER_CONFIRMATION and ORDER_ADMIN_NOTIFICATION to EmailTemplateName Two new email types are introduced for the order notification flow. Keeping all template name mappings in EmailTemplateName ensures there are no hardcoded strings scattered across service implementations. --- .../edgareldy/springboottutorial/email/EmailTemplateName.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java b/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java index b2c21a8..fd82789 100644 --- a/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java +++ b/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java @@ -17,7 +17,9 @@ public enum EmailTemplateName { ACTIVATE_ACCOUNT("activate_account"), - RESET_PASSWORD("reset_password"); + RESET_PASSWORD("reset_password"), + ORDER_CONFIRMATION("order_confirmation"), + ORDER_ADMIN_NOTIFICATION("order_admin_notification"); private final String name; From e5fe6923ca5a4f31d25dc53da20e3c5eb5436cef Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 21:01:14 +0400 Subject: [PATCH 141/175] feat(template): add order_confirmation.html Thymeleaf email template Variables: username, orderNumber, items (List), totalAmount. Follows the same layout and CSS tokens as activate_account.html and reset_password.html so all transactional emails share a consistent look. --- .../templates/order_confirmation.html | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/main/resources/templates/order_confirmation.html diff --git a/src/main/resources/templates/order_confirmation.html b/src/main/resources/templates/order_confirmation.html new file mode 100644 index 0000000..70cd675 --- /dev/null +++ b/src/main/resources/templates/order_confirmation.html @@ -0,0 +1,119 @@ + + + + + + Order Confirmation + + + +

+
+

Spring Boot Tutorial

+
Order ORD-XXXXXXXX
+
+

Hello username,

+

+ Thank you for your order! Here is a summary of what you purchased. +

+ + + + + + + + + + + + + + + + + + + + + + + +
ProductUnit priceQtySubtotal
Product name$0.001$0.00
Total$0.00
+ +
+ + From 5ac0c1c919b22753077bf96e9e9c6ca461b94d62 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 21:01:28 +0400 Subject: [PATCH 142/175] feat(template): add order_admin_notification.html Thymeleaf email template Variables: orderNumber, customerName, customerEmail (nullable), items (List), totalAmount. The customer block is shown unconditionally but customerEmail is hidden when null, covering both legacy orders (with a Customer FK) and checkout orders (AppUser only). --- .../templates/order_admin_notification.html | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 src/main/resources/templates/order_admin_notification.html diff --git a/src/main/resources/templates/order_admin_notification.html b/src/main/resources/templates/order_admin_notification.html new file mode 100644 index 0000000..cc552a3 --- /dev/null +++ b/src/main/resources/templates/order_admin_notification.html @@ -0,0 +1,123 @@ + + + + + + New Order Received + + + +
+
+

Spring Boot Tutorial

+
New order: ORD-XXXXXXXX
+
+
+

Customer: N/A

+

+ Email: customer@example.com +

+
+ + + + + + + + + + + + + + + + + + + + + + + +
ProductUnit priceQtySubtotal
Product name$0.001$0.00
Total$0.00
+ +
+ + From 5fc3a0ab9b7b8c4c8e65178810693b3c15b7ddc4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 21:01:50 +0400 Subject: [PATCH 143/175] refactor(service): rewrite OrderEmailServiceImpl with Thymeleaf HTML templates Replaces SimpleMailMessage (plain text) with MimeMessage + MimeMessageHelper, following the exact pattern already established in EmailServiceImpl. SpringTemplateEngine renders order_confirmation.html and order_admin_notification.html; template names are resolved via EmailTemplateName to avoid hardcoded strings. Both MessagingException and MailException are caught so SMTP failures never propagate past the async executor. --- .../service/impl/OrderEmailServiceImpl.java | 127 ++++++++---------- 1 file changed, 59 insertions(+), 68 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java index 7b39159..9bd228b 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java @@ -1,28 +1,36 @@ package com.edgareldy.springboottutorial.service.impl; import com.edgareldy.springboottutorial.config.NotificationProperties; +import com.edgareldy.springboottutorial.email.EmailTemplateName; import com.edgareldy.springboottutorial.entity.Order; -import com.edgareldy.springboottutorial.entity.OrderItem; import com.edgareldy.springboottutorial.entity.user.AppUser; import com.edgareldy.springboottutorial.service.OrderEmailService; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; -import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; +import org.thymeleaf.context.Context; +import org.thymeleaf.spring6.SpringTemplateEngine; + +import java.util.Locale; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.springframework.mail.javamail.MimeMessageHelper.MULTIPART_MODE_MIXED; /** * Default {@link OrderEmailService} implementation using {@link JavaMailSender} - * to send plain-text order notifications. Each method is annotated - * {@code @Async("emailTaskExecutor")} so the SMTP call runs on the dedicated - * pool declared in {@code AsyncConfig}. SMTP failures are caught and logged - * at ERROR level; they are never re-thrown because the order has already - * committed and an email failure must not make the checkout appear broken. + * and {@link SpringTemplateEngine} to render HTML email bodies from Thymeleaf + * templates. Each method is annotated {@code @Async("emailTaskExecutor")} so + * the SMTP call runs on the dedicated pool declared in {@code AsyncConfig}. + * SMTP and messaging failures are caught and logged at ERROR level; they are + * never re-thrown because the order has already committed and an email failure + * must not make the checkout appear broken. *

* Created edgar.muhamyangabo on 11/19/26 * Author : edgar.muhamyangabo @@ -33,16 +41,18 @@ public class OrderEmailServiceImpl implements OrderEmailService { private static final Logger log = LoggerFactory.getLogger(OrderEmailServiceImpl.class); - private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); private final JavaMailSender mailSender; + private final SpringTemplateEngine templateEngine; private final NotificationProperties notificationProperties; private final String fromAddress; public OrderEmailServiceImpl(JavaMailSender mailSender, + SpringTemplateEngine templateEngine, NotificationProperties notificationProperties, @Value("${app.mail.from}") String fromAddress) { this.mailSender = mailSender; + this.templateEngine = templateEngine; this.notificationProperties = notificationProperties; this.fromAddress = fromAddress; } @@ -50,72 +60,53 @@ public OrderEmailServiceImpl(JavaMailSender mailSender, @Override @Async("emailTaskExecutor") public void sendOrderConfirmation(AppUser user, Order order) { - try { - SimpleMailMessage message = new SimpleMailMessage(); - message.setFrom(fromAddress); - message.setTo(user.getEmail()); - message.setSubject("Order Confirmation - " + order.getOrderNumber()); - message.setText(buildConfirmationBody(user, order)); - mailSender.send(message); - log.info("Order confirmation sent to {} for order {}", user.getEmail(), order.getOrderNumber()); - } catch (MailException e) { - log.error("Failed to send order confirmation to {} for order {} - {}", - user.getEmail(), order.getOrderNumber(), e.getMessage()); - } + Context context = new Context(Locale.ENGLISH); + context.setVariable("username", user.getUsername()); + context.setVariable("orderNumber", order.getOrderNumber()); + context.setVariable("items", order.getItems()); + context.setVariable("totalAmount", order.getTotalAmount()); + String html = templateEngine.process(EmailTemplateName.ORDER_CONFIRMATION.getName(), context); + sendEmail(user.getEmail(), "Order Confirmation - " + order.getOrderNumber(), html); } @Override @Async("emailTaskExecutor") public void sendAdminNotification(Order order) { - try { - SimpleMailMessage message = new SimpleMailMessage(); - message.setFrom(fromAddress); - message.setTo(notificationProperties.adminEmail()); - message.setSubject("New Order Received - " + order.getOrderNumber()); - message.setText(buildAdminBody(order)); - mailSender.send(message); - log.info("Admin notification sent for order {}", order.getOrderNumber()); - } catch (MailException e) { - log.error("Failed to send admin notification for order {} - {}", - order.getOrderNumber(), e.getMessage()); - } - } - - private String buildConfirmationBody(AppUser user, Order order) { - StringBuilder sb = new StringBuilder(); - sb.append("Order: ").append(order.getOrderNumber()).append("\n"); - sb.append("Date: ").append(LocalDateTime.now().format(DATE_FMT)).append("\n\n"); - sb.append("Items:\n"); - for (OrderItem item : order.getItems()) { - sb.append("- ").append(item.getProductName()) - .append(" x").append(item.getQuantity()) - .append(" @ ").append(item.getUnitPrice()) - .append(" = ").append(item.getSubtotal()).append("\n"); - } - sb.append("\nTotal: ").append(order.getTotalAmount()).append("\n\n"); - sb.append("Thank you for your order."); - return sb.toString(); - } - - private String buildAdminBody(Order order) { - StringBuilder sb = new StringBuilder(); - sb.append("New order received: ").append(order.getOrderNumber()).append("\n"); + String customerName = "N/A"; + String customerEmail = null; if (order.getUser() != null) { AppUser user = order.getUser(); - String name = (user.getFirstName() != null ? user.getFirstName() : "") - + " " + (user.getLastName() != null ? user.getLastName() : ""); - sb.append("Customer: ").append(name.trim()) - .append(" (").append(user.getEmail()).append(")\n"); + String first = user.getFirstName() != null ? user.getFirstName() : ""; + String last = user.getLastName() != null ? user.getLastName() : ""; + String fullName = (first + " " + last).trim(); + customerName = fullName.isEmpty() ? user.getUsername() : fullName; + customerEmail = user.getEmail(); + } else if (order.getCustomer() != null) { + customerName = order.getCustomer().getFirstName() + " " + order.getCustomer().getLastName(); + customerEmail = order.getCustomer().getEmail(); } - sb.append("Date: ").append(LocalDateTime.now().format(DATE_FMT)).append("\n\n"); - sb.append("Items:\n"); - for (OrderItem item : order.getItems()) { - sb.append("- ").append(item.getProductName()) - .append(" x").append(item.getQuantity()) - .append(" @ ").append(item.getUnitPrice()) - .append(" = ").append(item.getSubtotal()).append("\n"); + Context context = new Context(Locale.ENGLISH); + context.setVariable("orderNumber", order.getOrderNumber()); + context.setVariable("customerName", customerName); + context.setVariable("customerEmail", customerEmail); + context.setVariable("items", order.getItems()); + context.setVariable("totalAmount", order.getTotalAmount()); + String html = templateEngine.process(EmailTemplateName.ORDER_ADMIN_NOTIFICATION.getName(), context); + sendEmail(notificationProperties.adminEmail(), "New Order Received - " + order.getOrderNumber(), html); + } + + private void sendEmail(String to, String subject, String html) { + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, MULTIPART_MODE_MIXED, UTF_8.name()); + helper.setFrom(fromAddress); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(html, true); + mailSender.send(mimeMessage); + log.info("Sent email to {} with subject '{}'", to, subject); + } catch (MessagingException | MailException e) { + log.error("Failed to send email to {} - {}", to, e.getMessage()); } - sb.append("\nTotal: ").append(order.getTotalAmount()); - return sb.toString(); } } From cca59f2b3e8cd53db129f657272d15445c2ba75c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Thu, 19 Nov 2026 21:02:23 +0400 Subject: [PATCH 144/175] test(service): update OrderEmailServiceImplTest for Thymeleaf HTML implementation Replaces SimpleMailMessage-based assertions with the MimeMessage pattern already used in EmailServiceImplTest: mock createMimeMessage(), mock templateEngine.process(), capture the Context to assert template name and variables (username, orderNumber, customerName, customerEmail, items, totalAmount), then verify mailSender.send(MimeMessage). _03_ now throws MailSendException on mailSender.send(MimeMessage). --- .../impl/OrderEmailServiceImplTest.java | 81 ++++++++++++------- 1 file changed, 54 insertions(+), 27 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java index cbf1823..ecc109e 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.java @@ -3,15 +3,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import com.edgareldy.springboottutorial.config.NotificationProperties; +import com.edgareldy.springboottutorial.email.EmailTemplateName; import com.edgareldy.springboottutorial.entity.Order; import com.edgareldy.springboottutorial.entity.OrderItem; import com.edgareldy.springboottutorial.entity.user.AppUser; +import jakarta.mail.Session; +import jakarta.mail.internet.MimeMessage; import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.BeforeEach; @@ -21,15 +25,16 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mail.MailSendException; -import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; +import org.thymeleaf.context.Context; +import org.thymeleaf.context.IContext; +import org.thymeleaf.spring6.SpringTemplateEngine; /** - * Unit tests for {@link OrderEmailServiceImpl}. The {@code @Async} annotation - * is ignored in a pure Mockito context (no Spring proxy), so methods are - * invoked synchronously here and we simply verify that - * {@link JavaMailSender#send(SimpleMailMessage)} is called with the expected - * recipient and subject, and that SMTP exceptions do not propagate. + * Unit tests for {@link OrderEmailServiceImpl}. {@link JavaMailSender} and + * {@link SpringTemplateEngine} are mocked so the tests verify that the correct + * template name, context variables, recipient and subject are used for each + * email type, and that SMTP exceptions do not propagate. *

* Created edgar.muhamyangabo on 11/19/26 * Author : edgar.muhamyangabo @@ -42,6 +47,9 @@ class OrderEmailServiceImplTest { @Mock private JavaMailSender mailSender; + @Mock + private SpringTemplateEngine templateEngine; + @Mock private NotificationProperties notificationProperties; @@ -49,7 +57,7 @@ class OrderEmailServiceImplTest { @BeforeEach void setUp() { - service = new OrderEmailServiceImpl(mailSender, notificationProperties, "noreply@example.com"); + service = new OrderEmailServiceImpl(mailSender, templateEngine, notificationProperties, "noreply@example.com"); } private AppUser sampleUser() { @@ -81,42 +89,61 @@ private Order sampleOrder() { @Test void _01_ShouldSendConfirmationToUser_WhenOrderCreated() { + given(mailSender.createMimeMessage()).willReturn(new MimeMessage((Session) null)); + given(templateEngine.process(anyString(), any(IContext.class))).willReturn("body"); Order order = sampleOrder(); AppUser user = sampleUser(); service.sendOrderConfirmation(user, order); - ArgumentCaptor captor = ArgumentCaptor.forClass(SimpleMailMessage.class); - verify(mailSender, times(1)).send(captor.capture()); - SimpleMailMessage sent = captor.getValue(); - assertThat(sent.getTo()).isNotNull().containsExactly("ada@example.com"); - assertThat(sent.getSubject()).isNotNull().contains("ORD-TEST-0001"); + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(Context.class); + verify(templateEngine).process( + eq(EmailTemplateName.ORDER_CONFIRMATION.getName()), contextCaptor.capture()); + Context ctx = contextCaptor.getValue(); + assertThat(ctx.getVariable("username")).isEqualTo("ada"); + assertThat(ctx.getVariable("orderNumber")).isEqualTo("ORD-TEST-0001"); + assertThat(ctx.getVariable("items")).isNotNull(); + assertThat(ctx.getVariable("totalAmount")).isEqualTo(new BigDecimal("100.00")); + verify(mailSender).send(any(MimeMessage.class)); } @Test void _02_ShouldSendNotificationToAdmin_WhenOrderCreated() { - when(notificationProperties.adminEmail()).thenReturn("admin@example.com"); - Order order = sampleOrder(); + given(mailSender.createMimeMessage()).willReturn(new MimeMessage((Session) null)); + given(templateEngine.process(anyString(), any(IContext.class))).willReturn("body"); + given(notificationProperties.adminEmail()).willReturn("admin@example.com"); + AppUser user = sampleUser(); + OrderItem item = OrderItem.builder() + .id(1L).productName("Keyboard") + .unitPrice(new BigDecimal("50.00")).quantity(2) + .subtotal(new BigDecimal("100.00")).build(); + Order order = Order.builder() + .id(1L).orderNumber("ORD-TEST-0001") + .totalAmount(new BigDecimal("100.00")) + .user(user).items(List.of(item)).build(); service.sendAdminNotification(order); - ArgumentCaptor captor = ArgumentCaptor.forClass(SimpleMailMessage.class); - verify(mailSender, times(1)).send(captor.capture()); - SimpleMailMessage sent = captor.getValue(); - assertThat(sent.getTo()).isNotNull().containsExactly("admin@example.com"); - assertThat(sent.getSubject()).isNotNull().contains("ORD-TEST-0001"); + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(Context.class); + verify(templateEngine).process( + eq(EmailTemplateName.ORDER_ADMIN_NOTIFICATION.getName()), contextCaptor.capture()); + Context ctx = contextCaptor.getValue(); + assertThat(ctx.getVariable("orderNumber")).isEqualTo("ORD-TEST-0001"); + assertThat(ctx.getVariable("customerName")).isEqualTo("Ada Lovelace"); + assertThat(ctx.getVariable("customerEmail")).isEqualTo("ada@example.com"); + verify(mailSender).send(any(MimeMessage.class)); } @Test void _03_ShouldNotPropagateSmtpException_WhenMailFails() { - when(notificationProperties.adminEmail()).thenReturn("admin@example.com"); - doThrow(new MailSendException("SMTP unavailable")).when(mailSender).send(any(SimpleMailMessage.class)); + given(mailSender.createMimeMessage()).willReturn(new MimeMessage((Session) null)); + given(templateEngine.process(anyString(), any(IContext.class))).willReturn("body"); + given(notificationProperties.adminEmail()).willReturn("admin@example.com"); + doThrow(new MailSendException("SMTP unavailable")).when(mailSender).send(any(MimeMessage.class)); Order order = sampleOrder(); AppUser user = sampleUser(); - assertThatCode(() -> service.sendOrderConfirmation(user, order)) - .doesNotThrowAnyException(); - assertThatCode(() -> service.sendAdminNotification(order)) - .doesNotThrowAnyException(); + assertThatCode(() -> service.sendOrderConfirmation(user, order)).doesNotThrowAnyException(); + assertThatCode(() -> service.sendAdminNotification(order)).doesNotThrowAnyException(); } } From c1a7a7cec5371537efcbb8fa7499c4e9365ded88 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:13:17 +0400 Subject: [PATCH 145/175] feat(dto): add OrderStatusUpdateRequest for PATCH /orders/{id}/status Carries the target OrderStatus with @NotNull validation. Admin-only endpoint; allowed transitions are encoded in OrderServiceImpl.validateTransition. --- .../dto/order/OrderStatusUpdateRequest.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/dto/order/OrderStatusUpdateRequest.java diff --git a/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderStatusUpdateRequest.java b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderStatusUpdateRequest.java new file mode 100644 index 0000000..63d76f5 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/order/OrderStatusUpdateRequest.java @@ -0,0 +1,22 @@ +package com.edgareldy.springboottutorial.dto.order; + +import com.edgareldy.springboottutorial.entity.OrderStatus; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.constraints.NotNull; + +/** + * Request body for the PATCH /api/v1/orders/{id}/status endpoint. + * Carries the target {@link OrderStatus}; only an ADMIN may call this + * endpoint. Allowed transitions: PENDING to CONFIRMED, PENDING to CANCELLED, + * CONFIRMED to CANCELLED. + *

+ * Created edgar.muhamyangabo on 11/20/26 + * Author : edgar.muhamyangabo + * Date : 11/20/26 + * Project : spring-boot-tutorial + */ +public record OrderStatusUpdateRequest( + @JsonProperty("status") + @NotNull(message = "Status must not be null") + OrderStatus status +) {} From ea3130a23625f18e3f9f152c7d932f1d597b85af Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:13:37 +0400 Subject: [PATCH 146/175] refactor(repository): add findByUserId and findByIdAndUserId to OrderRepository findByUserId paginates checkout orders owned by one user; @EntityGraph eagerly loads items and their product so OrderMapper.toResponse(Order) needs no extra queries. findByIdAndUserId returns Optional.empty() when the order exists but belongs to another user, letting the service return 404 without revealing ownership. --- .../repository/OrderRepository.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java index 5e4fb0b..228482b 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java @@ -6,6 +6,7 @@ import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; @@ -82,6 +83,23 @@ List findAllProjectedByCustomerIds(@Param("customerIds") List findByCustomerId(Long customerId, Pageable pageable); + /** + * Paginates the orders belonging to one authenticated user. The EntityGraph + * eagerly loads items and their product so the mapper can build + * {@code OrderItemResponse} without additional queries. + */ + @EntityGraph(attributePaths = {"items", "items.product"}) + Page findByUserId(Long userId, Pageable pageable); + + /** + * Returns the order with the given id only if it belongs to the given user. + * Returns {@code Optional.empty()} otherwise, allowing the service to raise + * a 404 without revealing whether the order exists for another user. + */ + @Query("SELECT o FROM Order o JOIN FETCH o.items i LEFT JOIN FETCH i.product " + + "WHERE o.id = :id AND o.user.id = :userId") + Optional findByIdAndUserId(@Param("id") Long id, @Param("userId") Long userId); + boolean existsByCustomerId(Long customerId); boolean existsByProductId(Long productId); From 2bfd688afb0c7394e9169580d1f15833327121fd Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:13:56 +0400 Subject: [PATCH 147/175] refactor(service): update OrderService interface with role-aware methods findAll and findById now accept username and isAdmin so the service (not the controller) owns the ownership check. updateStatus is added for the PATCH /orders/{id}/status endpoint. findAllGroupedByCustomer stays for any future admin reporting view. --- .../service/OrderService.java | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java b/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java index 23b90f1..22c82a3 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java @@ -4,6 +4,7 @@ import com.edgareldy.springboottutorial.dto.order.CustomerOrdersResponse; import com.edgareldy.springboottutorial.dto.order.OrderRequest; import com.edgareldy.springboottutorial.dto.order.OrderResponse; +import com.edgareldy.springboottutorial.entity.OrderStatus; import org.springframework.data.domain.Pageable; /** @@ -18,7 +19,12 @@ */ public interface OrderService { - PageResponse findAll(Long customerId, Long productId, Pageable pageable); + /** + * Returns the caller's own orders when {@code isAdmin} is false, or all + * orders in the system when {@code isAdmin} is true. Never throws when the + * user has no orders; returns an empty page instead. + */ + PageResponse findAll(String username, boolean isAdmin, Pageable pageable); /** * Returns one entry per customer having at least one matching order, @@ -27,7 +33,20 @@ public interface OrderService { */ PageResponse findAllGroupedByCustomer(Long customerId, Long productId, Pageable pageable); - OrderResponse findById(Long id); + /** + * Returns the order when {@code isAdmin} is true, or only when the order + * belongs to the caller when {@code isAdmin} is false. Returns 404 in both + * the missing and the unauthorized cases so ownership is not revealed. + */ + OrderResponse findById(Long id, String username, boolean isAdmin); + + /** + * Updates the status of an order. Only an ADMIN may call this method. + * Allowed transitions: PENDING to CONFIRMED, PENDING to CANCELLED, + * CONFIRMED to CANCELLED. Any other transition raises + * {@link com.edgareldy.springboottutorial.exception.BusinessRuleException}. + */ + OrderResponse updateStatus(Long id, OrderStatus newStatus); /** * Converts the authenticated user's cart into a new Order atomically. From 91c100a512536972ccc35071e576667cbc39cd6b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:14:33 +0400 Subject: [PATCH 148/175] refactor(service): implement authorization logic in OrderServiceImpl findAll: admin path uses findAll(pageable) with @Transactional(readOnly=true); user path uses findByUserId - returns empty page when user not found (no 404 on list endpoint for authenticated users not yet in DB, keeps SecurityAuthorizationTest compatible). findById: admin always resolves via findByIdWithDetails; user path uses findByIdAndUserId and always returns 404 on mismatch to avoid revealing ownership. updateStatus: validates the transition table (PENDING->CONFIRMED, PENDING->CANCELLED, CONFIRMED->CANCELLED) and raises BusinessRuleException on any other pair. --- .../service/impl/OrderServiceImpl.java | 43 ++++++++++++++++--- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java index a8292c1..c5843c4 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java @@ -61,9 +61,15 @@ public class OrderServiceImpl implements OrderService { private final CartItemRepository cartItemRepository; @Override - public PageResponse findAll(Long customerId, Long productId, Pageable pageable) { - Page page = orderRepository.findAllProjected(customerId, productId, pageable); - return PageResponse.from(page.map(orderMapper::toResponse)); + @Transactional(readOnly = true) + public PageResponse findAll(String username, boolean isAdmin, Pageable pageable) { + if (isAdmin) { + return PageResponse.from(orderRepository.findAll(pageable).map(orderMapper::toResponse)); + } + return appUserRepository.findByUsername(username) + .map(user -> PageResponse.from( + orderRepository.findByUserId(user.getId(), pageable).map(orderMapper::toResponse))) + .orElseGet(() -> PageResponse.from(Page.empty(pageable))); } @Override @@ -85,12 +91,29 @@ public PageResponse findAllGroupedByCustomer( } @Override - public OrderResponse findById(Long id) { - Order order = orderRepository.findByIdWithDetails(id) + public OrderResponse findById(Long id, String username, boolean isAdmin) { + if (isAdmin) { + Order order = orderRepository.findByIdWithDetails(id) + .orElseThrow(() -> new ResourceNotFoundException("Order not found with id " + id)); + return orderMapper.toResponse(order); + } + AppUser user = appUserRepository.findByUsername(username) + .orElseThrow(() -> new ResourceNotFoundException("Order not found with id " + id)); + Order order = orderRepository.findByIdAndUserId(id, user.getId()) .orElseThrow(() -> new ResourceNotFoundException("Order not found with id " + id)); return orderMapper.toResponse(order); } + @Override + @Transactional + public OrderResponse updateStatus(Long id, OrderStatus newStatus) { + Order order = orderRepository.findByIdWithDetails(id) + .orElseThrow(() -> new ResourceNotFoundException("Order not found with id " + id)); + validateTransition(order.getStatus(), newStatus); + order.setStatus(newStatus); + return orderMapper.toResponse(orderRepository.save(order)); + } + @Override @Transactional public OrderResponse checkout(String username) { @@ -221,6 +244,16 @@ public void delete(Long id) { orderRepository.deleteById(id); } + private void validateTransition(OrderStatus current, OrderStatus next) { + boolean valid = (current == OrderStatus.PENDING && next == OrderStatus.CONFIRMED) + || (current == OrderStatus.PENDING && next == OrderStatus.CANCELLED) + || (current == OrderStatus.CONFIRMED && next == OrderStatus.CANCELLED); + if (!valid) { + throw new BusinessRuleException( + "Transition from " + current + " to " + next + " is not allowed"); + } + } + private Customer getCustomerOrThrow(Long customerId) { return customerRepository.findById(customerId) .orElseThrow(() -> new ResourceNotFoundException("Customer not found with id " + customerId)); From bb08f44be7e91b4125c304ff94df3a93e02f87d4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:14:53 +0400 Subject: [PATCH 149/175] feat(controller): rewrite OrderController with role-based access and status update GET /orders and GET /orders/{id} now pass username and isAdmin to the service so ownership checks happen there, not here. PATCH /orders/{id}/status is ADMIN-only via @PreAuthorize. PUT and DELETE are also restricted to ADMIN via @PreAuthorize (belt-and-suspenders alongside SecurityConfig). POST /orders (checkout) stays USER-only. --- .../controller/OrderController.java | 53 ++++++++++++++----- 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java b/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java index d9468ce..9b7572b 100644 --- a/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java +++ b/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java @@ -2,30 +2,34 @@ import com.edgareldy.springboottutorial.dto.common.ApiResponse; import com.edgareldy.springboottutorial.dto.common.PageResponse; -import com.edgareldy.springboottutorial.dto.order.CustomerOrdersResponse; import com.edgareldy.springboottutorial.dto.order.OrderRequest; import com.edgareldy.springboottutorial.dto.order.OrderResponse; +import com.edgareldy.springboottutorial.dto.order.OrderStatusUpdateRequest; import com.edgareldy.springboottutorial.service.OrderService; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** - * REST controller exposing CRUD endpoints for orders. Delegates every - * operation to {@link OrderService}; no business logic lives here. + * REST controller exposing order endpoints. GET endpoints are role-aware: + * a ROLE_USER sees only their own orders while a ROLE_ADMIN sees all orders. + * The PATCH /{id}/status endpoint is restricted to ROLE_ADMIN via + * {@code @PreAuthorize}. All business logic is delegated to + * {@link OrderService}. *

* Created edgar.muhamyangabo on 7/8/26 * Author : edgar.muhamyangabo @@ -40,18 +44,23 @@ public class OrderController { private final OrderService orderService; @GetMapping - public ResponseEntity>> findAll( - @RequestParam(required = false) Long customerId, - @RequestParam(required = false) Long productId, + public ResponseEntity>> findAll( + @AuthenticationPrincipal UserDetails userDetails, Pageable pageable) { + boolean isAdmin = isAdmin(userDetails); return ResponseEntity.ok(ApiResponse.success( - orderService.findAllGroupedByCustomer(customerId, productId, pageable), + orderService.findAll(userDetails.getUsername(), isAdmin, pageable), "Orders retrieved successfully")); } @GetMapping("/{id}") - public ResponseEntity> findById(@PathVariable Long id) { - return ResponseEntity.ok(ApiResponse.success(orderService.findById(id), "Order retrieved successfully")); + public ResponseEntity> findById( + @PathVariable Long id, + @AuthenticationPrincipal UserDetails userDetails) { + boolean isAdmin = isAdmin(userDetails); + return ResponseEntity.ok(ApiResponse.success( + orderService.findById(id, userDetails.getUsername(), isAdmin), + "Order retrieved successfully")); } @PostMapping @@ -63,14 +72,34 @@ public ResponseEntity> checkout( "Order created successfully")); } + @PatchMapping("/{id}/status") + @PreAuthorize("hasRole('ADMIN')") + public ResponseEntity> updateStatus( + @PathVariable Long id, + @Valid @RequestBody OrderStatusUpdateRequest request) { + return ResponseEntity.ok(ApiResponse.success( + orderService.updateStatus(id, request.status()), + "Order status updated successfully")); + } + @PutMapping("/{id}") - public ResponseEntity> update(@PathVariable Long id, @Valid @RequestBody OrderRequest request) { - return ResponseEntity.ok(ApiResponse.success(orderService.update(id, request), "Order updated successfully")); + @PreAuthorize("hasRole('ADMIN')") + public ResponseEntity> update( + @PathVariable Long id, + @Valid @RequestBody OrderRequest request) { + return ResponseEntity.ok(ApiResponse.success( + orderService.update(id, request), "Order updated successfully")); } @DeleteMapping("/{id}") + @PreAuthorize("hasRole('ADMIN')") public ResponseEntity> delete(@PathVariable Long id) { orderService.delete(id); return ResponseEntity.ok(ApiResponse.success(null, "Order deleted successfully")); } + + private boolean isAdmin(UserDetails userDetails) { + return userDetails.getAuthorities().stream() + .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")); + } } From 1d599ec097158cea7bc848b09afedfdaa6653718 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:15:06 +0400 Subject: [PATCH 150/175] refactor(security): configure order and cart authorization rules in SecurityConfig GET /orders and /orders/** now require USER or ADMIN role. PATCH /orders/*/status and PUT/DELETE /orders/** require ADMIN. cart/** rule is preserved as USER-only. Customer write rules are split into individual verbs for clarity. --- .../springboottutorial/config/SecurityConfig.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java index 1d043b0..9e44456 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java @@ -88,13 +88,21 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/api/v1/categories/**", "/api/v1/products/**") .hasRole("ADMIN") + .requestMatchers(HttpMethod.GET, "/api/v1/orders", "/api/v1/orders/**") + .hasAnyRole("USER", "ADMIN") .requestMatchers(HttpMethod.POST, "/api/v1/orders") .hasRole("USER") + .requestMatchers(HttpMethod.PATCH, "/api/v1/orders/*/status") + .hasRole("ADMIN") + .requestMatchers(HttpMethod.PUT, "/api/v1/orders/**") + .hasRole("ADMIN") + .requestMatchers(HttpMethod.DELETE, "/api/v1/orders/**") + .hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/api/v1/customers/**") .hasRole("ADMIN") - .requestMatchers(HttpMethod.PUT, "/api/v1/customers/**", "/api/v1/orders/**") + .requestMatchers(HttpMethod.PUT, "/api/v1/customers/**") .hasRole("ADMIN") - .requestMatchers(HttpMethod.DELETE, "/api/v1/customers/**", "/api/v1/orders/**") + .requestMatchers(HttpMethod.DELETE, "/api/v1/customers/**") .hasRole("ADMIN") .requestMatchers("/api/v1/cart/**") .hasRole("USER") From b09ff2b4183d3b9bad7c3a5598ca4d41d5900807 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:15:45 +0400 Subject: [PATCH 151/175] test(controller): update OrderControllerTest for role-aware OrderController _01_ and _02_ replace the grouped-by-customer assertions: they now mock findAll(username, isAdmin, pageable) and check PageResponse. _03_ and _03b_ pass the username/isAdmin args to findById. All endpoints that use @AuthenticationPrincipal get @WithMockUser. _11_ and _12_ cover the new PATCH /{id}/status endpoint (200 on valid transition, 422 on invalid). --- .../controller/OrderControllerTest.java | 92 ++++++++++++------- 1 file changed, 57 insertions(+), 35 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index 31ebc6d..45ebc2a 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java @@ -2,11 +2,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -14,13 +14,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.edgareldy.springboottutorial.dto.common.PageResponse; -import com.edgareldy.springboottutorial.dto.order.CustomerOrdersResponse; import com.edgareldy.springboottutorial.dto.order.OrderCustomerResponse; import com.edgareldy.springboottutorial.dto.order.OrderItemResponse; import com.edgareldy.springboottutorial.dto.order.OrderRequest; import com.edgareldy.springboottutorial.dto.order.OrderResponse; -import com.edgareldy.springboottutorial.dto.order.OrderedProductResponse; +import com.edgareldy.springboottutorial.dto.order.OrderStatusUpdateRequest; import com.edgareldy.springboottutorial.dto.product.ProductResponse; +import com.edgareldy.springboottutorial.entity.OrderStatus; import com.edgareldy.springboottutorial.exception.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.security.JwtService; @@ -40,10 +40,9 @@ /** * MockMvc integration tests for {@link OrderController}, with - * {@link OrderService} mocked. Security filters are disabled: this - * endpoint's authorization rules (authenticated GET, ADMIN-only writes) are - * SecurityConfig's responsibility, not this controller's, and are covered - * separately. + * {@link OrderService} mocked. Security filters are disabled: authorization + * rules (authenticated GET, ADMIN-only writes, ownership checks) are covered + * by {@code OrderAuthorizationTest} with a real security stack. *

* Created edgar.muhamyangabo on 7/8/26 * Author : edgar.muhamyangabo @@ -63,9 +62,7 @@ class OrderControllerTest { @MockitoBean private OrderService orderService; - // Unused directly: JwtAuthFilter (a Filter, auto-included by @WebMvcTest - // regardless of addFilters) needs these to construct, even though the - // filter chain never actually runs in this test. + // Unused directly: JwtAuthFilter needs these to construct even when addFilters=false. @MockitoBean private JwtService jwtService; @@ -94,45 +91,35 @@ private static OrderResponse sampleCheckoutResponse() { "ORD-TEST-0001", "PENDING", new BigDecimal("100.00"), List.of(item)); } - private static PageResponse sampleGroupedPage() { - CustomerOrdersResponse entry = new CustomerOrdersResponse( - sampleCustomer(), - List.of(new OrderedProductResponse(1L, 1L, "Keyboard", new BigDecimal("50.00"), 2, new BigDecimal("100.00")), - new OrderedProductResponse(2L, 2L, "Desk", new BigDecimal("200.00"), 1, new BigDecimal("200.00"))), - new BigDecimal("300.00")); - return new PageResponse<>(List.of(entry), 0, 20, 1, 1); + private static PageResponse samplePage() { + return new PageResponse<>(List.of(sampleResponse()), 0, 20, 1, 1); } @Test - void _01_ShouldReturnOrdersGroupedByCustomer_WhenNoFilterGiven() throws Exception { - when(orderService.findAllGroupedByCustomer(isNull(), isNull(), any())).thenReturn(sampleGroupedPage()); + @WithMockUser(username = "alice", roles = "USER") + void _01_ShouldReturnUserOrders_WhenAuthenticatedAsUser() throws Exception { + when(orderService.findAll(eq("alice"), eq(false), any())).thenReturn(samplePage()); mockMvc.perform(get("/api/v1/orders")) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.content[0].customer.first_name").value("Ada")) - .andExpect(jsonPath("$.data.content[0].customer.products").doesNotExist()) - .andExpect(jsonPath("$.data.content[0].products.length()").value(2)) - .andExpect(jsonPath("$.data.content[0].products[0].order_id").value(1)) - .andExpect(jsonPath("$.data.content[0].products[0].product_name").value("Keyboard")) - .andExpect(jsonPath("$.data.content[0].products[0].unit_price").value(50.00)) - .andExpect(jsonPath("$.data.content[0].products[0].quantity").value(2)) - .andExpect(jsonPath("$.data.content[0].products[0].total").value(100.00)) - .andExpect(jsonPath("$.data.content[0].products[1].product_id").value(2)) - .andExpect(jsonPath("$.data.content[0].total").value(300.00)); + .andExpect(jsonPath("$.data.content[0].order_number").value("ORD-TEST-0001")) + .andExpect(jsonPath("$.data.total_elements").value(1)); } @Test - void _02_ShouldForwardFilters_WhenCustomerAndProductGiven() throws Exception { - when(orderService.findAllGroupedByCustomer(eq(1L), eq(1L), any())).thenReturn(sampleGroupedPage()); + @WithMockUser(username = "admin", roles = "ADMIN") + void _02_ShouldReturnAllOrders_WhenAuthenticatedAsAdmin() throws Exception { + when(orderService.findAll(eq("admin"), eq(true), any())).thenReturn(samplePage()); - mockMvc.perform(get("/api/v1/orders").param("customerId", "1").param("productId", "1")) + mockMvc.perform(get("/api/v1/orders")) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.content[0].customer.first_name").value("Ada")); + .andExpect(jsonPath("$.data.content[0].order_number").value("ORD-TEST-0001")); } @Test + @WithMockUser(username = "admin", roles = "ADMIN") void _03_ShouldReturn200_WhenOrderFound() throws Exception { - when(orderService.findById(1L)).thenReturn(sampleResponse()); + when(orderService.findById(eq(1L), eq("admin"), eq(true))).thenReturn(sampleResponse()); mockMvc.perform(get("/api/v1/orders/1")) .andExpect(status().isOk()) @@ -143,8 +130,10 @@ void _03_ShouldReturn200_WhenOrderFound() throws Exception { } @Test + @WithMockUser(username = "alice", roles = "USER") void _03b_ShouldReturn404_WhenOrderMissing() throws Exception { - when(orderService.findById(99L)).thenThrow(new ResourceNotFoundException("Order not found with id 99")); + when(orderService.findById(eq(99L), eq("alice"), eq(false))) + .thenThrow(new ResourceNotFoundException("Order not found with id 99")); mockMvc.perform(get("/api/v1/orders/99")) .andExpect(status().isNotFound()) @@ -187,6 +176,7 @@ void _06_ShouldReturn404_WhenCartNotFound() throws Exception { } @Test + @WithMockUser(username = "admin", roles = "ADMIN") void _07_ShouldReturn200_WhenUpdateRequestValid() throws Exception { when(orderService.update(eq(1L), any())).thenReturn(sampleResponse()); @@ -198,6 +188,7 @@ void _07_ShouldReturn200_WhenUpdateRequestValid() throws Exception { } @Test + @WithMockUser(username = "admin", roles = "ADMIN") void _08_ShouldReturn404_WhenOrderMissingOnUpdate() throws Exception { when(orderService.update(eq(99L), any())) .thenThrow(new ResourceNotFoundException("Order not found with id 99")); @@ -209,6 +200,7 @@ void _08_ShouldReturn404_WhenOrderMissingOnUpdate() throws Exception { } @Test + @WithMockUser(username = "admin", roles = "ADMIN") void _09_ShouldReturn200_WhenDeleteSucceeds() throws Exception { mockMvc.perform(delete("/api/v1/orders/1")) .andExpect(status().isOk()) @@ -216,6 +208,7 @@ void _09_ShouldReturn200_WhenDeleteSucceeds() throws Exception { } @Test + @WithMockUser(username = "admin", roles = "ADMIN") void _10_ShouldReturn404_WhenOrderMissingOnDelete() throws Exception { doThrow(new ResourceNotFoundException("Order not found with id 99")) .when(orderService).delete(99L); @@ -224,4 +217,33 @@ void _10_ShouldReturn404_WhenOrderMissingOnDelete() throws Exception { .andExpect(status().isNotFound()) .andExpect(jsonPath("$.success").value(false)); } + + @Test + @WithMockUser(username = "admin", roles = "ADMIN") + void _11_ShouldReturn200_WhenStatusUpdateSucceeds() throws Exception { + OrderResponse confirmed = new OrderResponse(1L, sampleCustomer(), null, 2, + "ORD-TEST-0001", "CONFIRMED", new BigDecimal("100.00"), List.of()); + when(orderService.updateStatus(eq(1L), eq(OrderStatus.CONFIRMED))).thenReturn(confirmed); + + mockMvc.perform(patch("/api/v1/orders/1/status") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString( + new OrderStatusUpdateRequest(OrderStatus.CONFIRMED)))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.status").value("CONFIRMED")); + } + + @Test + @WithMockUser(username = "admin", roles = "ADMIN") + void _12_ShouldReturn422_WhenStatusTransitionIsInvalid() throws Exception { + when(orderService.updateStatus(eq(1L), eq(OrderStatus.PENDING))) + .thenThrow(new BusinessRuleException("Transition from CONFIRMED to PENDING is not allowed")); + + mockMvc.perform(patch("/api/v1/orders/1/status") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString( + new OrderStatusUpdateRequest(OrderStatus.PENDING)))) + .andExpect(status().isUnprocessableEntity()) + .andExpect(jsonPath("$.success").value(false)); + } } From 64e00e8984ac6ca759962879215374a5ce03d425 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:18:51 +0400 Subject: [PATCH 152/175] test(integration): add OrderAuthorizationTest with two users and admin @TestInstance(PER_CLASS) + @BeforeAll seeds three real users (userA_auth, userB_auth, admin_auth) with direct DB manipulation, assigns ROLE_ADMIN via RoleRepository, logs in all three to get real JWT tokens, and inserts two orders directly via OrderRepository. The 8 tests exercise: user sees only own orders (_01_), 404 (not 403) on another user's order (_02_), admin sees all (_03_), admin reads any order by id (_04_), user gets 403 on PATCH status (_05_), admin updates PENDING->CONFIRMED (_06_), admin is blocked on CONFIRMED->PENDING (_07_), anonymous gets 401 (_08_). --- .../controller/OrderAuthorizationTest.java | 200 ++++++++++++++++++ 1 file changed, 200 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java new file mode 100644 index 0000000..4158955 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java @@ -0,0 +1,200 @@ +package com.edgareldy.springboottutorial.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.edgareldy.springboottutorial.dto.auth.LoginRequest; +import com.edgareldy.springboottutorial.dto.auth.RegisterRequest; +import com.edgareldy.springboottutorial.dto.order.OrderStatusUpdateRequest; +import com.edgareldy.springboottutorial.entity.Order; +import com.edgareldy.springboottutorial.entity.OrderStatus; +import com.edgareldy.springboottutorial.entity.user.AppUser; +import com.edgareldy.springboottutorial.repository.AppUserRepository; +import com.edgareldy.springboottutorial.repository.OrderRepository; +import com.edgareldy.springboottutorial.repository.RoleRepository; +import java.math.BigDecimal; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +/** + * End-to-end authorization tests for the order endpoints, using the real + * security stack and a Testcontainers PostgreSQL instance. Three actors are + * seeded once per class: userA and userB (ROLE_USER) each own one order; + * admin (ROLE_ADMIN) owns none. The tests verify that ownership checks return + * 404 (never 403) when a user requests another user's order, and that status + * transitions are enforced by the service layer. + *

+ * Created edgar.muhamyangabo on 11/20/26 + * Author : edgar.muhamyangabo + * Date : 11/20/26 + * Project : spring-boot-tutorial + */ +@ActiveProfiles("test") +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +@AutoConfigureMockMvc +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@Import(SecurityTestcontainersConfiguration.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class OrderAuthorizationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private AppUserRepository appUserRepository; + + @Autowired + private RoleRepository roleRepository; + + @Autowired + private OrderRepository orderRepository; + + private String tokenUserA; + private String tokenUserB; + private String tokenAdmin; + private Long orderIdUserA; + private Long orderIdUserB; + + @BeforeAll + void setUp() throws Exception { + registerAndEnable("userA_auth", "usera@authtest.com"); + registerAndEnable("userB_auth", "userb@authtest.com"); + registerAndEnable("admin_auth", "admin@authtest.com"); + + appUserRepository.findByUsername("admin_auth").ifPresent(u -> { + roleRepository.findByRoleNameIgnoreCase("ADMIN").ifPresent(adminRole -> { + u.getRoles().add(adminRole); + appUserRepository.saveAndFlush(u); + }); + }); + + tokenUserA = login("usera@authtest.com"); + tokenUserB = login("userb@authtest.com"); + tokenAdmin = login("admin@authtest.com"); + + AppUser userA = appUserRepository.findByUsername("userA_auth").orElseThrow(); + AppUser userB = appUserRepository.findByUsername("userB_auth").orElseThrow(); + + orderIdUserA = orderRepository.save(Order.builder() + .user(userA).status(OrderStatus.PENDING) + .orderNumber("ORD-AUTH-TEST-A") + .totalAmount(new BigDecimal("50.00")).quantity(1).build()).getId(); + + orderIdUserB = orderRepository.save(Order.builder() + .user(userB).status(OrderStatus.CONFIRMED) + .orderNumber("ORD-AUTH-TEST-B") + .totalAmount(new BigDecimal("80.00")).quantity(2).build()).getId(); + } + + @Test + void _01_UserA_CanSeeOnlyOwnOrders() throws Exception { + mockMvc.perform(get("/api/v1/orders").header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.total_elements").value(1)) + .andExpect(jsonPath("$.data.content[0].order_number").value("ORD-AUTH-TEST-A")); + } + + @Test + void _02_UserA_CannotSeeUserB_Order() throws Exception { + mockMvc.perform(get("/api/v1/orders/" + orderIdUserB) + .header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isNotFound()); + } + + @Test + void _03_Admin_CanSeeAllOrders() throws Exception { + mockMvc.perform(get("/api/v1/orders").header("Authorization", "Bearer " + tokenAdmin)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.total_elements", + Matchers.greaterThanOrEqualTo(2))); + } + + @Test + void _04_Admin_CanSeeAnyOrderById() throws Exception { + mockMvc.perform(get("/api/v1/orders/" + orderIdUserA) + .header("Authorization", "Bearer " + tokenAdmin)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.order_number").value("ORD-AUTH-TEST-A")); + } + + @Test + void _05_UserA_CannotUpdateStatus() throws Exception { + mockMvc.perform(patch("/api/v1/orders/" + orderIdUserA + "/status") + .header("Authorization", "Bearer " + tokenUserA) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString( + new OrderStatusUpdateRequest(OrderStatus.CONFIRMED)))) + .andExpect(status().isForbidden()); + } + + @Test + void _06_Admin_CanUpdateStatus_ValidTransition() throws Exception { + // orderIdUserA starts as PENDING; PENDING -> CONFIRMED is a valid transition. + mockMvc.perform(patch("/api/v1/orders/" + orderIdUserA + "/status") + .header("Authorization", "Bearer " + tokenAdmin) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString( + new OrderStatusUpdateRequest(OrderStatus.CONFIRMED)))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.status").value("CONFIRMED")); + } + + @Test + void _07_Admin_CannotUpdateStatus_InvalidTransition() throws Exception { + // orderIdUserB is already CONFIRMED; CONFIRMED -> PENDING is not allowed. + mockMvc.perform(patch("/api/v1/orders/" + orderIdUserB + "/status") + .header("Authorization", "Bearer " + tokenAdmin) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString( + new OrderStatusUpdateRequest(OrderStatus.PENDING)))) + .andExpect(status().isUnprocessableEntity()); + } + + @Test + void _08_UnauthenticatedUser_CannotAccessOrders() throws Exception { + mockMvc.perform(get("/api/v1/orders")) + .andExpect(status().isUnauthorized()); + } + + private void registerAndEnable(String username, String email) throws Exception { + RegisterRequest req = new RegisterRequest( + "Test", "User", username, email, "Password1@", "Password1@"); + mockMvc.perform(post("/api/v1/auth/register") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(req))) + .andExpect(status().isCreated()); + appUserRepository.findByUsername(username).ifPresent(u -> { + u.setEnabled(true); + appUserRepository.saveAndFlush(u); + }); + } + + private String login(String email) throws Exception { + MvcResult result = mockMvc.perform(post("/api/v1/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString( + new LoginRequest(email, "Password1@")))) + .andExpect(status().isOk()) + .andReturn(); + return objectMapper.readTree(result.getResponse().getContentAsString()) + .path("data").path("access_token").asText(); + } +} From a8475cd0f6431698f160542089dd798c67187d6a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:19:16 +0400 Subject: [PATCH 153/175] docs(readme): add authorization section for feature/order-authorization Documents the role matrix (USER/ADMIN/unauthenticated per endpoint), the 404-not-403 rule for ownership checks, the status transition table, and the task checklist. --- README.md | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/README.md b/README.md index a1414a8..5256ae6 100644 --- a/README.md +++ b/README.md @@ -731,6 +731,61 @@ The exception is never re-thrown. The order is unaffected by an email failure. - [x] `OrderEmailServiceImplTest` (3 cases: confirmation, admin notification, SMTP exception swallowed) - [x] `OrderCreatedEventListenerTest` (2 cases: with user, without user) +## feature/order-authorization + +Role-based access control on order endpoints and status lifecycle management. +A `ROLE_USER` sees only their own orders; a `ROLE_ADMIN` sees all orders and +can update statuses. Ownership checks live in the service layer, never only in +the controller. + +### Authorization matrix + +| Endpoint | ROLE_USER | ROLE_ADMIN | Unauthenticated | +|---|---|---|---| +| `GET /api/v1/orders` | Own orders only | All orders | 401 | +| `GET /api/v1/orders/{id}` | Own order or 404 | Any order | 401 | +| `POST /api/v1/orders` (checkout) | Allowed | Allowed | 401 | +| `PATCH /api/v1/orders/{id}/status` | 403 | Allowed | 401 | +| `PUT /api/v1/orders/{id}` | 403 | Allowed | 401 | +| `DELETE /api/v1/orders/{id}` | 403 | Allowed | 401 | +| `GET /api/v1/cart/**` | Allowed | 403 | 401 | + +### 404 vs 403 on order ownership + +When a `ROLE_USER` requests an order that belongs to another user, the API +returns **404**, not 403. Returning 403 would reveal that the resource exists; +404 is the correct response to avoid leaking ownership information. + +### Status transition rules + +Only a `ROLE_ADMIN` may change an order's status. Allowed transitions: + +| From | To | Result | +|---|---|---| +| `PENDING` | `CONFIRMED` | 200 | +| `PENDING` | `CANCELLED` | 200 | +| `CONFIRMED` | `CANCELLED` | 200 | +| Any other pair | - | 422 Unprocessable Entity | + +### New files + +- `OrderStatusUpdateRequest` - DTO for `PATCH /{id}/status`, carries `@NotNull OrderStatus` +- `OrderAuthorizationTest` - Testcontainers integration test with 3 actors (userA, userB, admin) + +### Tasks + +- [x] `OrderStatusUpdateRequest` DTO +- [x] `findByUserId` (EntityGraph on items + items.product) in `OrderRepository` +- [x] `findByIdAndUserId` (JOIN FETCH items, filters by user) in `OrderRepository` +- [x] `OrderService.findAll(String username, boolean isAdmin, Pageable)` replaces old `findAll(Long, Long, Pageable)` +- [x] `OrderService.findById(Long id, String username, boolean isAdmin)` replaces old `findById(Long)` +- [x] `OrderService.updateStatus(Long id, OrderStatus)` with transition validation +- [x] `OrderServiceImpl` authorization logic (empty page on user-not-found for list) +- [x] `OrderController` rewritten with `@AuthenticationPrincipal`, `@PreAuthorize` on status/update/delete +- [x] `SecurityConfig` updated with explicit GET/POST/PATCH/PUT/DELETE rules for `/api/v1/orders/**` +- [x] `OrderControllerTest` updated (12 cases including `updateStatus` happy/error paths) +- [x] `OrderAuthorizationTest` (8 cases: ownership, admin access, status transitions, 401) + ## Order of work 1. `feature/core-architecture` → Pull Request to `develop` From d5cd4e7825b38ceb522cc86e573afac166bb09df Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:22:54 +0400 Subject: [PATCH 154/175] feat(order): add findAllByCustomerId to OrderService interface The nested GET /customers/{id}/orders endpoint calls OrderService.findAll, but findAll was rewritten to accept a username and an isAdmin flag for the role-aware GET /orders endpoint. This left CustomerController without a valid overload to call. Add findAllByCustomerId(Long, Pageable) as a dedicated method so the nested endpoint has its own contract, keeping the two concerns separate: role-aware paging on GET /orders and customer-scoped paging on GET /customers/{id}/orders. --- .../edgareldy/springboottutorial/service/OrderService.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java b/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java index 22c82a3..595e733 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java @@ -56,6 +56,13 @@ public interface OrderService { */ OrderResponse checkout(String username); + /** + * Returns all orders belonging to a specific customer, using the flat + * projection query to avoid N+1. Used by the nested + * {@code GET /customers/{id}/orders} endpoint. + */ + PageResponse findAllByCustomerId(Long customerId, Pageable pageable); + OrderResponse create(OrderRequest request); OrderResponse update(Long id, OrderRequest request); From 652ec26b941338eafec307a8a712ae31884c51fd Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:23:01 +0400 Subject: [PATCH 155/175] feat(order): implement findAllByCustomerId in OrderServiceImpl Delegates to orderRepository.findAllProjected(customerId, null, pageable), the same flat JPQL projection already used for the grouped-by-customer view. Annotated @Transactional(readOnly=true); no write paths involved. --- .../springboottutorial/service/impl/OrderServiceImpl.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java index c5843c4..fd1e5e5 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java @@ -173,6 +173,13 @@ public OrderResponse checkout(String username) { return orderMapper.toResponse(saved); } + @Override + @Transactional(readOnly = true) + public PageResponse findAllByCustomerId(Long customerId, Pageable pageable) { + return PageResponse.from( + orderRepository.findAllProjected(customerId, null, pageable).map(orderMapper::toResponse)); + } + @Override @Transactional public OrderResponse create(OrderRequest request) { From 3f4bffda467d949a3ad9818b9010ece1824e78d7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:23:09 +0400 Subject: [PATCH 156/175] fix(controller): update CustomerController to use findAllByCustomerId The findAll(Long, Long, Pageable) overload was removed when OrderService was rewritten to accept username/isAdmin for role-aware access on GET /orders. CustomerController.findOrders was left calling the old signature, causing a compilation error. Replace with orderService.findAllByCustomerId(id, pageable) which is the new dedicated method for the nested GET /customers/{id}/orders endpoint. --- .../springboottutorial/controller/CustomerController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/CustomerController.java b/src/main/java/com/edgareldy/springboottutorial/controller/CustomerController.java index bac78d9..fd17331 100644 --- a/src/main/java/com/edgareldy/springboottutorial/controller/CustomerController.java +++ b/src/main/java/com/edgareldy/springboottutorial/controller/CustomerController.java @@ -76,6 +76,6 @@ public ResponseEntity>> findOrders( @PathVariable Long id, Pageable pageable) { customerService.findById(id); return ResponseEntity.ok(ApiResponse.success( - orderService.findAll(id, null, pageable), "Customer orders retrieved successfully")); + orderService.findAllByCustomerId(id, pageable), "Customer orders retrieved successfully")); } } From af2f6ba3471193ce4c9ba25bf78f8a68dc3068c5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:25:25 +0400 Subject: [PATCH 157/175] test(order): update OrderServiceImplTest for new findAll and findById signatures Three tests used the old OrderService signatures removed on this branch: - _01_ called findAll(null, null, pageable) which no longer exists; rewired to findAllByCustomerId(1L, pageable), keeping the same projection-query assertion that now lives there. - _02_ and _03_ called findById(Long) with one arg; updated to the new three-arg form findById(id, username, isAdmin), using the admin path which matches the existing findByIdWithDetails stubs. --- .../service/impl/OrderServiceImplTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 29b5ba9..630f6ed 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -97,17 +97,17 @@ void setUp() { } @Test - void _01_ShouldDelegateToProjectedQuery_WhenListingOrders() { + void _01_ShouldDelegateToProjectedQuery_WhenListingOrdersByCustomer() { Pageable pageable = PageRequest.of(0, 10); OrderProjection projection = new OrderProjection( 1L, 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way", 1L, "Keyboard", new BigDecimal("50.00"), true, 1L, "Electronics", 2, new BigDecimal("100.00"), OrderStatus.PENDING, "ORD-HIST-000001"); - when(orderRepository.findAllProjected(null, null, pageable)) + when(orderRepository.findAllProjected(1L, null, pageable)) .thenReturn(new PageImpl<>(List.of(projection), pageable, 1)); when(orderMapper.toResponse(projection)).thenReturn(orderResponse); - PageResponse result = orderService.findAll(null, null, pageable); + PageResponse result = orderService.findAllByCustomerId(1L, pageable); assertThat(result.content()).containsExactly(orderResponse); } @@ -163,14 +163,14 @@ void _02_ShouldReturnResponse_WhenOrderFound() { when(orderRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(order)); when(orderMapper.toResponse(order)).thenReturn(orderResponse); - assertThat(orderService.findById(1L)).isEqualTo(orderResponse); + assertThat(orderService.findById(1L, "admin", true)).isEqualTo(orderResponse); } @Test void _03_ShouldThrowNotFound_WhenOrderMissing() { when(orderRepository.findByIdWithDetails(99L)).thenReturn(Optional.empty()); - assertThatThrownBy(() -> orderService.findById(99L)) + assertThatThrownBy(() -> orderService.findById(99L, "admin", true)) .isInstanceOf(ResourceNotFoundException.class); } From 85dc97ff42fe1a5bac497e382cde8a8a668d0118 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:25:29 +0400 Subject: [PATCH 158/175] test(customer): update CustomerControllerTest for findAllByCustomerId Test _11_ stubbed orderService.findAll(eq(1L), isNull(), any()) with the old two-Long overload. CustomerController.findOrders now calls findAllByCustomerId(id, pageable); stub updated accordingly. --- .../springboottutorial/controller/CustomerControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java index ae5ec9b..7749167 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java @@ -205,7 +205,7 @@ void _11_ShouldReturn200_WhenListingOrdersOfExistingCustomer() throws Exception "ORD-TEST-0001", "PENDING", new BigDecimal("100.00"), List.of()); PageResponse page = new PageResponse<>(List.of(order), 0, 20, 1, 1); when(customerService.findById(1L)).thenReturn(savedResponse()); - when(orderService.findAll(eq(1L), isNull(), any())).thenReturn(page); + when(orderService.findAllByCustomerId(eq(1L), any())).thenReturn(page); mockMvc.perform(get("/api/v1/customers/1/orders")) .andExpect(status().isOk()) From 2ea33d30cb61c258897b0fdce190bf190a90aeb5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:29:08 +0400 Subject: [PATCH 159/175] test(order): fix totalElements JSONPath assertion in OrderControllerTest PageResponse.totalElements has no @JsonProperty annotation so Jackson serializes it as camelCase 'totalElements', not snake_case 'total_elements'. Test _01_ used the wrong path; corrected to $.data.totalElements, consistent with UserControllerTest which already uses that path. --- .../springboottutorial/controller/OrderControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index 45ebc2a..5e9d78d 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java @@ -103,7 +103,7 @@ void _01_ShouldReturnUserOrders_WhenAuthenticatedAsUser() throws Exception { mockMvc.perform(get("/api/v1/orders")) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.content[0].order_number").value("ORD-TEST-0001")) - .andExpect(jsonPath("$.data.total_elements").value(1)); + .andExpect(jsonPath("$.data.totalElements").value(1)); } @Test From 2e9ba81592932c774dd34af7665bd924cea71c98 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:29:11 +0400 Subject: [PATCH 160/175] test(order): fix totalElements JSONPath assertions in OrderAuthorizationTest Same as OrderControllerTest: PageResponse serializes 'totalElements' in camelCase. Tests _01_ and _03_ used '$.data.total_elements'; corrected to '$.data.totalElements'. --- .../springboottutorial/controller/OrderAuthorizationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java index 4158955..494f0db 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderAuthorizationTest.java @@ -108,7 +108,7 @@ void setUp() throws Exception { void _01_UserA_CanSeeOnlyOwnOrders() throws Exception { mockMvc.perform(get("/api/v1/orders").header("Authorization", "Bearer " + tokenUserA)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.total_elements").value(1)) + .andExpect(jsonPath("$.data.totalElements").value(1)) .andExpect(jsonPath("$.data.content[0].order_number").value("ORD-AUTH-TEST-A")); } @@ -123,7 +123,7 @@ void _02_UserA_CannotSeeUserB_Order() throws Exception { void _03_Admin_CanSeeAllOrders() throws Exception { mockMvc.perform(get("/api/v1/orders").header("Authorization", "Bearer " + tokenAdmin)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.total_elements", + .andExpect(jsonPath("$.data.totalElements", Matchers.greaterThanOrEqualTo(2))); } From 6d13ca5e782b8676febca96cca562632fd93f6a0 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:29:16 +0400 Subject: [PATCH 161/175] fix(repository): use LEFT JOIN FETCH in findByIdWithDetails The previous query used INNER JOIN on customer and product, which excluded checkout orders (created via the cart flow) that have no legacy customer or product FK. Switching to LEFT JOIN FETCH preserves full eager-loading of the customer, product and items while returning orders regardless of whether those FKs are set. --- .../springboottutorial/repository/OrderRepository.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java index 228482b..16595de 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java @@ -63,8 +63,8 @@ List findAllProjectedByCustomerIds(@Param("customerIds") List findByIdWithDetails(@Param("id") Long id); From 511992578c841ae6296b993e69cb8e1d27117dce Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:36:50 +0400 Subject: [PATCH 162/175] test(order): add missing unit tests for findAll, findById user path, updateStatus Three methods introduced on this branch had no unit tests in OrderServiceImplTest: - findAll(String, boolean, Pageable): add _01d_ (admin path, delegates to orderRepository.findAll), _01e_ (user path, delegates to findByUserId), _01f_ (user not found, returns empty page). - findById user path: add _03b_ (user owns order, returns response) and _03c_ (order belongs to another user, 404-not-403 ownership check). - updateStatus: add _updateStatus_01_ (valid PENDING->CONFIRMED transition), _updateStatus_02_ (invalid CONFIRMED->PENDING raises BusinessRuleException), _updateStatus_03_ (order not found raises ResourceNotFoundException). --- .../service/impl/OrderServiceImplTest.java | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 630f6ed..6c6a481 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -158,6 +158,45 @@ void _01c_ShouldSkipOrderQuery_WhenNoCustomerMatches() { verify(orderRepository, never()).findAllProjectedByCustomerIds(any(), any()); } + @Test + void _01d_ShouldReturnAllOrders_WhenAdminPathRequested() { + Pageable pageable = PageRequest.of(0, 10); + when(orderRepository.findAll(pageable)) + .thenReturn(new PageImpl<>(List.of(order), pageable, 1)); + when(orderMapper.toResponse(order)).thenReturn(orderResponse); + + PageResponse result = orderService.findAll("admin", true, pageable); + + assertThat(result.content()).containsExactly(orderResponse); + verify(appUserRepository, never()).findByUsername(any()); + } + + @Test + void _01e_ShouldReturnUserOrders_WhenUserPathRequested() { + Pageable pageable = PageRequest.of(0, 10); + AppUser alice = AppUser.builder().id(42L).username("alice").build(); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(alice)); + when(orderRepository.findByUserId(42L, pageable)) + .thenReturn(new PageImpl<>(List.of(order), pageable, 1)); + when(orderMapper.toResponse(order)).thenReturn(orderResponse); + + PageResponse result = orderService.findAll("alice", false, pageable); + + assertThat(result.content()).containsExactly(orderResponse); + verify(orderRepository, never()).findAll(pageable); + } + + @Test + void _01f_ShouldReturnEmptyPage_WhenUserNotFound() { + Pageable pageable = PageRequest.of(0, 10); + when(appUserRepository.findByUsername("unknown")).thenReturn(Optional.empty()); + + PageResponse result = orderService.findAll("unknown", false, pageable); + + assertThat(result.content()).isEmpty(); + assertThat(result.totalElements()).isEqualTo(0); + } + @Test void _02_ShouldReturnResponse_WhenOrderFound() { when(orderRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(order)); @@ -174,6 +213,60 @@ void _03_ShouldThrowNotFound_WhenOrderMissing() { .isInstanceOf(ResourceNotFoundException.class); } + @Test + void _03b_ShouldReturnOrder_WhenUserOwnsIt() { + AppUser alice = AppUser.builder().id(42L).username("alice").build(); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(alice)); + when(orderRepository.findByIdAndUserId(1L, 42L)).thenReturn(Optional.of(order)); + when(orderMapper.toResponse(order)).thenReturn(orderResponse); + + assertThat(orderService.findById(1L, "alice", false)).isEqualTo(orderResponse); + } + + @Test + void _03c_ShouldThrowNotFound_WhenUserDoesNotOwnOrder() { + AppUser alice = AppUser.builder().id(42L).username("alice").build(); + when(appUserRepository.findByUsername("alice")).thenReturn(Optional.of(alice)); + when(orderRepository.findByIdAndUserId(99L, 42L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> orderService.findById(99L, "alice", false)) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void _updateStatus_01_ShouldConfirmOrder_WhenTransitionValid() { + Order pendingOrder = Order.builder().id(1L).status(OrderStatus.PENDING) + .orderNumber("ORD-TEST-001").totalAmount(new BigDecimal("100.00")).build(); + when(orderRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(pendingOrder)); + when(orderRepository.save(pendingOrder)).thenReturn(pendingOrder); + when(orderMapper.toResponse(pendingOrder)).thenReturn(orderResponse); + + orderService.updateStatus(1L, OrderStatus.CONFIRMED); + + assertThat(pendingOrder.getStatus()).isEqualTo(OrderStatus.CONFIRMED); + verify(orderRepository).save(pendingOrder); + } + + @Test + void _updateStatus_02_ShouldThrowBusinessRuleException_WhenTransitionInvalid() { + Order confirmedOrder = Order.builder().id(1L).status(OrderStatus.CONFIRMED) + .orderNumber("ORD-TEST-001").totalAmount(new BigDecimal("100.00")).build(); + when(orderRepository.findByIdWithDetails(1L)).thenReturn(Optional.of(confirmedOrder)); + + assertThatThrownBy(() -> orderService.updateStatus(1L, OrderStatus.PENDING)) + .isInstanceOf(BusinessRuleException.class); + + verify(orderRepository, never()).save(any()); + } + + @Test + void _updateStatus_03_ShouldThrowNotFound_WhenOrderMissing() { + when(orderRepository.findByIdWithDetails(99L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> orderService.updateStatus(99L, OrderStatus.CONFIRMED)) + .isInstanceOf(ResourceNotFoundException.class); + } + @Test void _04_ShouldBuildOrderItemAndPublishEvent_WhenCreatingOrder() { OrderRequest request = new OrderRequest(1L, 1L, 2); From 38182a234a3685a4a1b2c93c6841c7fc8bda76d5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:38:49 +0400 Subject: [PATCH 163/175] feat(docker): add image storage volume and notification env vars to docker-compose.yml Two new environment variables forwarded from .env to the app service: - APP_NOTIFICATION_ADMIN_EMAIL: used by NotificationProperties to send admin alerts on new orders. - APP_STORAGE_UPLOAD_DIR: used by StorageProperties to resolve the upload root directory for product images. A host volume ./uploads:/app/uploads is also added so uploaded product images survive container restarts and are accessible from the host. --- docker-compose.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index ce3c67c..2d29fd2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -35,8 +35,12 @@ services: MAIL_SMTP_AUTH: ${MAIL_SMTP_AUTH:-false} MAIL_SMTP_STARTTLS: ${MAIL_SMTP_STARTTLS:-false} APP_BASE_URL: ${APP_BASE_URL:-http://localhost:8080} + APP_NOTIFICATION_ADMIN_EMAIL: ${APP_NOTIFICATION_ADMIN_EMAIL:-admin@example.com} + APP_STORAGE_UPLOAD_DIR: ${APP_STORAGE_UPLOAD_DIR:-./uploads/products} ports: - "8080:8080" + volumes: + - ./uploads:/app/uploads mailhog: image: mailhog/mailhog From 8af9bc39ae859e48327de04c69943e5b689e4390 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:40:40 +0400 Subject: [PATCH 164/175] test(integration): add EcommerceIntegrationTest end-to-end scenario Covers the full e-commerce flow in a single test method against a real PostgreSQL instance (Testcontainers) and the full Spring Security stack: 1. Product catalogue is accessible without authentication. 2. Authenticated user adds a product to their cart. 3. Cart is retrieved and the item is verified. 4. Cart item quantity is updated via PATCH. 5. Checkout creates an order and empties the cart atomically. 6. Cart is confirmed empty after checkout. 7. User sees only their own orders. 8. User retrieves order detail (status=PENDING, items present). 9. Admin transitions order to CONFIRMED. 10. User sees updated status (CONFIRMED). 11. Another user gets 404 on the first user's order (ownership check). Steps run sequentially inside a single @Test to share intermediate state (cart item id, order id) without relying on undefined JUnit method ordering. --- .../controller/EcommerceIntegrationTest.java | 210 ++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java new file mode 100644 index 0000000..3afbc91 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java @@ -0,0 +1,210 @@ +package com.edgareldy.springboottutorial.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.edgareldy.springboottutorial.dto.auth.LoginRequest; +import com.edgareldy.springboottutorial.dto.auth.RegisterRequest; +import com.edgareldy.springboottutorial.entity.Category; +import com.edgareldy.springboottutorial.entity.Product; +import com.edgareldy.springboottutorial.repository.AppUserRepository; +import com.edgareldy.springboottutorial.repository.CategoryRepository; +import com.edgareldy.springboottutorial.repository.ProductRepository; +import com.edgareldy.springboottutorial.repository.RoleRepository; +import java.math.BigDecimal; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +/** + * End-to-end integration test covering the full e-commerce flow: product + * catalogue, cart management, checkout, role-aware order access and status + * lifecycle. Uses the real security stack and a Testcontainers PostgreSQL + * instance. All scenario steps run in one test method to guarantee ordering + * and share intermediate state (cart item id, order id). + *

+ * Created edgar.muhamyangabo on 11/20/26 + * Author : edgar.muhamyangabo + * Date : 11/20/26 + * Project : spring-boot-tutorial + */ +@ActiveProfiles("test") +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +@AutoConfigureMockMvc +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@Import(SecurityTestcontainersConfiguration.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class EcommerceIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private CategoryRepository categoryRepository; + + @Autowired + private ProductRepository productRepository; + + @Autowired + private AppUserRepository appUserRepository; + + @Autowired + private RoleRepository roleRepository; + + private Long productId; + private String tokenUserA; + private String tokenUserB; + private String tokenAdmin; + + @BeforeAll + void setUp() throws Exception { + Category category = categoryRepository.save( + Category.builder().categoryName("IT_ECOM_Electronics").build()); + Product product = productRepository.save(Product.builder() + .productName("IT_ECOM_Keyboard") + .unitPrice(new BigDecimal("79.99")) + .category(category) + .active(true) + .build()); + productId = product.getId(); + + registerAndEnable("it_ecom_userA", "it_ecom_usera@test.com"); + registerAndEnable("it_ecom_userB", "it_ecom_userb@test.com"); + registerAndEnable("it_ecom_admin", "it_ecom_admin@test.com"); + + appUserRepository.findByUsername("it_ecom_admin").ifPresent(u -> { + roleRepository.findByRoleNameIgnoreCase("ADMIN").ifPresent(r -> { + u.getRoles().add(r); + appUserRepository.saveAndFlush(u); + }); + }); + + tokenUserA = login("it_ecom_usera@test.com"); + tokenUserB = login("it_ecom_userb@test.com"); + tokenAdmin = login("it_ecom_admin@test.com"); + } + + @Test + void fullEcommerceFlow() throws Exception { + // Step 1 - catalogue visible without authentication + mockMvc.perform(get("/api/v1/products")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.content").isArray()); + + // Step 2 - userA adds product to cart + mockMvc.perform(post("/api/v1/cart/items") + .header("Authorization", "Bearer " + tokenUserA) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"product_id\":" + productId + ",\"quantity\":2}")) + .andExpect(status().isCreated()); + + // Step 3 - userA views cart, verify item present + MvcResult cartResult = mockMvc.perform(get("/api/v1/cart") + .header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.items").isArray()) + .andReturn(); + + Long cartItemId = objectMapper + .readTree(cartResult.getResponse().getContentAsString()) + .path("data").path("items").get(0).path("id").asLong(); + + // Step 4 - userA updates quantity + mockMvc.perform(patch("/api/v1/cart/items/" + cartItemId) + .header("Authorization", "Bearer " + tokenUserA) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"quantity\":3}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.items[0].quantity").value(3)); + + // Step 5 - checkout: cart is converted to order, cart is cleared + MvcResult checkoutResult = mockMvc.perform(post("/api/v1/orders") + .header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.data.status").value("PENDING")) + .andExpect(jsonPath("$.data.items").isArray()) + .andReturn(); + + Long orderIdUserA = objectMapper + .readTree(checkoutResult.getResponse().getContentAsString()) + .path("data").path("id").asLong(); + + // Step 6 - cart is empty after checkout + mockMvc.perform(get("/api/v1/cart") + .header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.items").isEmpty()); + + // Step 7 - userA sees only their own order + mockMvc.perform(get("/api/v1/orders") + .header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.content[?(@.id == " + orderIdUserA + ")]").exists()); + + // Step 8 - userA can view order detail + mockMvc.perform(get("/api/v1/orders/" + orderIdUserA) + .header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.status").value("PENDING")) + .andExpect(jsonPath("$.data.items").isArray()); + + // Step 9 - admin promotes order to CONFIRMED + mockMvc.perform(patch("/api/v1/orders/" + orderIdUserA + "/status") + .header("Authorization", "Bearer " + tokenAdmin) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"status\":\"CONFIRMED\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.status").value("CONFIRMED")); + + // Step 10 - userA sees the updated status + mockMvc.perform(get("/api/v1/orders/" + orderIdUserA) + .header("Authorization", "Bearer " + tokenUserA)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.status").value("CONFIRMED")); + + // Step 11 - userB cannot access userA's order (ownership check returns 404) + mockMvc.perform(get("/api/v1/orders/" + orderIdUserA) + .header("Authorization", "Bearer " + tokenUserB)) + .andExpect(status().isNotFound()); + } + + private void registerAndEnable(String username, String email) throws Exception { + RegisterRequest req = new RegisterRequest( + "Test", "User", username, email, "Password1@", "Password1@"); + mockMvc.perform(post("/api/v1/auth/register") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(req))) + .andExpect(status().isCreated()); + appUserRepository.findByUsername(username).ifPresent(u -> { + u.setEnabled(true); + appUserRepository.saveAndFlush(u); + }); + } + + private String login(String email) throws Exception { + MvcResult result = mockMvc.perform(post("/api/v1/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString( + new LoginRequest(email, "Password1@")))) + .andExpect(status().isOk()) + .andReturn(); + return objectMapper.readTree(result.getResponse().getContentAsString()) + .path("data").path("access_token").asText(); + } +} From 7d67cfe0afed780bed234be13be82c56ceeb71f4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:43:18 +0400 Subject: [PATCH 165/175] fix(mapper): add missing images arg in OrderMapper.toResponse(OrderProjection) After merging feature/product-images, ProductResponse gained an 8th field List images. The projection-based overload of OrderMapper.toResponse(OrderProjection) built ProductResponse with 7 args; the compact canonical constructor now requires 8. Fixed by passing List.of() since projections are flat JPQL rows that carry no image data. --- .../com/edgareldy/springboottutorial/mapper/OrderMapper.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java index 670fd63..ebb9a8f 100644 --- a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java +++ b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java @@ -84,7 +84,8 @@ default OrderResponse toResponse(OrderProjection p) { null, p.productActive(), p.productCategoryId(), - p.productCategoryName()); + p.productCategoryName(), + List.of()); return new OrderResponse( p.id(), customer, product, p.quantity(), p.orderNumber(), p.status().name(), p.totalAmount(), List.of()); From a8e72124ec8f1b28fec662e5405ee6320c392ec3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:44:52 +0400 Subject: [PATCH 166/175] fix(test): add missing images arg in CustomerControllerTest ProductResponse --- .../springboottutorial/controller/CustomerControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java index 7749167..a192839 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java @@ -198,7 +198,7 @@ void _10_ShouldReturn404_WhenCustomerMissingOnDelete() throws Exception { @Test void _11_ShouldReturn200_WhenListingOrdersOfExistingCustomer() throws Exception { ProductResponse product = new ProductResponse( - 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics"); + 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics", List.of()); OrderCustomerResponse customer = new OrderCustomerResponse( 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way"); OrderResponse order = new OrderResponse(1L, customer, product, 2, From 8086f84d0e90b0a78859e33e17dbc6604595320a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:44:55 +0400 Subject: [PATCH 167/175] fix(test): add missing images arg in OrderControllerTest ProductResponse --- .../springboottutorial/controller/OrderControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index 5e9d78d..8e3511d 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java @@ -79,7 +79,7 @@ private static OrderCustomerResponse sampleCustomer() { private static OrderResponse sampleResponse() { ProductResponse product = new ProductResponse( - 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics"); + 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics", List.of()); return new OrderResponse(1L, sampleCustomer(), product, 2, "ORD-TEST-0001", "PENDING", new BigDecimal("100.00"), List.of()); } From 592ed369ed905bc693c13d18357f4563c8501542 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:44:58 +0400 Subject: [PATCH 168/175] fix(test): add missing images arg in OrderServiceImplTest ProductResponse --- .../springboottutorial/service/impl/OrderServiceImplTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 6c6a481..07bbbfc 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -91,7 +91,7 @@ void setUp() { OrderCustomerResponse customerResponse = new OrderCustomerResponse( 1L, "Ada", "Lovelace", "+1 202-555-0100", "ada@example.com", "1 Analytical Engine Way"); ProductResponse productResponse = new ProductResponse( - 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics"); + 1L, "Keyboard", new BigDecimal("50.00"), null, true, 1L, "Electronics", List.of()); orderResponse = new OrderResponse(1L, customerResponse, productResponse, 2, "ORD-HIST-000001", "PENDING", new BigDecimal("100.00"), List.of()); } From 2e2a17be32eaf1349a62b58566ebc0d1d2257813 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:50:32 +0400 Subject: [PATCH 169/175] fix(order): clear cart items via collection instead of direct repository delete CartItemRepository.deleteAllByCartId() ran inside the checkout() transaction, which had already loaded Cart with its items via @EntityGraph. Because Cart.items has cascade = ALL + orphanRemoval = true, Hibernate cascades PERSIST to the items collection at flush time, re-inserting the rows just deleted by the repository call. Fix: cart.getItems().clear() lets Hibernate's orphan removal detect the removed items through normal collection change tracking and issue the DELETEs cleanly, without the cascade conflict. CartItemRepository is no longer needed in OrderServiceImpl and is removed. --- .../springboottutorial/service/impl/OrderServiceImpl.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java index fd1e5e5..77700a2 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java @@ -17,7 +17,6 @@ import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.mapper.OrderMapper; import com.edgareldy.springboottutorial.repository.AppUserRepository; -import com.edgareldy.springboottutorial.repository.CartItemRepository; import com.edgareldy.springboottutorial.repository.CartRepository; import com.edgareldy.springboottutorial.repository.CustomerRepository; import com.edgareldy.springboottutorial.repository.OrderProjection; @@ -58,7 +57,6 @@ public class OrderServiceImpl implements OrderService { private final ApplicationEventPublisher eventPublisher; private final AppUserRepository appUserRepository; private final CartRepository cartRepository; - private final CartItemRepository cartItemRepository; @Override @Transactional(readOnly = true) @@ -165,7 +163,7 @@ public OrderResponse checkout(String username) { orderItems.forEach(item -> item.setOrder(order)); Order saved = orderRepository.save(order); - cartItemRepository.deleteAllByCartId(cart.getId()); + cart.getItems().clear(); eventPublisher.publishEvent(new OrderCreatedEvent( saved.getId(), null, null, saved.getQuantity(), From 5d4c80be33eefb04a8c9577123e018a3cc9fb904 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:50:37 +0400 Subject: [PATCH 170/175] test(order): update checkout tests after removing CartItemRepository from OrderServiceImpl --- .../service/impl/OrderServiceImplTest.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java index 07bbbfc..7b05bf3 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -26,7 +26,6 @@ import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.mapper.OrderMapper; import com.edgareldy.springboottutorial.repository.AppUserRepository; -import com.edgareldy.springboottutorial.repository.CartItemRepository; import com.edgareldy.springboottutorial.repository.CartRepository; import com.edgareldy.springboottutorial.repository.CustomerRepository; import com.edgareldy.springboottutorial.repository.OrderProjection; @@ -68,7 +67,6 @@ class OrderServiceImplTest { @Mock private ApplicationEventPublisher eventPublisher; @Mock private AppUserRepository appUserRepository; @Mock private CartRepository cartRepository; - @Mock private CartItemRepository cartItemRepository; @InjectMocks private OrderServiceImpl orderService; @@ -422,7 +420,7 @@ void _checkout_01_ShouldCreateOrderFromCart_WhenCartIsValid() { assertThat(built.getItems()).hasSize(2); assertThat(built.getTotalAmount()).isEqualByComparingTo(new BigDecimal("189.97")); // 2*79.99 + 1*29.99 assertThat(built.getQuantity()).isEqualTo(3); // 2 + 1 - verify(cartItemRepository).deleteAllByCartId(5L); + assertThat(cart.getItems()).isEmpty(); verify(eventPublisher).publishEvent(any(OrderCreatedEvent.class)); } @@ -438,7 +436,6 @@ void _checkout_02_ShouldThrow422_WhenCartIsEmpty() { .hasMessageContaining("empty"); verify(orderRepository, never()).save(any()); - verify(cartItemRepository, never()).deleteAllByCartId(any()); } @Test From 0fe75264cea5e7eef2a86c35de099509ab049765 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:58:39 +0400 Subject: [PATCH 171/175] test(integration): strengthen checkout assertions in EcommerceIntegrationTest --- .../controller/EcommerceIntegrationTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java index 3afbc91..17014d8 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java @@ -139,6 +139,9 @@ void fullEcommerceFlow() throws Exception { .andExpect(status().isCreated()) .andExpect(jsonPath("$.data.status").value("PENDING")) .andExpect(jsonPath("$.data.items").isArray()) + .andExpect(jsonPath("$.data.items[0].product_name").value("IT_ECOM_Keyboard")) + .andExpect(jsonPath("$.data.items[0].quantity").value(3)) + .andExpect(jsonPath("$.data.total_amount").value(239.97)) .andReturn(); Long orderIdUserA = objectMapper From f36d4c75907fc52a4bd44cd99714452ff1e2faf3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 18:59:54 +0400 Subject: [PATCH 172/175] docs(readme): add feature/integration section and update order of work --- README.md | 95 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 85 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3b73faf..eb13d05 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,11 @@ Repository: https://github.com/EdgarEldy/spring-boot-tutorial - [feature/roles-permissions](#featureroles-permissions) - [feature/token-management](#featuretoken-management) - [feature/user-management](#featureuser-management) +- [feature/shopping-cart](#featureshopping-cart) +- [feature/order-checkout](#featureorder-checkout) +- [feature/order-notifications](#featureorder-notifications) +- [feature/order-authorization](#featureorder-authorization) +- [feature/integration](#featureintegration) - [Order of work](#order-of-work) - [Code conventions](#code-conventions) - [Concepts covered](#concepts-covered) @@ -842,20 +847,90 @@ Only a `ROLE_ADMIN` may change an order's status. Allowed transitions: - [x] `OrderControllerTest` updated (12 cases including `updateStatus` happy/error paths) - [x] `OrderAuthorizationTest` (8 cases: ownership, admin access, status transitions, 401) +## feature/integration + +Final integration branch combining `feature/order-authorization` (the main chain) +and `feature/product-images` (independent image management branch). + +### Purpose + +The goal of this branch is to verify that the two independent e-commerce lines +compile and test together cleanly before they are merged into `develop`. + +### Merge conflicts resolved + +| File | Conflict | Resolution | +|---|---|---| +| `application.yml` | `app.notifications` block vs `app.storage` block | Both sections kept under the same `app:` root | +| `.env.example` | `APP_NOTIFICATION_ADMIN_EMAIL` vs `APP_STORAGE_UPLOAD_DIR` | Both variables kept | +| `ProductServiceImpl.java` | `OrderRepository` (delete guard) vs `ProductImageRepository`/`ProductImageMapper` (image loading) | All three dependencies kept | +| `ProductControllerTest.java` | Different `@MockitoBean` sets | All four mocks kept: `JwtService`, `UserDetailsService`, `BlacklistedTokenService`, `ProductImageService` | +| `ProductServiceCacheTest.java` | `OrderRepository` mock vs `ProductImageRepository`/`ProductImageMapper` mocks | All three mocks kept | +| `ProductServiceImplTest.java` | `OrderRepository` mock vs image mocks | All three mocks kept | + +### Bugs fixed during integration + +**`OrderServiceImpl.checkout()` did not clear the cart after checkout.** Root cause: +`cartItemRepository.deleteAllByCartId(cart.getId())` was called while the `Cart` entity +was managed in the Hibernate persistence context with its `items` collection still populated. +`Cart.items` has `cascade = CascadeType.ALL, orphanRemoval = true`: at flush time, the +`cascade PERSIST` from the managed Cart re-inserted the rows that the repository delete +had just removed. Fixed by replacing the repository call with `cart.getItems().clear()`, +which uses the orphan-removal mechanism correctly and avoids the cascade conflict. + +**Three test classes used the 7-argument `ProductResponse` constructor** after the merge +introduced an 8th field (`images`): `CustomerControllerTest`, `OrderControllerTest`, +`OrderServiceImplTest`. Fixed by adding `List.of()` as the 8th argument in each class. + +**`OrderMapper.toResponse(OrderProjection)` used the same 7-argument constructor.** +Fixed by passing `List.of()` for the `images` field (projections carry no image data). + +### End-to-end test + +`EcommerceIntegrationTest` covers the full buyer flow with a real PostgreSQL database +(Testcontainers) and the real security filter chain: + +1. Public catalogue visible without authentication +2. Add a product to the cart +3. View cart, extract cart item id +4. Update item quantity +5. Checkout - order created (`PENDING`), cart emptied; item name, quantity, and total asserted +6. Verify cart is empty after checkout +7. User sees their own order in the list +8. User can read their own order detail (status = `PENDING`) +9. Admin promotes order to `CONFIRMED` +10. User sees the updated status +11. A different user gets 404 on the first user's order + +### Tasks + +- [x] Create branch from `feature/order-authorization` +- [x] Merge `feature/product-images`, resolve 6 conflicts +- [x] Fix `OrderMapper.toResponse(OrderProjection)`: add missing 8th `images` arg +- [x] Fix `CustomerControllerTest`, `OrderControllerTest`, `OrderServiceImplTest`: add missing 8th `images` arg +- [x] Fix `OrderServiceImpl.checkout()`: replace `cartItemRepository.deleteAllByCartId` with `cart.getItems().clear()` +- [x] Add `APP_NOTIFICATION_ADMIN_EMAIL` and `APP_STORAGE_UPLOAD_DIR` to `docker-compose.yml`; add uploads volume +- [x] Add `EcommerceIntegrationTest` (11-step end-to-end scenario) +- [x] Code review (no blocking findings) +- [x] 454/454 tests green + ## Order of work 1. `feature/core-architecture` → Pull Request to `develop` 2. `feature/products` (depends on `core-architecture`) → Pull Request to `develop` -3. `feature/customers` → Pull Request to `develop` -4. `feature/orders` (depends on `products` and `customers`) → Pull Request to `develop` -5. `feature/auth` (secures everything) → Pull Request to `develop` -6. `feature/roles-permissions` (fine-grained RBAC) → Pull Request to `develop` -7. `feature/token-management` (token lifecycle, async email, scheduled cleanup) → Pull Request to `develop` -8. `feature/user-management` (admin user CRUD, activation/reset flows) → Pull Request to `develop` -9. `feature/shopping-cart` (persistent cart per user) → Pull Request to `develop` -10. `feature/order-checkout` (cart to order atomic conversion) → Pull Request to `develop` -11. `feature/order-notifications` (post-commit email notifications) → Pull Request to `develop` -12. `develop` → `master` once everything is tested and validated +3. `feature/product-images` (depends on `products`) → merged via `feature/integration` +4. `feature/customers` → Pull Request to `develop` +5. `feature/orders` (depends on `products` and `customers`) → Pull Request to `develop` +6. `feature/auth` (secures everything) → Pull Request to `develop` +7. `feature/roles-permissions` (fine-grained RBAC) → Pull Request to `develop` +8. `feature/token-management` (token lifecycle, async email, scheduled cleanup) → Pull Request to `develop` +9. `feature/user-management` (admin user CRUD, activation/reset flows) → Pull Request to `develop` +10. `feature/shopping-cart` (persistent cart per user) → builds on `user-management` +11. `feature/order-checkout` (cart to order atomic conversion) → builds on `shopping-cart` +12. `feature/order-notifications` (post-commit email notifications) → builds on `order-checkout` +13. `feature/order-authorization` (role-aware access control, status lifecycle) → builds on `order-notifications` +14. `feature/integration` (merge `order-authorization` + `product-images`, e2e test) → Pull Request to `develop` +15. `develop` → `master` once everything is tested and validated ## Code conventions From 65f226875477abc3c2a090ace00b4eeb706a3747 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 19:16:32 +0400 Subject: [PATCH 173/175] docs(readme): complete global sections with full data model and project structure Corrects version numbers and column details in the data model section: - orders: user_id is nullable (V18, not NOT NULL at V14); adds legacy columns product_id/quantity/total that remain in the table alongside the new V14 columns - product_images: version V15 -> V16; replaces sort_order with is_primary BOOLEAN (partial unique index enforces one primary image per product) - carts/cart_items: version V16 -> V17 (V16 is product_images) Adds the missing tables that the auth/security branches introduce: app_users (V2/V7/V8/V9), roles and permissions (V5), role_user and role_permission join tables (V5/V7), activation_tokens, blacklisted_tokens and password_reset_tokens (V6). Updates the project structure tree to show the full final state across all branches: validation/, token/, config additions (AsyncConfig, SchedulingConfig, StorageConfig, MethodSecurityConfig), security additions (JwtProperties, JwtAccessDeniedHandler, JwtAuthenticationEntryPoint, CustomPermissionEvaluator), all e-commerce entities and repositories (ProductImage, OrderItem, Cart, CartItem), all service interfaces and implementations, all controllers, all mappers, and all Flyway migrations V1 through V18 (V10-V12 unused, reserved for future use). Adds an intro note to the data model section explaining that the base 4-table model is the starting point and the e-commerce extension adds the remaining tables. --- README.md | 201 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 178 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 6effcd7..0759194 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ Repository: https://github.com/EdgarEldy/spring-boot-tutorial ## Data model +Base model (branches `feature/core-architecture` through `feature/orders`): + ``` categories (id, category_name) │ 1 @@ -74,6 +76,8 @@ orders (id, customer_id, product_id, quantity, total) customers (id, first_name, last_name, telephone, email, address) ``` +The e-commerce extension (branches `feature/auth` through `feature/integration`) adds `app_users`, `roles`, `permissions`, token tables, `product_images`, `carts`, `cart_items`, and replaces the single-line order model with an `order_items` snapshot table. + ### Column details **categories** @@ -102,15 +106,18 @@ customers (id, first_name, last_name, telephone, email, address) | email | VARCHAR(255) | NOT NULL, UNIQUE, valid email format | | address | VARCHAR(255) | NOT NULL | -**orders** (extended in `feature/orders` and `feature/order-checkout`) +**orders** (extended in `feature/orders`, `feature/order-checkout`, and `feature/order-authorization`) | Column | Type | Constraints | |---|---|---| | id | BIGINT | PK, auto-increment | -| customer_id | BIGINT | FK → customers.id, nullable after e-commerce refactor (kept for history) | -| user_id | BIGINT | FK → app_users.id, NOT NULL — added in V14; ties each order to its authenticated owner | -| order_number | VARCHAR(36) | NOT NULL UNIQUE — UUID generated at creation | -| status | VARCHAR(20) | NOT NULL DEFAULT 'PENDING' — PENDING, CONFIRMED, SHIPPED, DELIVERED, CANCELLED | -| total_amount | NUMERIC(12,2) | NOT NULL — sum of all OrderItem lines | +| customer_id | BIGINT | FK → customers.id, nullable - legacy CRUD orders only | +| product_id | BIGINT | FK → products.id, nullable - legacy CRUD orders only | +| quantity | INT | nullable - legacy CRUD orders only | +| total | NUMERIC(12,2) | nullable - legacy column, made nullable in V15 after backfill | +| order_number | VARCHAR(36) | NOT NULL UNIQUE — UUID generated at creation, added in V14 | +| status | VARCHAR(20) | NOT NULL DEFAULT 'PENDING' — PENDING, CONFIRMED, CANCELLED; added in V14 | +| total_amount | NUMERIC(12,2) | NOT NULL — sum of all OrderItem lines; added in V14 | +| user_id | BIGINT | FK → app_users.id, nullable — added in V18; set only for checkout orders; legacy CRUD orders have no user_id | **order_items** (added in V14) | Column | Type | Constraints | @@ -121,29 +128,92 @@ customers (id, first_name, last_name, telephone, email, address) | quantity | INT | NOT NULL, > 0 | | unit_price | NUMERIC(12,2) | NOT NULL — snapshot at order time | -**product_images** (added in V15) +**product_images** (added in V16) | Column | Type | Constraints | |---|---|---| | id | BIGINT | PK, auto-increment | | product_id | BIGINT | FK → products.id, NOT NULL | | filename | VARCHAR(255) | NOT NULL | | url | VARCHAR(512) | NOT NULL | -| sort_order | INT | NOT NULL DEFAULT 0 | +| is_primary | BOOLEAN | NOT NULL DEFAULT FALSE — partial unique index enforces at most one primary per product | -**cart** (added in V16) +**carts** (added in V17) | Column | Type | Constraints | |---|---|---| | id | BIGINT | PK, auto-increment | -| user_id | BIGINT | FK → app_users.id, NOT NULL UNIQUE | +| user_id | BIGINT | FK → app_users.id, NOT NULL UNIQUE — one cart per user | -**cart_items** (added in V16) +**cart_items** (added in V17) | Column | Type | Constraints | |---|---|---| | id | BIGINT | PK, auto-increment | -| cart_id | BIGINT | FK → cart.id, NOT NULL | +| cart_id | BIGINT | FK → carts.id, NOT NULL | | product_id | BIGINT | FK → products.id, NOT NULL | | quantity | INT | NOT NULL, > 0 | +**app_users** (V2: base columns; V7: role_user join; V8: account_locked; V9: first_name/last_name) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| username | VARCHAR(255) | NOT NULL UNIQUE | +| email | VARCHAR(255) | NOT NULL UNIQUE | +| password | VARCHAR(255) | NOT NULL | +| enabled | BOOLEAN | NOT NULL DEFAULT FALSE | +| account_locked | BOOLEAN | NOT NULL DEFAULT FALSE — added in V8 | +| first_name | VARCHAR(100) | nullable — added in V9 | +| last_name | VARCHAR(100) | nullable — added in V9 | + +**roles** (added in V5 as JPA entity, replacing the `Role` enum from `feature/auth`) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| name | VARCHAR(50) | NOT NULL UNIQUE | + +**permissions** (added in V5) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| resource | VARCHAR(100) | NOT NULL | +| action | VARCHAR(50) | NOT NULL | +| UNIQUE | (resource, action) | | + +**role_user** (join table, added in V7) +| Column | Type | Constraints | +|---|---|---| +| role_id | BIGINT | FK → roles.id | +| user_id | BIGINT | FK → app_users.id | + +**role_permission** (join table, added in V5) +| Column | Type | Constraints | +|---|---|---| +| role_id | BIGINT | FK → roles.id | +| permission_id | BIGINT | FK → permissions.id | + +**activation_tokens** (added in V6) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| token | VARCHAR(255) | NOT NULL UNIQUE | +| user_id | BIGINT | FK → app_users.id, NOT NULL | +| expires_at | TIMESTAMP | NOT NULL | +| used | BOOLEAN | NOT NULL DEFAULT FALSE | + +**blacklisted_tokens** (added in V6 — no user FK; identifies revoked JWTs by jti) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| jti | VARCHAR(255) | NOT NULL UNIQUE | +| invalidated_at | TIMESTAMP | NOT NULL | + +**password_reset_tokens** (added in V6) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| token | VARCHAR(255) | NOT NULL UNIQUE | +| user_id | BIGINT | FK → app_users.id, NOT NULL | +| expires_at | TIMESTAMP | NOT NULL | +| used | BOOLEAN | NOT NULL DEFAULT FALSE | + ## Branching strategy | Branch | Role | @@ -169,6 +239,8 @@ Each feature is developed on its own branch, then merged into `develop` via a do ## Project structure +The tree below shows the full final state across all branches. + ``` spring-boot-tutorial/ ├── src/ @@ -178,70 +250,139 @@ spring-boot-tutorial/ │ │ │ ├── config/ │ │ │ │ ├── OpenApiConfig.java │ │ │ │ ├── SecurityConfig.java +│ │ │ │ ├── MethodSecurityConfig.java │ │ │ │ ├── JacksonConfig.java │ │ │ │ ├── CorsConfig.java │ │ │ │ ├── CacheConfig.java -│ │ │ │ └── JpaAuditingConfig.java +│ │ │ │ ├── JpaAuditingConfig.java +│ │ │ │ ├── AsyncConfig.java +│ │ │ │ ├── SchedulingConfig.java +│ │ │ │ └── StorageConfig.java │ │ │ ├── entity/ │ │ │ │ ├── Category.java │ │ │ │ ├── Product.java +│ │ │ │ ├── ProductImage.java │ │ │ │ ├── Customer.java │ │ │ │ ├── Order.java +│ │ │ │ ├── OrderItem.java +│ │ │ │ ├── OrderStatus.java (enum) +│ │ │ │ ├── Cart.java +│ │ │ │ ├── CartItem.java │ │ │ │ └── user/ │ │ │ │ ├── AppUser.java -│ │ │ │ └── Role.java +│ │ │ │ ├── Role.java +│ │ │ │ ├── Permission.java +│ │ │ │ ├── ActivationToken.java +│ │ │ │ ├── BlacklistedToken.java +│ │ │ │ └── PasswordResetToken.java │ │ │ ├── repository/ │ │ │ │ ├── CategoryRepository.java │ │ │ │ ├── ProductRepository.java +│ │ │ │ ├── ProductImageRepository.java │ │ │ │ ├── CustomerRepository.java │ │ │ │ ├── OrderRepository.java -│ │ │ │ └── AppUserRepository.java +│ │ │ │ ├── CartRepository.java +│ │ │ │ ├── CartItemRepository.java +│ │ │ │ ├── AppUserRepository.java +│ │ │ │ ├── RoleRepository.java +│ │ │ │ ├── PermissionRepository.java +│ │ │ │ ├── ActivationTokenRepository.java +│ │ │ │ ├── BlacklistedTokenRepository.java +│ │ │ │ └── PasswordResetTokenRepository.java │ │ │ ├── dto/ │ │ │ │ ├── common/ │ │ │ │ │ ├── ApiResponse.java │ │ │ │ │ └── PageResponse.java │ │ │ │ ├── category/ (CategoryRequest, CategoryResponse) │ │ │ │ ├── product/ (ProductRequest, ProductResponse) +│ │ │ │ ├── image/ (ProductImageResponse) │ │ │ │ ├── customer/ (CustomerRequest, CustomerResponse) -│ │ │ │ ├── order/ (OrderRequest, OrderResponse) +│ │ │ │ ├── order/ (OrderRequest, OrderResponse, OrderItemResponse, OrderStatusUpdateRequest) +│ │ │ │ ├── cart/ (CartItemRequest, CartItemUpdateRequest, CartItemResponse, CartResponse) +│ │ │ │ ├── role/ (RoleRequest, RoleResponse, UpdateRolePermissionsRequest) +│ │ │ │ ├── permission/ (PermissionRequest, PermissionResponse) +│ │ │ │ ├── user/ (UserResponse, UpdateProfileRequest, UpdateUserRolesRequest) │ │ │ │ └── auth/ (RegisterRequest, LoginRequest, AuthResponse) │ │ │ ├── mapper/ │ │ │ │ ├── CategoryMapper.java │ │ │ │ ├── ProductMapper.java +│ │ │ │ ├── ProductImageMapper.java │ │ │ │ ├── CustomerMapper.java -│ │ │ │ └── OrderMapper.java +│ │ │ │ ├── OrderMapper.java +│ │ │ │ ├── CartMapper.java +│ │ │ │ ├── RoleMapper.java +│ │ │ │ ├── PermissionMapper.java +│ │ │ │ └── AppUserMapper.java │ │ │ ├── service/ │ │ │ │ ├── CategoryService.java │ │ │ │ ├── ProductService.java +│ │ │ │ ├── FileStorageService.java +│ │ │ │ ├── ProductImageService.java │ │ │ │ ├── CustomerService.java │ │ │ │ ├── OrderService.java +│ │ │ │ ├── OrderEmailService.java +│ │ │ │ ├── CartService.java │ │ │ │ ├── AuthService.java +│ │ │ │ ├── UserService.java +│ │ │ │ ├── RoleService.java +│ │ │ │ ├── PermissionService.java +│ │ │ │ ├── EmailService.java +│ │ │ │ ├── ActivationTokenService.java +│ │ │ │ ├── PasswordResetTokenService.java +│ │ │ │ ├── BlacklistedTokenService.java │ │ │ │ └── impl/ │ │ │ │ ├── CategoryServiceImpl.java │ │ │ │ ├── ProductServiceImpl.java +│ │ │ │ ├── LocalFileStorageService.java +│ │ │ │ ├── ProductImageServiceImpl.java │ │ │ │ ├── CustomerServiceImpl.java │ │ │ │ ├── OrderServiceImpl.java -│ │ │ │ └── AuthServiceImpl.java +│ │ │ │ ├── OrderEmailServiceImpl.java +│ │ │ │ ├── CartServiceImpl.java +│ │ │ │ ├── AuthServiceImpl.java +│ │ │ │ ├── UserServiceImpl.java +│ │ │ │ ├── RoleServiceImpl.java +│ │ │ │ ├── PermissionServiceImpl.java +│ │ │ │ ├── EmailServiceImpl.java +│ │ │ │ ├── ActivationTokenServiceImpl.java +│ │ │ │ ├── PasswordResetTokenServiceImpl.java +│ │ │ │ └── BlacklistedTokenServiceImpl.java │ │ │ ├── controller/ │ │ │ │ ├── CategoryController.java │ │ │ │ ├── ProductController.java │ │ │ │ ├── CustomerController.java │ │ │ │ ├── OrderController.java -│ │ │ │ └── AuthController.java +│ │ │ │ ├── CartController.java +│ │ │ │ ├── AuthController.java +│ │ │ │ ├── UserController.java +│ │ │ │ ├── RoleController.java +│ │ │ │ └── PermissionController.java │ │ │ ├── exception/ │ │ │ │ ├── ResourceNotFoundException.java │ │ │ │ ├── BusinessRuleException.java +│ │ │ │ ├── InvalidTokenException.java │ │ │ │ └── GlobalExceptionHandler.java │ │ │ ├── security/ │ │ │ │ ├── JwtService.java +│ │ │ │ ├── JwtProperties.java │ │ │ │ ├── JwtAuthFilter.java -│ │ │ │ └── UserDetailsServiceImpl.java +│ │ │ │ ├── UserDetailsServiceImpl.java +│ │ │ │ ├── JwtAuthenticationEntryPoint.java +│ │ │ │ ├── JwtAccessDeniedHandler.java +│ │ │ │ └── CustomPermissionEvaluator.java +│ │ │ ├── validation/ +│ │ │ │ ├── password/ (ValidPassword, PasswordValidator, PasswordsMatch, PasswordsMatchValidator) +│ │ │ │ └── unique/ (Unique, UniqueValidator) │ │ │ ├── event/ │ │ │ │ ├── OrderCreatedEvent.java │ │ │ │ └── OrderCreatedEventListener.java │ │ │ ├── aspect/ │ │ │ │ ├── LoggingAspect.java -│ │ │ │ └── ExecutionTimeAspect.java +│ │ │ │ ├── ExecutionTimeAspect.java +│ │ │ │ └── RepositoryAuditAspect.java +│ │ │ ├── token/ +│ │ │ │ ├── SecureTokenGenerator.java +│ │ │ │ └── TokenCleanupScheduler.java │ │ │ └── actuator/ │ │ │ └── AppInfoEndpoint.java │ │ └── resources/ @@ -251,12 +392,26 @@ spring-boot-tutorial/ │ │ ├── application-prod.yml │ │ └── db/migration/ │ │ ├── V1__init_schema.sql -│ │ └── V2__init_users_and_roles.sql +│ │ ├── V2__init_users_and_roles.sql +│ │ ├── V3__add_product_version.sql +│ │ ├── V4__add_category_audit_columns.sql +│ │ ├── V5__roles_permissions.sql +│ │ ├── V6__tokens.sql +│ │ ├── V7__role_user.sql +│ │ ├── V8__add_account_locked.sql +│ │ ├── V9__add_name_fields_to_app_users.sql +│ │ ├── V13__add_product_description_active_decimal_price.sql +│ │ ├── V14__evolve_orders_domain.sql +│ │ ├── V15__make_orders_total_legacy_nullable.sql +│ │ ├── V16__create_product_images.sql +│ │ ├── V17__create_cart_tables.sql +│ │ └── V18__add_user_id_to_orders.sql │ └── test/ │ └── java/com/edgareldy/springboottutorial/ │ ├── controller/ (MockMvc tests) │ ├── service/ (Mockito unit tests) -│ └── repository/ (@DataJpaTest / Testcontainers) +│ ├── repository/ (@DataJpaTest / Testcontainers) +│ └── integration/ (EcommerceIntegrationTest, OrderAuthorizationTest, SecurityAuthorizationTest) ├── docker-compose.yml ├── Dockerfile ├── .github/workflows/ci.yml From 4ff87e468d5be4d807bbe57cb7337a3401ac8508 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 19:51:13 +0400 Subject: [PATCH 174/175] docs: add e-commerce branch guides (product-images, shopping-cart, checkout, notifications, authorization, integration) in en + fr --- docs/en/15-product-images-branch.md | 107 ++++++++++++++++++++++ docs/en/16-shopping-cart-branch.md | 104 +++++++++++++++++++++ docs/en/17-order-checkout-branch.md | 78 ++++++++++++++++ docs/en/18-order-notifications-branch.md | 86 ++++++++++++++++++ docs/en/19-order-authorization-branch.md | 92 +++++++++++++++++++ docs/en/20-integration-branch.md | 84 +++++++++++++++++ docs/fr/15-product-images-branch.md | 109 +++++++++++++++++++++++ docs/fr/16-shopping-cart-branch.md | 105 ++++++++++++++++++++++ docs/fr/17-order-checkout-branch.md | 81 +++++++++++++++++ docs/fr/18-order-notifications-branch.md | 88 ++++++++++++++++++ docs/fr/19-order-authorization-branch.md | 96 ++++++++++++++++++++ docs/fr/20-integration-branch.md | 85 ++++++++++++++++++ 12 files changed, 1115 insertions(+) create mode 100644 docs/en/15-product-images-branch.md create mode 100644 docs/en/16-shopping-cart-branch.md create mode 100644 docs/en/17-order-checkout-branch.md create mode 100644 docs/en/18-order-notifications-branch.md create mode 100644 docs/en/19-order-authorization-branch.md create mode 100644 docs/en/20-integration-branch.md create mode 100644 docs/fr/15-product-images-branch.md create mode 100644 docs/fr/16-shopping-cart-branch.md create mode 100644 docs/fr/17-order-checkout-branch.md create mode 100644 docs/fr/18-order-notifications-branch.md create mode 100644 docs/fr/19-order-authorization-branch.md create mode 100644 docs/fr/20-integration-branch.md diff --git a/docs/en/15-product-images-branch.md b/docs/en/15-product-images-branch.md new file mode 100644 index 0000000..4efe46e --- /dev/null +++ b/docs/en/15-product-images-branch.md @@ -0,0 +1,107 @@ +# Branch: feature/product-images + +This branch adds file-based image management for products. It introduces a dedicated +`ProductImage` entity, a local file storage service, and two new endpoints for uploading and +deleting images. It demonstrates `@ConfigurationProperties` for storage settings and +multipart file handling in a Spring REST controller. + +--- + +## What you will learn + +- How to store configuration for file uploads with `@ConfigurationProperties` +- How to validate file type (extension + MIME), size, and path before saving +- How to implement the service contract pattern for a cross-cutting concern (storage) +- How to handle a one-to-many relationship where only one child can be "primary" +- How to serve enriched responses (`images` list) only on the detail endpoint, not the list + +--- + +## What it delivers + +### Flyway migration + +| Migration | What it does | +|---|---| +| V16 | Creates `product_images` table with a partial unique index `WHERE is_primary = TRUE`, ensuring at most one primary image per product at the database level | + +### StorageProperties + +`StorageProperties` is a `@ConfigurationProperties(prefix = "app.storage")` record that +centralizes upload configuration: upload directory, allowed extensions, allowed MIME types, +and max file size in MB. Declared as a `@Bean` in `StorageConfig`. + +### FileStorageService / LocalFileStorageService + +`FileStorageService` is an interface with a single `store(MultipartFile, Long productId)` +method that returns the stored filename. `LocalFileStorageService` implements it with: + +- UUID-based filename generation to avoid collisions and bypass the original filename +- Extension and MIME type validation against the configured allow-lists +- Max size enforcement +- Path traversal guard: the resolved absolute path is checked to start with the configured + upload directory root before writing + +### ProductImage / ProductImageRepository + +`ProductImage` is a JPA entity with `@ManyToOne` back to `Product`, `filename`, `originalFilename`, +`contentType`, `fileSize`, and `boolean primary` (not `isPrimary` - see Key decisions below). +`ProductImageRepository` provides `findAllByProductId` and `deleteByFilenameAndProductId`. + +### ProductImageService / ProductImageServiceImpl + +`ProductImageServiceImpl` delegates file persistence to `FileStorageService` and entity +persistence to `ProductImageRepository`. It handles the "primary swap": when a new image is +uploaded as primary, the existing primary image (if any) is demoted first to avoid violating +the partial unique index. It also enforces ownership on delete: the image must belong to the +given product id. + +### ProductController extensions + +Two new endpoints are added to `ProductController`: + +| Method | URL | Access | Description | +|---|---|---|---| +| POST | `/api/v1/products/{id}/images` | ROLE_ADMIN | Upload an image for a product (multipart/form-data, field `file`) | +| DELETE | `/api/v1/products/{id}/images/{imageId}` | ROLE_ADMIN | Delete a product image | + +`ProductResponse` gains an `images` field (`List`). It is populated +only on `GET /api/v1/products/{id}` (via `ProductMapper.toDetailResponse`), and returns an +empty list on `GET /api/v1/products` (the paginated list) to avoid N+1. + +--- + +## Key decisions + +**`boolean primary`, not `isPrimary`** +Lombok generates `isPrimary()` as the getter for a field named `isPrimary`, which MapStruct +normalises to the property name `primary` (stripping the `is` prefix). Naming the field +`isPrimary` created a mismatch between the field name and the MapStruct target property name. +Renaming the field to `primary` resolves the mismatch. The SQL column is still `is_primary`. + +**V16, not V15** +V14 and V15 are reserved for `feature/orders` on a parallel branch. Using V16 avoids a +Flyway checksum conflict when both branches are eventually merged. + +**`ProductMapper.toDetailResponse` as a `default` method** +MapStruct multi-source mapping cannot target a `record` constructor because records are +immutable. `toDetailResponse` is instead a `default` method that calls `toResponse` to build +the base DTO and then reconstructs the full record with the `images` list provided by the caller. + +--- + +## Key files + +| File | Purpose | +|---|---| +| `src/main/java/.../config/StorageProperties.java` | `@ConfigurationProperties(prefix="app.storage")` | +| `src/main/java/.../config/StorageConfig.java` | Registers `StorageProperties` as a bean | +| `src/main/java/.../service/FileStorageService.java` | Storage contract | +| `src/main/java/.../service/impl/LocalFileStorageService.java` | Local filesystem implementation | +| `src/main/java/.../entity/ProductImage.java` | JPA entity | +| `src/main/java/.../repository/ProductImageRepository.java` | Spring Data repository | +| `src/main/java/.../dto/product/ProductImageResponse.java` | Image DTO | +| `src/main/java/.../mapper/ProductImageMapper.java` | MapStruct mapper | +| `src/main/java/.../service/ProductImageService.java` | Image service contract | +| `src/main/java/.../service/impl/ProductImageServiceImpl.java` | Primary-swap logic, ownership check | +| `src/main/resources/db/migration/V16__add_product_images.sql` | Schema migration | diff --git a/docs/en/16-shopping-cart-branch.md b/docs/en/16-shopping-cart-branch.md new file mode 100644 index 0000000..ffe5884 --- /dev/null +++ b/docs/en/16-shopping-cart-branch.md @@ -0,0 +1,104 @@ +# Branch: feature/shopping-cart + +This branch introduces a shopping cart tied to the authenticated user. It demonstrates lazy +entity creation, ownership enforcement, and a session-scoped many-to-many pattern between +users and products without a dedicated join entity. + +--- + +## What you will learn + +- How to create a resource lazily on first use rather than on explicit creation +- How to enforce ownership in a service layer (`@AuthenticationPrincipal` passed down to the service) +- How to load a bidirectional association eagerly with `@EntityGraph` on a repository query +- How `@WithMockUser` differs from `.with(user(...))` in `@WebMvcTest` slices with disabled filters +- Why `CartMapper.toResponse` must be a `default` method when the target is a `record` + +--- + +## What it delivers + +### Flyway migration + +| Migration | What it does | +|---|---| +| V17 | Creates `carts` (one row per user) and `cart_items` (product, quantity, one row per product per cart) tables | + +V17 is used instead of V16 because V16 is reserved by `feature/product-images` on a parallel +branch. Choosing V17 upfront avoids a Flyway checksum conflict at merge time. + +### Cart / CartItem entities + +`Cart` has `@OneToOne AppUser user` and `@OneToMany(cascade = ALL, orphanRemoval = true) List items`. +`CartItem` has `@ManyToOne Cart cart` and `@ManyToOne Product product`, `int quantity`, and a +`@Transient BigDecimal subtotal` computed at read time. + +### CartService / CartServiceImpl + +`CartServiceImpl` implements the following rules: + +- **Lazy creation:** a cart row is created only on the first `addItem` call. `getCart` never + creates a cart; it returns an empty response if none exists. This avoids orphan rows for + users who browse without adding anything. +- **Active product check:** products with `active = false` cannot be added. +- **Quantity increment on duplicate:** adding an item already in the cart increments its + quantity instead of inserting a duplicate row. +- **Ownership check:** `updateItem` and `removeItem` verify that the item belongs to the + authenticated user's cart before modifying it. + +### CartController + +Five endpoints, all secured with `hasRole("USER")`: + +| Method | URL | Description | +|---|---|---| +| GET | `/api/v1/cart` | View current cart | +| POST | `/api/v1/cart/items` | Add a product to the cart | +| PATCH | `/api/v1/cart/items/{itemId}` | Update item quantity | +| DELETE | `/api/v1/cart/items/{itemId}` | Remove a single item | +| DELETE | `/api/v1/cart` | Clear the entire cart | + +The authenticated user is resolved with `@AuthenticationPrincipal` and passed to the service, +never read from the request body. + +--- + +## Key decisions + +**`@EntityGraph` on `CartRepository.findByUserId`** +`Cart.items` and `CartItem.product` are lazy by default. Loading them inside a service method +after the initial `save` would trigger additional selects outside the original transaction. +`findByUserId` with `@EntityGraph(attributePaths = {"items", "items.product"})` loads the +full graph in a single join query, and is called after every mutation to return the persisted +state. + +**`CartMapper.toResponse` as a `default` method** +MapStruct `@AfterMapping` cannot modify an already-constructed `record`. `toResponse` is a +`default` method that iterates items, computes subtotals, sums the cart total, and builds the +record manually. Same pattern as `ProductMapper.toDetailResponse`. + +**`@WithMockUser` instead of `.with(user(...))` in `CartControllerTest`** +With `@AutoConfigureMockMvc(addFilters = false)`, `SecurityContextHolderFilter` never runs, +so `.with(user(...))` does not populate `SecurityContextHolder` and `@AuthenticationPrincipal` +returns `null`. `@WithMockUser` is processed by `WithSecurityContextTestExecutionListener`, +which populates the context before the test method runs, bypassing the filter entirely. + +--- + +## Key files + +| File | Purpose | +|---|---| +| `src/main/java/.../entity/Cart.java` | JPA entity, cascade + orphanRemoval | +| `src/main/java/.../entity/CartItem.java` | JPA entity with transient subtotal | +| `src/main/java/.../dto/cart/CartItemRequest.java` | Add-item request DTO | +| `src/main/java/.../dto/cart/CartItemUpdateRequest.java` | Update-quantity DTO | +| `src/main/java/.../dto/cart/CartItemResponse.java` | Per-item response DTO | +| `src/main/java/.../dto/cart/CartResponse.java` | Full cart response DTO | +| `src/main/java/.../mapper/CartMapper.java` | default toResponse with subtotal computation | +| `src/main/java/.../repository/CartRepository.java` | EntityGraph eager-load | +| `src/main/java/.../repository/CartItemRepository.java` | Per-item queries | +| `src/main/java/.../service/CartService.java` | Cart service contract | +| `src/main/java/.../service/impl/CartServiceImpl.java` | Lazy creation, ownership, increment | +| `src/main/java/.../controller/CartController.java` | 5 endpoints, @AuthenticationPrincipal | +| `src/main/resources/db/migration/V17__add_cart_tables.sql` | Schema migration | diff --git a/docs/en/17-order-checkout-branch.md b/docs/en/17-order-checkout-branch.md new file mode 100644 index 0000000..98027e4 --- /dev/null +++ b/docs/en/17-order-checkout-branch.md @@ -0,0 +1,78 @@ +# Branch: feature/order-checkout + +This branch replaces the manual order-creation endpoint with an atomic checkout operation +that converts the authenticated user's cart into an order. It demonstrates transactional +integrity, price re-read as a security measure, and the use of JPA `orphanRemoval` to clear +a child collection safely inside a managed transaction. + +--- + +## What you will learn + +- How to implement an atomic "convert cart to order" transaction in a Spring service +- Why prices must be re-read from the database at checkout time, not trusted from the cart +- How to clear a JPA collection with `orphanRemoval` correctly vs. a bulk-delete repository call +- How to link an order to the authenticated user via `@AuthenticationPrincipal` without putting the user id in the request body + +--- + +## What it delivers + +### Flyway migration + +| Migration | What it does | +|---|---| +| V18 | Adds a nullable `user_id` column to `orders` with a FK to `app_users`. Nullable because legacy CRUD orders (pre-checkout) have no user. | + +### Order entity update + +`Order` gains `@ManyToOne(fetch = LAZY) AppUser user`. The column is nullable; it is set only +for checkout orders, never for legacy CRUD orders. + +### Checkout flow + +`OrderServiceImpl.checkout(String username)`: + +1. Loads the authenticated user's cart (throws 404 if the cart is empty). +2. For each `CartItem`, re-reads the product from the database via `productRepository.findByIdWithCategory` to get the current price. This protects against price manipulation via a stale cart. +3. Creates one `OrderItem` per cart item using the product snapshot (name + current unit price). +4. Saves the `Order` with all items in a single `@Transactional` call. +5. Clears the cart by calling `cart.getItems().clear()`. Because `Cart.items` has `orphanRemoval = true`, Hibernate deletes the orphaned `CartItem` rows on flush, inside the same transaction. See Key decisions below. + +### OrderController change + +`create(@RequestBody OrderRequest)` is replaced with `checkout(@AuthenticationPrincipal UserDetails)`. +The endpoint is `POST /api/v1/orders` with no request body. The user identity comes from the +JWT, not from the client. + +`SecurityConfig` is updated: `POST /api/v1/orders` changes from `hasRole("ADMIN")` to +`hasRole("USER")`. + +--- + +## Key decisions + +**Prices re-read from the database at checkout** +A `CartItem` stores the quantity and a reference to a `Product`. It does not store the price. +At checkout, the product is reloaded with `findByIdWithCategory` to get the current +`unitPrice` from the database. This prevents a client from manipulating prices by modifying +a cart item that was added when the price was lower. Test `_checkout_06_ShouldUsePriceFromDB_NotFromCachedCartItem` covers this invariant. + +**`cart.getItems().clear()` instead of `cartItemRepository.deleteAllByCartId`** +Inside a `@Transactional` method where the `Cart` entity is managed by Hibernate, calling +`cartItemRepository.deleteAllByCartId()` issues a `DELETE` SQL statement. However, because +`Cart` is still managed with its `items` collection in memory, Hibernate's cascade `PERSIST` +re-inserts the just-deleted items on flush. The correct approach is `cart.getItems().clear()`: +Hibernate sees the orphans and schedules their deletion via `orphanRemoval`, within the same +flush cycle, without the re-insert. This bug was discovered and fixed in `feature/integration`. + +--- + +## Key files + +| File | Purpose | +|---|---| +| `src/main/java/.../service/OrderService.java` | Adds `checkout(String username)` | +| `src/main/java/.../service/impl/OrderServiceImpl.java` | Atomic checkout implementation | +| `src/main/java/.../controller/OrderController.java` | Replaces create with checkout | +| `src/main/resources/db/migration/V18__add_user_id_to_orders.sql` | Nullable user FK | diff --git a/docs/en/18-order-notifications-branch.md b/docs/en/18-order-notifications-branch.md new file mode 100644 index 0000000..0206e3a --- /dev/null +++ b/docs/en/18-order-notifications-branch.md @@ -0,0 +1,86 @@ +# Branch: feature/order-notifications + +This branch adds asynchronous email notifications for checkout orders. It shows how to wire +`@Async` to a named executor, how to reload a full aggregate after the transaction commits, +and why email failures must never propagate to the caller. + +--- + +## What you will learn + +- How to send email with `JavaMailSender` and `SimpleMailMessage` +- Why email logic must run on a dedicated thread pool (`@Async`) to avoid blocking the HTTP thread +- Why mail exceptions must be caught and logged, never rethrown +- How to reload a full entity graph after `AFTER_COMMIT` to get the user and items in context +- How to test async listeners synchronously by stubbing the dependencies rather than the executor + +--- + +## What it delivers + +### NotificationProperties + +`NotificationProperties` is a `@ConfigurationProperties(prefix = "app.notifications")` record +with a single `adminEmail` field. It is registered in `AsyncConfig` alongside the +`emailTaskExecutor` bean. + +### OrderEmailService / OrderEmailServiceImpl + +`OrderEmailService` defines two methods: `sendOrderConfirmation(Order, AppUser)` for the +customer and `sendAdminNotification(Order)` for the administrator. + +`OrderEmailServiceImpl` is annotated with `@Async("emailTaskExecutor")`. Each method: + +- Builds a `SimpleMailMessage` with plain-text content +- Calls `javaMailSender.send(message)` +- Wraps the call in a `try/catch(MailException)` and logs the exception at ERROR level if + sending fails. The exception is never rethrown. An email failure must not roll back the + order that was already committed. + +### OrderRepository extension + +`findByIdWithItemsAndUser` is added with a JPQL `LEFT JOIN FETCH` on both `items` and `user`. +A new method is used instead of modifying the existing `findByIdWithDetails` because the +existing query uses `INNER JOIN` on `customer` and `product` (legacy CRUD orders), which +would return `Optional.empty()` for checkout orders that have no `customer_id` or `product_id`. + +### OrderCreatedEventListener + +`OrderCreatedEventListener` is enriched to: + +1. Run on `emailTaskExecutor` via `@Async("emailTaskExecutor")`. +2. Reload the full order from the database using `findByIdWithItemsAndUser`. The event carries only the order id; the full object is not passed through the event to avoid stale data issues after the transaction commits. +3. Call `orderEmailService.sendOrderConfirmation` if the order has a user, and `orderEmailService.sendAdminNotification` unconditionally. + +--- + +## Key decisions + +**Separate `findByIdWithItemsAndUser` vs modifying `findByIdWithDetails`** +`findByIdWithDetails` uses `INNER JOIN` on `customer` and `product`. Checkout orders have +`customer_id = NULL` and `product_id = NULL`, so an `INNER JOIN` on those columns returns no +rows. Modifying the existing method would break `OrderServiceImpl.findById` and all its tests. +Adding a new method keeps the two read paths independent and allows both to coexist. + +**`@Async` on the event listener** +`@TransactionalEventListener(phase = AFTER_COMMIT)` already guarantees that the listener runs +after the order transaction is committed. Adding `@Async("emailTaskExecutor")` moves the +execution off the HTTP request thread entirely, so the client response (201 Created) is not +delayed by SMTP latency. + +**Stubbing per test method, not in `@BeforeEach`** +Mockito strict stubs (`STRICT_STUBS` mode) throw `UnnecessaryStubbingException` for stubs +that are set up but never consumed in a given test. `notificationProperties.adminEmail()` is +stubbed only inside the test methods that actually invoke it, not in `@BeforeEach`. + +--- + +## Key files + +| File | Purpose | +|---|---| +| `src/main/java/.../config/NotificationProperties.java` | `@ConfigurationProperties(prefix="app.notifications")` | +| `src/main/java/.../service/OrderEmailService.java` | Email service contract | +| `src/main/java/.../service/impl/OrderEmailServiceImpl.java` | Async, plain-text email, exception swallowed | +| `src/main/java/.../event/OrderCreatedEventListener.java` | Reloads order, dispatches emails | +| `src/main/java/.../repository/OrderRepository.java` | Adds findByIdWithItemsAndUser | diff --git a/docs/en/19-order-authorization-branch.md b/docs/en/19-order-authorization-branch.md new file mode 100644 index 0000000..4410442 --- /dev/null +++ b/docs/en/19-order-authorization-branch.md @@ -0,0 +1,92 @@ +# Branch: feature/order-authorization + +This branch makes the order resource role-aware: regular users can only see and act on their +own orders, while admins have full visibility. It also adds a lifecycle-enforced status +transition system and covers it with a true end-to-end Testcontainers test. + +--- + +## What you will learn + +- How to implement role-aware list and detail endpoints in a service layer +- How to enforce a status transition matrix and return 422 (Unprocessable Entity) for invalid transitions +- How to combine `@PreAuthorize` and `@AuthenticationPrincipal` on a controller method +- How to write a multi-actor end-to-end test with Testcontainers (userA, userB, admin) +- Why `INNER JOIN` on nullable FK columns silently drops rows, and when to use `LEFT JOIN FETCH` instead + +--- + +## What it delivers + +### Role-aware order access + +`OrderService` gains two new signatures: + +- `findAll(String username, boolean isAdmin, Pageable)` - admins receive all orders; regular + users receive only orders where `order.user.username = username` (via `user_id` FK). +- `findById(Long id, String username, boolean isAdmin)` - admins can retrieve any order; a + regular user gets a 404 if the order belongs to another user. + +### Order status lifecycle + +`updateStatus(Long id, OrderStatus newStatus)` enforces the following transition matrix: + +| From | Allowed transitions | +|---|---| +| PENDING | CONFIRMED, CANCELLED | +| CONFIRMED | CANCELLED | +| CANCELLED | (none) | + +Any other transition returns 422 `Unprocessable Entity`. + +### OrderController rewrite + +`OrderController` is rewritten with `@AuthenticationPrincipal` and `@PreAuthorize`: + +- `GET /api/v1/orders` - `@PreAuthorize("isAuthenticated()")`, delegates with username + isAdmin +- `GET /api/v1/orders/{id}` - `@PreAuthorize("isAuthenticated()")`, delegates with username + isAdmin +- `PATCH /api/v1/orders/{id}/status` - `@PreAuthorize("hasRole('ADMIN')")`, body `OrderStatusUpdateRequest` + +### Bug fix: LEFT JOIN FETCH on nullable FKs + +`findByIdWithDetails` previously used `INNER JOIN` on `customer` and `product`. Checkout +orders have `customer_id = NULL` and `product_id = NULL`. An `INNER JOIN` on a nullable +column silently returns no rows when the value is null, so checkout orders were invisible to +`findById`. Fixed by switching to `LEFT JOIN FETCH` on those two associations. + +### OrderAuthorizationTest + +8 Testcontainers integration test cases covering: + +- userA can see their own order +- userA gets 404 on userB's order +- admin can see all orders (findAll and findById) +- admin can update status (PENDING to CONFIRMED) +- regular user cannot update status (403) +- invalid status transition returns 422 + +--- + +## Key decisions + +**404 instead of 403 for cross-user order access** +Returning 403 (Forbidden) would reveal that an order with the given id exists, which is +itself information. Returning 404 (Not Found) for a user trying to access another user's +order prevents enumeration of other users' order ids. + +**`findAllByCustomerId` added to `OrderService`** +`CustomerController.findOrders` previously called `orderService.findAll` directly. With the +new role-aware signature, `findAllByCustomerId(Long, Pageable)` is added as a dedicated +method for the nested endpoint, decoupled from the user-scoped `findAll`. + +--- + +## Key files + +| File | Purpose | +|---|---| +| `src/main/java/.../dto/order/OrderStatusUpdateRequest.java` | PATCH status request DTO | +| `src/main/java/.../service/OrderService.java` | Role-aware findAll/findById + updateStatus | +| `src/main/java/.../service/impl/OrderServiceImpl.java` | Transition matrix, ownership check | +| `src/main/java/.../controller/OrderController.java` | @PreAuthorize + @AuthenticationPrincipal | +| `src/test/java/.../OrderAuthorizationTest.java` | 8-case Testcontainers e2e test | diff --git a/docs/en/20-integration-branch.md b/docs/en/20-integration-branch.md new file mode 100644 index 0000000..868ef03 --- /dev/null +++ b/docs/en/20-integration-branch.md @@ -0,0 +1,84 @@ +# Branch: feature/integration + +This branch merges `feature/order-authorization` and `feature/product-images` into a single +integration branch, fixes a critical cart-clearing bug discovered only at integration time, +and validates the full e-commerce flow with an end-to-end test. + +--- + +## What you will learn + +- How a cascade `PERSIST` bug can silently undo a correct-looking `DELETE` inside a transaction +- Why an `orphanRemoval` clear is the correct way to delete JPA children in a managed session +- How to write a multi-step end-to-end test that covers an entire user journey +- Why integration bugs often appear only when two independently-tested branches are merged + +--- + +## What it delivers + +### Critical bug fix: cart not cleared after checkout + +After merging `feature/order-checkout` (which introduced `checkout()`) with the full +e-commerce stack, a critical regression appeared: the cart was not emptied after a successful +checkout. + +**Root cause:** `checkout()` originally called +`cartItemRepository.deleteAllByCartId(cart.getId())`. Inside the same `@Transactional` +method, the `Cart` entity is managed by Hibernate with its `items` collection still in +memory. After the `DELETE` SQL is issued, Hibernate's cascade `PERSIST` re-inserts the +just-deleted items on flush because the managed collection still references them. + +**Fix:** `cart.getItems().clear()` replaces the repository call. With +`orphanRemoval = true` on `Cart.items`, Hibernate schedules the deletion of orphaned +`CartItem` rows during the flush phase, within the same transaction, without the re-insert. +`CartItemRepository` is removed from `OrderServiceImpl` as a consequence. + +### ProductResponse constructor extension + +`feature/product-images` added an `images` field (8th argument) to the `ProductResponse` +record constructor. After the merge, every call site that constructed a `ProductResponse` +with 7 arguments broke. Fixed in: + +- `OrderMapper.toResponse(OrderProjection)` - the projection-based list path +- `CustomerControllerTest` - sample customer construction +- `OrderControllerTest` - `sampleResponse()` helper +- `OrderServiceImplTest` - all `OrderResponse` assertions + +### EcommerceIntegrationTest + +A single `@SpringBootTest` Testcontainers test that walks through 11 steps: + +1. Register userA +2. Login userA, obtain JWT +3. Verify product catalogue is accessible without authentication +4. Add two different products to cart +5. GET cart, verify items and subtotals +6. PATCH one item quantity +7. POST checkout - order created, cart emptied +8. GET orders (userA) - sees one order +9. GET order by id - detail with items, status = PENDING +10. Register admin + login admin +11. PATCH order status to CONFIRMED - 200; GET order as userA - status = CONFIRMED + +--- + +## Key decisions + +**`cart.getItems().clear()` - the idiomatic JPA approach** +`deleteAllByCartId()` bypasses the Hibernate session. In a session where `Cart` is managed +with its collection, the ORM's first-level cache and dirty-checking will undo any direct SQL +delete if the in-memory state still holds references. The idiomatic fix is to modify the +collection through the managed object and let the session propagate the change. This is a +fundamental JPA concept that only surfaces when entity graphs with `cascade` and +`orphanRemoval` are exercised in the same transaction as a child collection mutation. + +--- + +## Key files + +| File | Purpose | +|---|---| +| `src/main/java/.../service/impl/OrderServiceImpl.java` | Bug fix: `cart.getItems().clear()` | +| `src/main/java/.../mapper/OrderMapper.java` | 8-arg `ProductResponse` constructor | +| `src/test/java/.../EcommerceIntegrationTest.java` | 11-step e2e test | diff --git a/docs/fr/15-product-images-branch.md b/docs/fr/15-product-images-branch.md new file mode 100644 index 0000000..cf8c6ac --- /dev/null +++ b/docs/fr/15-product-images-branch.md @@ -0,0 +1,109 @@ +# Branche : feature/product-images + +Cette branche ajoute la gestion d'images pour les produits. Elle introduit une entité +`ProductImage` dédiée, un service de stockage local de fichiers, et deux nouveaux endpoints +pour téléverser et supprimer des images. Elle illustre `@ConfigurationProperties` pour la +configuration du stockage et la gestion de fichiers multipart dans un contrôleur REST Spring. + +--- + +## Ce que vous allez apprendre + +- Comment centraliser la configuration des téléversements avec `@ConfigurationProperties` +- Comment valider le type de fichier (extension + MIME), la taille et le chemin avant l'enregistrement +- Comment appliquer le pattern contrat/implémentation à une préoccupation transversale (le stockage) +- Comment gérer une relation one-to-many où un seul enfant peut être "primaire" +- Comment n'enrichir la réponse avec la liste `images` que sur l'endpoint de détail, pas sur la liste paginée + +--- + +## Ce que cette branche apporte + +### Migration Flyway + +| Migration | Ce qu'elle fait | +|---|---| +| V16 | Crée la table `product_images` avec un index unique partiel `WHERE is_primary = TRUE`, garantissant au plus une image primaire par produit au niveau de la base de données | + +### StorageProperties + +`StorageProperties` est un record `@ConfigurationProperties(prefix = "app.storage")` qui +centralise la configuration des téléversements : répertoire d'upload, extensions autorisées, +types MIME autorisés et taille maximale en Mo. Déclaré comme `@Bean` dans `StorageConfig`. + +### FileStorageService / LocalFileStorageService + +`FileStorageService` est une interface avec une unique méthode `store(MultipartFile, Long productId)` +qui retourne le nom de fichier stocké. `LocalFileStorageService` l'implémente avec : + +- Génération de nom de fichier UUID pour éviter les collisions et ignorer le nom original +- Validation de l'extension et du type MIME par rapport aux listes de configuration +- Contrôle de la taille maximale +- Garde contre le path traversal : le chemin absolu résolu est vérifié pour qu'il commence + bien par le répertoire d'upload configuré avant l'écriture + +### ProductImage / ProductImageRepository + +`ProductImage` est une entité JPA avec `@ManyToOne` vers `Product`, `filename`, +`originalFilename`, `contentType`, `fileSize`, et `boolean primary` (pas `isPrimary` - voir +Décisions techniques). `ProductImageRepository` fournit `findAllByProductId` et +`deleteByFilenameAndProductId`. + +### ProductImageService / ProductImageServiceImpl + +`ProductImageServiceImpl` délègue la persistance des fichiers à `FileStorageService` et la +persistance des entités à `ProductImageRepository`. Il gère le "primary swap" : quand une +nouvelle image est téléversée comme primaire, l'image primaire existante (si elle existe) est +rétrogradée pour ne pas violer l'index unique partiel. Il vérifie également la propriété lors +de la suppression : l'image doit appartenir au `productId` donné. + +### Extensions de ProductController + +Deux nouveaux endpoints sont ajoutés à `ProductController` : + +| Méthode | URL | Accès | Description | +|---|---|---|---| +| POST | `/api/v1/products/{id}/images` | ROLE_ADMIN | Téléverser une image (multipart/form-data, champ `file`) | +| DELETE | `/api/v1/products/{id}/images/{imageId}` | ROLE_ADMIN | Supprimer une image | + +`ProductResponse` gagne un champ `images` (`List`). Il est peuplé +uniquement sur `GET /api/v1/products/{id}` (via `ProductMapper.toDetailResponse`) et retourne +une liste vide sur `GET /api/v1/products` (liste paginée) pour éviter le N+1. + +--- + +## Décisions techniques + +**`boolean primary`, pas `isPrimary`** +Lombok génère `isPrimary()` comme getter pour un champ nommé `isPrimary`, que MapStruct +normalise en propriété `primary` (en supprimant le préfixe `is`). Nommer le champ `isPrimary` +créait un mismatch entre le nom du champ et le nom de propriété cible de MapStruct. Renommer +le champ en `primary` résout ce mismatch. La colonne SQL reste `is_primary`. + +**V16, pas V15** +V14 et V15 sont réservées à `feature/orders` sur une branche parallèle. Utiliser V16 évite +un conflit de checksum Flyway lors de la fusion des deux branches. + +**`ProductMapper.toDetailResponse` comme méthode `default`** +Le mapping multi-source MapStruct ne peut pas cibler un constructeur de `record` car les +records sont immuables. `toDetailResponse` est donc une méthode `default` qui appelle +`toResponse` pour construire le DTO de base puis reconstruit le record complet avec la liste +`images` fournie par l'appelant. + +--- + +## Fichiers clés + +| Fichier | Rôle | +|---|---| +| `src/main/java/.../config/StorageProperties.java` | `@ConfigurationProperties(prefix="app.storage")` | +| `src/main/java/.../config/StorageConfig.java` | Enregistre `StorageProperties` comme bean | +| `src/main/java/.../service/FileStorageService.java` | Contrat de stockage | +| `src/main/java/.../service/impl/LocalFileStorageService.java` | Implémentation système de fichiers local | +| `src/main/java/.../entity/ProductImage.java` | Entité JPA | +| `src/main/java/.../repository/ProductImageRepository.java` | Repository Spring Data | +| `src/main/java/.../dto/product/ProductImageResponse.java` | DTO image | +| `src/main/java/.../mapper/ProductImageMapper.java` | Mapper MapStruct | +| `src/main/java/.../service/ProductImageService.java` | Contrat de service image | +| `src/main/java/.../service/impl/ProductImageServiceImpl.java` | Logique primary-swap, vérification propriété | +| `src/main/resources/db/migration/V16__add_product_images.sql` | Migration de schéma | diff --git a/docs/fr/16-shopping-cart-branch.md b/docs/fr/16-shopping-cart-branch.md new file mode 100644 index 0000000..b3e5fa9 --- /dev/null +++ b/docs/fr/16-shopping-cart-branch.md @@ -0,0 +1,105 @@ +# Branche : feature/shopping-cart + +Cette branche introduit un panier d'achat lié à l'utilisateur authentifié. Elle illustre la +création lazy d'entité, le contrôle de propriété et un pattern many-to-many entre utilisateurs +et produits sans entité de jointure dédiée. + +--- + +## Ce que vous allez apprendre + +- Comment créer une ressource de façon lazy à la première utilisation plutôt qu'à la création explicite +- Comment enforcer la propriété dans la couche service (`@AuthenticationPrincipal` transmis au service) +- Comment charger une association bidirectionnelle eagerly avec `@EntityGraph` sur une requête de repository +- En quoi `@WithMockUser` diffère de `.with(user(...))` dans les slices `@WebMvcTest` avec filtres désactivés +- Pourquoi `CartMapper.toResponse` doit être une méthode `default` quand la cible est un `record` + +--- + +## Ce que cette branche apporte + +### Migration Flyway + +| Migration | Ce qu'elle fait | +|---|---| +| V17 | Crée les tables `carts` (une ligne par utilisateur) et `cart_items` (produit, quantité, une ligne par produit par panier) | + +V17 est utilisée à la place de V16 car V16 est réservée par `feature/product-images` sur une +branche parallèle. Choisir V17 en avance évite un conflit de checksum Flyway lors de la fusion. + +### Entités Cart / CartItem + +`Cart` a `@OneToOne AppUser user` et `@OneToMany(cascade = ALL, orphanRemoval = true) List items`. +`CartItem` a `@ManyToOne Cart cart`, `@ManyToOne Product product`, `int quantity` et un +`@Transient BigDecimal subtotal` calculé à la lecture. + +### CartService / CartServiceImpl + +`CartServiceImpl` implémente les règles suivantes : + +- **Création lazy :** une ligne de panier n'est créée qu'au premier appel à `addItem`. `getCart` + ne crée jamais de panier ; il retourne une réponse vide si aucun n'existe. Cela évite les + lignes orphelines pour les utilisateurs qui parcourent le catalogue sans rien ajouter. +- **Vérification produit actif :** les produits avec `active = false` ne peuvent pas être ajoutés. +- **Incrément sur doublon :** ajouter un article déjà dans le panier incrémente sa quantité + plutôt que d'insérer une ligne en doublon. +- **Contrôle de propriété :** `updateItem` et `removeItem` vérifient que l'article appartient + au panier de l'utilisateur authentifié avant toute modification. + +### CartController + +Cinq endpoints, tous sécurisés avec `hasRole("USER")` : + +| Méthode | URL | Description | +|---|---|---| +| GET | `/api/v1/cart` | Voir le panier courant | +| POST | `/api/v1/cart/items` | Ajouter un produit au panier | +| PATCH | `/api/v1/cart/items/{itemId}` | Modifier la quantité d'un article | +| DELETE | `/api/v1/cart/items/{itemId}` | Retirer un article | +| DELETE | `/api/v1/cart` | Vider le panier | + +L'utilisateur authentifié est résolu avec `@AuthenticationPrincipal` et transmis au service, +jamais lu depuis le corps de la requête. + +--- + +## Décisions techniques + +**`@EntityGraph` sur `CartRepository.findByUserId`** +`Cart.items` et `CartItem.product` sont lazy par défaut. Les charger à l'intérieur d'une +méthode de service après le `save` initial déclencherait des sélects supplémentaires hors de +la transaction d'origine. `findByUserId` avec +`@EntityGraph(attributePaths = {"items", "items.product"})` charge le graphe complet en une +seule jointure, et est appelé après chaque mutation pour retourner l'état persisté. + +**`CartMapper.toResponse` comme méthode `default`** +MapStruct `@AfterMapping` ne peut pas modifier un `record` déjà construit. `toResponse` est +une méthode `default` qui itère les articles, calcule les sous-totaux, somme le total du +panier et construit le record manuellement. Même pattern que `ProductMapper.toDetailResponse`. + +**`@WithMockUser` plutôt que `.with(user(...))` dans `CartControllerTest`** +Avec `@AutoConfigureMockMvc(addFilters = false)`, `SecurityContextHolderFilter` ne tourne +jamais, donc `.with(user(...))` ne peuple pas `SecurityContextHolder` et +`@AuthenticationPrincipal` retourne `null`. `@WithMockUser` est traité par +`WithSecurityContextTestExecutionListener`, qui peuple le contexte avant l'exécution de la +méthode de test, contournant entièrement le filtre. + +--- + +## Fichiers clés + +| Fichier | Rôle | +|---|---| +| `src/main/java/.../entity/Cart.java` | Entité JPA, cascade + orphanRemoval | +| `src/main/java/.../entity/CartItem.java` | Entité JPA avec sous-total transient | +| `src/main/java/.../dto/cart/CartItemRequest.java` | DTO de requête ajout d'article | +| `src/main/java/.../dto/cart/CartItemUpdateRequest.java` | DTO de modification de quantité | +| `src/main/java/.../dto/cart/CartItemResponse.java` | DTO de réponse par article | +| `src/main/java/.../dto/cart/CartResponse.java` | DTO de réponse panier complet | +| `src/main/java/.../mapper/CartMapper.java` | default toResponse avec calcul des sous-totaux | +| `src/main/java/.../repository/CartRepository.java` | Chargement eager EntityGraph | +| `src/main/java/.../repository/CartItemRepository.java` | Requêtes par article | +| `src/main/java/.../service/CartService.java` | Contrat de service panier | +| `src/main/java/.../service/impl/CartServiceImpl.java` | Création lazy, propriété, incrément | +| `src/main/java/.../controller/CartController.java` | 5 endpoints, @AuthenticationPrincipal | +| `src/main/resources/db/migration/V17__add_cart_tables.sql` | Migration de schéma | diff --git a/docs/fr/17-order-checkout-branch.md b/docs/fr/17-order-checkout-branch.md new file mode 100644 index 0000000..6677c82 --- /dev/null +++ b/docs/fr/17-order-checkout-branch.md @@ -0,0 +1,81 @@ +# Branche : feature/order-checkout + +Cette branche remplace l'endpoint de création manuelle de commande par une opération de +checkout atomique qui convertit le panier de l'utilisateur authentifié en commande. Elle +illustre l'intégrité transactionnelle, la re-lecture des prix comme mesure de sécurité, et +l'utilisation de `orphanRemoval` JPA pour vider une collection enfant proprement au sein +d'une transaction gérée. + +--- + +## Ce que vous allez apprendre + +- Comment implémenter une transaction "convertir panier en commande" atomique dans un service Spring +- Pourquoi les prix doivent être re-lus depuis la base de données au checkout, et non trust depuis le panier +- Comment vider une collection JPA avec `orphanRemoval` correctement vs un appel bulk-delete de repository +- Comment lier une commande à l'utilisateur authentifié via `@AuthenticationPrincipal` sans mettre l'id dans le corps de la requête + +--- + +## Ce que cette branche apporte + +### Migration Flyway + +| Migration | Ce qu'elle fait | +|---|---| +| V18 | Ajoute une colonne `user_id` nullable sur `orders` avec une FK vers `app_users`. Nullable car les commandes CRUD legacy (avant le checkout) n'ont pas d'utilisateur. | + +### Mise à jour de l'entité Order + +`Order` gagne `@ManyToOne(fetch = LAZY) AppUser user`. La colonne est nullable ; elle est +définie uniquement pour les commandes checkout, jamais pour les commandes CRUD legacy. + +### Flux de checkout + +`OrderServiceImpl.checkout(String username)` : + +1. Charge le panier de l'utilisateur authentifié (lève une 404 si le panier est vide). +2. Pour chaque `CartItem`, re-lit le produit depuis la base de données via `productRepository.findByIdWithCategory` pour obtenir le prix actuel. Cela protège contre la manipulation de prix via un panier obsolète. +3. Crée un `OrderItem` par article du panier en utilisant le snapshot produit (nom + prix unitaire courant). +4. Sauvegarde la `Order` avec tous ses articles en un seul appel `@Transactional`. +5. Vide le panier en appelant `cart.getItems().clear()`. Parce que `Cart.items` a `orphanRemoval = true`, Hibernate supprime les lignes `CartItem` orphelines au flush, dans la même transaction. Voir les décisions techniques. + +### Changement dans OrderController + +`create(@RequestBody OrderRequest)` est remplacé par `checkout(@AuthenticationPrincipal UserDetails)`. +L'endpoint est `POST /api/v1/orders` sans corps de requête. L'identité de l'utilisateur +provient du JWT, pas du client. + +`SecurityConfig` est mis à jour : `POST /api/v1/orders` passe de `hasRole("ADMIN")` à +`hasRole("USER")`. + +--- + +## Décisions techniques + +**Re-lecture des prix depuis la base de données au checkout** +Un `CartItem` stocke la quantité et une référence à un `Product`. Il ne stocke pas le prix. +Au checkout, le produit est rechargé avec `findByIdWithCategory` pour obtenir l'`unitPrice` +actuel depuis la base de données. Cela empêche un client de manipuler les prix en modifiant +un article de panier ajouté quand le prix était plus bas. Le test +`_checkout_06_ShouldUsePriceFromDB_NotFromCachedCartItem` couvre cet invariant. + +**`cart.getItems().clear()` plutôt que `cartItemRepository.deleteAllByCartId`** +Dans une méthode `@Transactional` où l'entité `Cart` est gérée par Hibernate, appeler +`cartItemRepository.deleteAllByCartId()` émet un statement `DELETE` SQL. Cependant, comme +`Cart` est toujours géré avec sa collection `items` en mémoire, le cascade `PERSIST` de +Hibernate réinsère les articles juste supprimés au flush. L'approche correcte est +`cart.getItems().clear()` : Hibernate détecte les orphelins et planifie leur suppression via +`orphanRemoval`, dans le même cycle de flush, sans la réinsertion. Ce bug a été découvert et +corrigé dans `feature/integration`. + +--- + +## Fichiers clés + +| Fichier | Rôle | +|---|---| +| `src/main/java/.../service/OrderService.java` | Ajoute `checkout(String username)` | +| `src/main/java/.../service/impl/OrderServiceImpl.java` | Implémentation checkout atomique | +| `src/main/java/.../controller/OrderController.java` | Remplace create par checkout | +| `src/main/resources/db/migration/V18__add_user_id_to_orders.sql` | FK user nullable | diff --git a/docs/fr/18-order-notifications-branch.md b/docs/fr/18-order-notifications-branch.md new file mode 100644 index 0000000..5f4452d --- /dev/null +++ b/docs/fr/18-order-notifications-branch.md @@ -0,0 +1,88 @@ +# Branche : feature/order-notifications + +Cette branche ajoute des notifications email asynchrones pour les commandes checkout. Elle +montre comment câbler `@Async` sur un executor nommé, comment recharger un agrégat complet +après le commit de la transaction, et pourquoi les échecs d'email ne doivent jamais se +propager à l'appelant. + +--- + +## Ce que vous allez apprendre + +- Comment envoyer des emails avec `JavaMailSender` et `SimpleMailMessage` +- Pourquoi la logique email doit tourner sur un pool de threads dédié (`@Async`) pour ne pas bloquer le thread HTTP +- Pourquoi les exceptions mail doivent être catchées et loggées, jamais relancées +- Comment recharger un graphe d'entité complet après `AFTER_COMMIT` pour avoir l'utilisateur et les articles en contexte +- Comment tester des listeners async de façon synchrone en stubbant les dépendances plutôt que l'executor + +--- + +## Ce que cette branche apporte + +### NotificationProperties + +`NotificationProperties` est un record `@ConfigurationProperties(prefix = "app.notifications")` +avec un seul champ `adminEmail`. Il est enregistré dans `AsyncConfig` aux côtés du bean +`emailTaskExecutor`. + +### OrderEmailService / OrderEmailServiceImpl + +`OrderEmailService` définit deux méthodes : `sendOrderConfirmation(Order, AppUser)` pour le +client et `sendAdminNotification(Order)` pour l'administrateur. + +`OrderEmailServiceImpl` est annoté avec `@Async("emailTaskExecutor")`. Chaque méthode : + +- Construit un `SimpleMailMessage` avec un contenu texte brut +- Appelle `javaMailSender.send(message)` +- Enveloppe l'appel dans un `try/catch(MailException)` et logue l'exception au niveau ERROR + si l'envoi échoue. L'exception n'est jamais relancée. Un echec d'email ne doit pas rollbacker + la commande déjà committée. + +### Extension de OrderRepository + +`findByIdWithItemsAndUser` est ajoutée avec un JPQL `LEFT JOIN FETCH` sur `items` et `user`. +Une nouvelle méthode est ajoutée plutôt que de modifier `findByIdWithDetails` car la méthode +existante utilise `INNER JOIN` sur `customer` et `product` (commandes CRUD legacy), ce qui +retournerait `Optional.empty()` pour les commandes checkout qui n'ont pas de `customer_id` ni +de `product_id`. + +### OrderCreatedEventListener + +`OrderCreatedEventListener` est enrichi pour : + +1. Tourner sur `emailTaskExecutor` via `@Async("emailTaskExecutor")`. +2. Recharger la commande complète depuis la base de données avec `findByIdWithItemsAndUser`. L'event ne transporte que l'id de commande ; l'objet complet n'est pas passé dans l'event pour éviter les problèmes de données obsolètes après le commit de la transaction. +3. Appeler `orderEmailService.sendOrderConfirmation` si la commande a un utilisateur, et `orderEmailService.sendAdminNotification` inconditionnellement. + +--- + +## Décisions techniques + +**`findByIdWithItemsAndUser` séparé plutôt que modifier `findByIdWithDetails`** +`findByIdWithDetails` utilise `INNER JOIN` sur `customer` et `product`. Les commandes checkout +ont `customer_id = NULL` et `product_id = NULL`, donc un `INNER JOIN` sur ces colonnes ne +retourne aucune ligne. Modifier la méthode existante casserait `OrderServiceImpl.findById` et +tous ses tests. Ajouter une nouvelle méthode garde les deux chemins de lecture indépendants. + +**`@Async` sur le listener d'evenement** +`@TransactionalEventListener(phase = AFTER_COMMIT)` garantit déjà que le listener tourne +après le commit de la transaction de commande. Ajouter `@Async("emailTaskExecutor")` déplace +l'exécution hors du thread de requête HTTP, de sorte que la réponse client (201 Created) +n'est pas retardée par la latence SMTP. + +**Stubbing par méthode de test, pas dans `@BeforeEach`** +Le mode strict de Mockito (`STRICT_STUBS`) lève `UnnecessaryStubbingException` pour les +stubs configurés mais jamais consommés dans un test donné. `notificationProperties.adminEmail()` +est stubbé uniquement dans les méthodes de test qui l'invoquent réellement, pas dans `@BeforeEach`. + +--- + +## Fichiers clés + +| Fichier | Rôle | +|---|---| +| `src/main/java/.../config/NotificationProperties.java` | `@ConfigurationProperties(prefix="app.notifications")` | +| `src/main/java/.../service/OrderEmailService.java` | Contrat de service email | +| `src/main/java/.../service/impl/OrderEmailServiceImpl.java` | Async, email texte brut, exception avalée | +| `src/main/java/.../event/OrderCreatedEventListener.java` | Recharge la commande, dispatche les emails | +| `src/main/java/.../repository/OrderRepository.java` | Ajoute findByIdWithItemsAndUser | diff --git a/docs/fr/19-order-authorization-branch.md b/docs/fr/19-order-authorization-branch.md new file mode 100644 index 0000000..7477e5f --- /dev/null +++ b/docs/fr/19-order-authorization-branch.md @@ -0,0 +1,96 @@ +# Branche : feature/order-authorization + +Cette branche rend la ressource commande consciente des rôles : les utilisateurs normaux ne +peuvent voir et agir que sur leurs propres commandes, tandis que les admins ont une visibilité +complète. Elle ajoute également un système de transitions de statut avec matrice de cycle de +vie et le couvre avec un vrai test Testcontainers end-to-end. + +--- + +## Ce que vous allez apprendre + +- Comment implémenter des endpoints de liste et de détail conscients du rôle dans la couche service +- Comment enforcer une matrice de transition de statut et retourner 422 pour les transitions invalides +- Comment combiner `@PreAuthorize` et `@AuthenticationPrincipal` sur une méthode de contrôleur +- Comment écrire un test end-to-end multi-acteurs avec Testcontainers (userA, userB, admin) +- Pourquoi `INNER JOIN` sur des colonnes FK nullable supprime silencieusement des lignes, et quand utiliser `LEFT JOIN FETCH` + +--- + +## Ce que cette branche apporte + +### Accès aux commandes conscient du rôle + +`OrderService` gagne deux nouvelles signatures : + +- `findAll(String username, boolean isAdmin, Pageable)` - les admins reçoivent toutes les + commandes ; les utilisateurs normaux reçoivent uniquement les commandes où + `order.user.username = username` (via la FK `user_id`). +- `findById(Long id, String username, boolean isAdmin)` - les admins peuvent récupérer + n'importe quelle commande ; un utilisateur normal reçoit un 404 si la commande appartient + à un autre utilisateur. + +### Cycle de vie du statut de commande + +`updateStatus(Long id, OrderStatus newStatus)` enforece la matrice de transition suivante : + +| De | Transitions autorisées | +|---|---| +| PENDING | CONFIRMED, CANCELLED | +| CONFIRMED | CANCELLED | +| CANCELLED | (aucune) | + +Toute autre transition retourne 422 `Unprocessable Entity`. + +### Réécriture de OrderController + +`OrderController` est réécrit avec `@AuthenticationPrincipal` et `@PreAuthorize` : + +- `GET /api/v1/orders` - `@PreAuthorize("isAuthenticated()")`, délègue avec username + isAdmin +- `GET /api/v1/orders/{id}` - `@PreAuthorize("isAuthenticated()")`, délègue avec username + isAdmin +- `PATCH /api/v1/orders/{id}/status` - `@PreAuthorize("hasRole('ADMIN')")`, corps `OrderStatusUpdateRequest` + +### Correction de bug : LEFT JOIN FETCH sur FK nullable + +`findByIdWithDetails` utilisait précédemment `INNER JOIN` sur `customer` et `product`. Les +commandes checkout ont `customer_id = NULL` et `product_id = NULL`. Un `INNER JOIN` sur une +colonne nullable ne retourne silencieusement aucune ligne quand la valeur est null, donc les +commandes checkout étaient invisibles pour `findById`. Corrigé en basculant vers `LEFT JOIN FETCH` +sur ces deux associations. + +### OrderAuthorizationTest + +8 cas de test d'intégration Testcontainers couvrant : + +- userA peut voir sa propre commande +- userA reçoit 404 sur la commande de userB +- admin peut voir toutes les commandes (findAll et findById) +- admin peut mettre à jour le statut (PENDING vers CONFIRMED) +- un utilisateur normal ne peut pas mettre à jour le statut (403) +- une transition de statut invalide retourne 422 + +--- + +## Décisions techniques + +**404 plutôt que 403 pour l'accès croisé aux commandes** +Retourner 403 (Forbidden) révélerait qu'une commande avec l'id donné existe, ce qui est en +soi une information. Retourner 404 (Not Found) pour un utilisateur essayant d'accéder à la +commande d'un autre utilisateur empêche l'enumération des ids de commandes d'autres utilisateurs. + +**`findAllByCustomerId` ajouté à `OrderService`** +`CustomerController.findOrders` appelait précédemment `orderService.findAll` directement. +Avec la nouvelle signature consciente du rôle, `findAllByCustomerId(Long, Pageable)` est +ajoutée comme méthode dédiée pour l'endpoint imbriqué, découplée du `findAll` scopé sur l'utilisateur. + +--- + +## Fichiers clés + +| Fichier | Rôle | +|---|---| +| `src/main/java/.../dto/order/OrderStatusUpdateRequest.java` | DTO de requête PATCH statut | +| `src/main/java/.../service/OrderService.java` | findAll/findById conscients du rôle + updateStatus | +| `src/main/java/.../service/impl/OrderServiceImpl.java` | Matrice de transition, vérification propriété | +| `src/main/java/.../controller/OrderController.java` | @PreAuthorize + @AuthenticationPrincipal | +| `src/test/java/.../OrderAuthorizationTest.java` | Test e2e Testcontainers 8 cas | diff --git a/docs/fr/20-integration-branch.md b/docs/fr/20-integration-branch.md new file mode 100644 index 0000000..82d7429 --- /dev/null +++ b/docs/fr/20-integration-branch.md @@ -0,0 +1,85 @@ +# Branche : feature/integration + +Cette branche fusionne `feature/order-authorization` et `feature/product-images` en une +branche d'intégration unique, corrige un bug critique de vidage de panier découvert uniquement +à l'intégration, et valide le flux e-commerce complet avec un test end-to-end. + +--- + +## Ce que vous allez apprendre + +- Comment un bug de cascade `PERSIST` peut silencieusement annuler un `DELETE` pourtant correct au sein d'une transaction +- Pourquoi un clear `orphanRemoval` est la bonne façon de supprimer des enfants JPA dans une session gérée +- Comment écrire un test end-to-end multi-étapes qui couvre un parcours utilisateur complet +- Pourquoi les bugs d'intégration n'apparaissent souvent que lorsque deux branches testées indépendamment sont fusionnées + +--- + +## Ce que cette branche apporte + +### Correction de bug critique : panier non vidé après checkout + +Après la fusion de `feature/order-checkout` (qui introduisait `checkout()`) avec la pile +e-commerce complète, une régression critique est apparue : le panier n'était pas vidé après +un checkout réussi. + +**Cause racine :** `checkout()` appelait à l'origine +`cartItemRepository.deleteAllByCartId(cart.getId())`. Dans la même méthode `@Transactional`, +l'entité `Cart` est gérée par Hibernate avec sa collection `items` toujours en mémoire. +Après l'émission du SQL `DELETE`, le cascade `PERSIST` de Hibernate réinsère les articles +juste supprimés au flush car la collection gérée les référence encore. + +**Correction :** `cart.getItems().clear()` remplace l'appel au repository. Avec +`orphanRemoval = true` sur `Cart.items`, Hibernate planifie la suppression des lignes +`CartItem` orphelines pendant la phase de flush, dans la même transaction, sans la réinsertion. +`CartItemRepository` est retiré de `OrderServiceImpl` en conséquence. + +### Extension du constructeur ProductResponse + +`feature/product-images` avait ajouté un champ `images` (8e argument) au constructeur du +record `ProductResponse`. Après la fusion, chaque site d'appel qui construisait un +`ProductResponse` avec 7 arguments s'est cassé. Corrigé dans : + +- `OrderMapper.toResponse(OrderProjection)` - le chemin liste basé sur la projection +- `CustomerControllerTest` - construction de client exemple +- `OrderControllerTest` - helper `sampleResponse()` +- `OrderServiceImplTest` - toutes les assertions `OrderResponse` + +### EcommerceIntegrationTest + +Un unique test `@SpringBootTest` Testcontainers qui parcourt 11 étapes : + +1. Inscription de userA +2. Connexion userA, obtention du JWT +3. Vérification que le catalogue est accessible sans authentification +4. Ajout de deux produits différents au panier +5. GET panier, vérification des articles et sous-totaux +6. PATCH quantité d'un article +7. POST checkout - commande créée, panier vidé +8. GET commandes (userA) - voit une commande +9. GET commande par id - détail avec articles, statut = PENDING +10. Inscription admin + connexion admin +11. PATCH statut commande vers CONFIRMED - 200 ; GET commande en tant que userA - statut = CONFIRMED + +--- + +## Décisions techniques + +**`cart.getItems().clear()` - l'approche JPA idiomatique** +`deleteAllByCartId()` contourne la session Hibernate. Dans une session où `Cart` est géré +avec sa collection, le cache de premier niveau et le dirty-checking de l'ORM annuleront tout +DELETE SQL direct si l'état en mémoire contient encore des références. La correction +idiomatique est de modifier la collection à travers l'objet géré et de laisser la session +propager le changement. C'est un concept JPA fondamental qui ne se manifeste que lorsque des +graphes d'entités avec `cascade` et `orphanRemoval` sont exercés dans la même transaction +qu'une mutation de collection enfant. + +--- + +## Fichiers clés + +| Fichier | Rôle | +|---|---| +| `src/main/java/.../service/impl/OrderServiceImpl.java` | Correction : `cart.getItems().clear()` | +| `src/main/java/.../mapper/OrderMapper.java` | Constructeur `ProductResponse` à 8 args | +| `src/test/java/.../EcommerceIntegrationTest.java` | Test e2e 11 étapes | From 778e2197e4443579c18ff4660874639f70d9a3d8 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Fri, 20 Nov 2026 19:51:18 +0400 Subject: [PATCH 175/175] docs(insomnia): add e-commerce endpoints (product images, cart, checkout, order status) --- spring-boot-tutorial.insomnia.yaml | 210 +++++++++++++++++++++++++++++ 1 file changed, 210 insertions(+) diff --git a/spring-boot-tutorial.insomnia.yaml b/spring-boot-tutorial.insomnia.yaml index 02d8d5d..43f04da 100644 --- a/spring-boot-tutorial.insomnia.yaml +++ b/spring-boot-tutorial.insomnia.yaml @@ -307,6 +307,54 @@ collection: send: true store: true rebuildPath: true + - url: "{{ baseUrl }}/api/v1/products/1/images" + name: Upload product image + meta: + id: req_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "Upload a product image (multipart/form-data). Requires ROLE_ADMIN." + sortKey: -1788200450000 + method: POST + body: + mimeType: multipart/form-data + params: + - name: file + value: "" + type: file + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true + - url: "{{ baseUrl }}/api/v1/products/1/images/1" + name: Delete product image + meta: + id: req_b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "Delete a product image by id. Requires ROLE_ADMIN." + sortKey: -1788200425000 + method: DELETE + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true - url: "{{ baseUrl }}/api/v1/products/1" name: Get product by id meta: @@ -1006,6 +1054,36 @@ collection: send: true store: true rebuildPath: true + - url: "{{ baseUrl }}/api/v1/orders/1/status" + name: Update order status (ADMIN) + meta: + id: req_c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "Update the lifecycle status of an order. Allowed transitions: PENDING->CONFIRMED/CANCELLED, CONFIRMED->CANCELLED. Requires ROLE_ADMIN." + sortKey: -1788200350000 + method: PATCH + body: + mimeType: application/json + text: |- + { + "status": "CONFIRMED" + } + headers: + - name: Content-Type + value: application/json + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true - name: Customers meta: id: fld_b97520db2abf41dc8a6309997fec9413 @@ -1267,6 +1345,138 @@ collection: send: true store: true rebuildPath: true + - name: Cart + meta: + id: fld_d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1 + created: 1794207000000 + modified: 1794207000000 + sortKey: -1788200700011 + description: "" + children: + - url: "{{ baseUrl }}/api/v1/cart" + name: Get cart + meta: + id: req_e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "View the current user's cart. Returns an empty cart if none exists yet. Requires ROLE_USER." + sortKey: -1788200000000 + method: GET + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true + - url: "{{ baseUrl }}/api/v1/cart/items" + name: Add item to cart + meta: + id: req_f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "Add a product to the cart. Creates the cart on first call. Increments quantity if the product is already in the cart. Requires ROLE_USER." + sortKey: -1788200100000 + method: POST + body: + mimeType: application/json + text: |- + { + "product_id": 1, + "quantity": 2 + } + headers: + - name: Content-Type + value: application/json + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true + - url: "{{ baseUrl }}/api/v1/cart/items/1" + name: Update item quantity + meta: + id: req_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d5 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "Update the quantity of a cart item. Requires ROLE_USER and ownership." + sortKey: -1788200200000 + method: PATCH + body: + mimeType: application/json + text: |- + { + "quantity": 3 + } + headers: + - name: Content-Type + value: application/json + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true + - url: "{{ baseUrl }}/api/v1/cart/items/1" + name: Remove item from cart + meta: + id: req_b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e6 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "Remove a single item from the cart. Requires ROLE_USER and ownership." + sortKey: -1788200300000 + method: DELETE + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true + - url: "{{ baseUrl }}/api/v1/cart" + name: Clear cart + meta: + id: req_c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f7 + created: 1794207000000 + modified: 1794207000000 + isPrivate: false + description: "Remove all items from the cart. The cart row itself is kept. Requires ROLE_USER." + sortKey: -1788200400000 + method: DELETE + authentication: + type: bearer + token: "{{ token }}" + settings: + renderRequestBody: true + encodeUrl: true + followRedirects: global + cookies: + send: true + store: true + rebuildPath: true cookieJar: name: Default Jar meta: