diff --git a/.env.example b/.env.example index cff5aea..57b6f1b 100644 --- a/.env.example +++ b/.env.example @@ -21,3 +21,5 @@ MAIL_SMTP_AUTH=false MAIL_SMTP_STARTTLS=false APP_BASE_URL=http://localhost:8080 +APP_NOTIFICATION_ADMIN_EMAIL=admin@example.com +APP_STORAGE_UPLOAD_DIR=./uploads/products diff --git a/README.md b/README.md index d49c289..d1fdb1b 100644 --- a/README.md +++ b/README.md @@ -18,12 +18,19 @@ 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) - [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) @@ -52,6 +59,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 @@ -68,6 +77,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** @@ -82,7 +93,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 +107,113 @@ 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`, `feature/order-checkout`, and `feature/order-authorization`) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| 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 | +|---|---|---| +| 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 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 | +| is_primary | BOOLEAN | NOT NULL DEFAULT FALSE — partial unique index enforces at most one primary per product | + +**carts** (added in V17) +| Column | Type | Constraints | +|---|---|---| +| id | BIGINT | PK, auto-increment | +| user_id | BIGINT | FK → app_users.id, NOT NULL UNIQUE — one cart per user | + +**cart_items** (added in V17) | Column | Type | Constraints | |---|---|---| | id | BIGINT | PK, auto-increment | -| customer_id | BIGINT | FK → customers.id, NOT NULL | +| cart_id | BIGINT | FK → carts.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 | + +**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 @@ -117,11 +229,19 @@ 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. ## Project structure +The tree below shows the full final state across all branches. + ``` spring-boot-tutorial/ ├── src/ @@ -131,69 +251,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/ @@ -203,12 +393,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 @@ -346,6 +550,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 +570,65 @@ 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/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 @@ -396,35 +659,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 @@ -563,6 +838,278 @@ 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 `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 + +- `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 `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 +- [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`) + +## 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) + +## 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) + +## 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) + +## 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` @@ -573,7 +1120,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 @@ -619,13 +1172,165 @@ Admin-facing user management: list, view, activate/deactivate accounts, assign r - Local development tooling (Spring Boot DevTools) - 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. 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 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 | 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: 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); diff --git a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java index 20e994c..e0f41d6 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/DataSeeder.java @@ -9,13 +9,14 @@ import com.edgareldy.springboottutorial.repository.CategoryRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; import com.edgareldy.springboottutorial.repository.RoleRepository; +import java.math.BigDecimal; import java.util.List; import java.util.Set; 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; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; import org.springframework.security.crypto.password.PasswordEncoder; @@ -54,11 +55,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()); } if (appUserRepository.count() == 0) { 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 +) { +} diff --git a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java index eb5ba60..9e44456 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/SecurityConfig.java @@ -88,12 +88,24 @@ 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.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/customers/**", "/api/v1/orders/**") + .requestMatchers(HttpMethod.PUT, "/api/v1/orders/**") .hasRole("ADMIN") - .requestMatchers(HttpMethod.DELETE, "/api/v1/customers/**", "/api/v1/orders/**") + .requestMatchers(HttpMethod.DELETE, "/api/v1/orders/**") .hasRole("ADMIN") + .requestMatchers(HttpMethod.POST, "/api/v1/customers/**") + .hasRole("ADMIN") + .requestMatchers(HttpMethod.PUT, "/api/v1/customers/**") + .hasRole("ADMIN") + .requestMatchers(HttpMethod.DELETE, "/api/v1/customers/**") + .hasRole("ADMIN") + .requestMatchers("/api/v1/cart/**") + .hasRole("USER") .anyRequest() .authenticated()) .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); 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 +) { +} 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")); + } +} 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")); } } diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java b/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java index 8e44338..9b7572b 100644 --- a/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java +++ b/src/main/java/com/edgareldy/springboottutorial/controller/OrderController.java @@ -2,28 +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 @@ -38,34 +44,62 @@ 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 - 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")); + } + + @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")); + } } diff --git a/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java b/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java index 4837791..cfa6cb6 100644 --- a/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java +++ b/src/main/java/com/edgareldy/springboottutorial/controller/ProductController.java @@ -2,10 +2,13 @@ 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; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; @@ -19,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 @@ -35,13 +39,14 @@ public class ProductController { private final ProductService productService; + private final ProductImageService productImageService; @GetMapping 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), @@ -71,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")); + } } 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..57900db --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/dto/cart/CartItemRequest.java @@ -0,0 +1,24 @@ +package com.edgareldy.springboottutorial.dto.cart; + +import com.fasterxml.jackson.annotation.JsonProperty; +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( + @JsonProperty("product_id") + @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/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/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 +) {} 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 +) {} 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 ) { } 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 ) { } 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 +) { +} 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 ) { } 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 +) {} 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 ) { } 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 +) { +} 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 ) { } 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..8443866 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,8 @@ package com.edgareldy.springboottutorial.dto.product; import com.fasterxml.jackson.annotation.JsonProperty; +import java.math.BigDecimal; +import java.util.List; /** * Representation of a {@link com.edgareldy.springboottutorial.entity.Product} @@ -9,6 +11,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,12 +26,18 @@ public record ProductResponse( String productName, @JsonProperty("unit_price") - float unitPrice, + BigDecimal unitPrice, + + String description, + + boolean active, @JsonProperty("category_id") Long categoryId, @JsonProperty("category_name") - String categoryName + String categoryName, + + List images ) { } 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; 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; +} 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; +} diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/Order.java b/src/main/java/com/edgareldy/springboottutorial/entity/Order.java index bdee7f5..47c13c7 100644 --- a/src/main/java/com/edgareldy/springboottutorial/entity/Order.java +++ b/src/main/java/com/edgareldy/springboottutorial/entity/Order.java @@ -1,14 +1,22 @@ 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.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 +24,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 +51,32 @@ public class Order { private Long id; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "customer_id", nullable = false) + @JoinColumn(name = "user_id") + private AppUser user; + + @ManyToOne(fetch = FetchType.LAZY) + @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<>(); } 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; +} 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 +} 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; 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..1c76e36 --- /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 primary; + + @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; +} 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 ) { } diff --git a/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java b/src/main/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListener.java index eeca3a5..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,13 +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.customerId(), event.productId(), event.quantity(), event.total()); + 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); } } 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); + } +} diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/CustomerMapper.java index 21aa1ce..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}. @@ -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); 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); +} diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/OrderMapper.java index 3e60509..ebb9a8f 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,52 @@ 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(), + List.of()); + return new OrderResponse( + p.id(), customer, product, p.quantity(), + p.orderNumber(), p.status().name(), 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); } 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); +} diff --git a/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java b/src/main/java/com/edgareldy/springboottutorial/mapper/ProductMapper.java index ad5dd3a..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; @@ -13,7 +15,11 @@ * {@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 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 @@ -25,15 +31,29 @@ 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) + @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); } 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..c70cea1 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/repository/CartItemRepository.java @@ -0,0 +1,20 @@ +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); + + void deleteAllByCartId(Long cartId); +} 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); +} diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderProjection.java index cbaf334..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,8 @@ package com.edgareldy.springboottutorial.repository; +import com.edgareldy.springboottutorial.entity.OrderStatus; +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 +11,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 +29,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, + OrderStatus status, + String orderNumber ) { } diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/OrderRepository.java index b2fb84a..16595de 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; @@ -23,8 +24,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 +48,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 +62,44 @@ 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 " + + "LEFT JOIN FETCH o.customer " + + "LEFT JOIN FETCH o.product p LEFT 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); + /** + * 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); + + /** + * 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); 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); +} 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); 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..f64f3ee --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/CartService.java @@ -0,0 +1,33 @@ +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 { + + /** + * 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); + + CartResponse updateItem(String username, Long itemId, CartItemUpdateRequest request); + + CartResponse removeItem(String username, Long itemId); + + CartResponse clearCart(String username); +} 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); +} diff --git a/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java b/src/main/java/com/edgareldy/springboottutorial/service/OrderService.java index 6afc15f..595e733 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,35 @@ 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. + * 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); + + /** + * 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); 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); +} 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); 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..bfd208f --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/CartServiceImpl.java @@ -0,0 +1,145 @@ +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 + 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)); + } +} 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) { 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..9bd228b --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImpl.java @@ -0,0 +1,112 @@ +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.user.AppUser; +import com.edgareldy.springboottutorial.service.OrderEmailService; +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.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} + * 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 + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@Service +public class OrderEmailServiceImpl implements OrderEmailService { + + private static final Logger log = LoggerFactory.getLogger(OrderEmailServiceImpl.class); + + 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; + } + + @Override + @Async("emailTaskExecutor") + public void sendOrderConfirmation(AppUser user, Order order) { + 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) { + String customerName = "N/A"; + String customerEmail = null; + if (order.getUser() != null) { + AppUser user = order.getUser(); + 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(); + } + 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()); + } + } +} 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..77700a2 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImpl.java @@ -4,19 +4,31 @@ 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.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; +import java.util.UUID; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.springframework.context.ApplicationEventPublisher; @@ -43,11 +55,19 @@ 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; @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 @@ -61,40 +81,162 @@ 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); })); } @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) { + 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); + cart.getItems().clear(); + + eventPublisher.publishEvent(new OrderCreatedEvent( + saved.getId(), null, null, saved.getQuantity(), + saved.getTotalAmount(), saved.getOrderNumber())); + 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) { 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)); } @@ -107,6 +249,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)); 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..8bb9ebd --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImpl.java @@ -0,0 +1,79 @@ +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.cache.annotation.CacheEvict; +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 + @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)); + + 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 + @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)); + if (!image.getProduct().getId().equals(productId)) { + throw new ResourceNotFoundException("Image " + imageId + " does not belong to product " + productId); + } + fileStorageService.delete(image.getImageUrl()); + productImageRepository.delete(image); + } +} 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 2be4b85..276929f 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/ProductServiceImpl.java @@ -1,18 +1,23 @@ 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.BusinessRuleException; 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.OrderRepository; +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; @@ -49,10 +54,12 @@ public class ProductServiceImpl implements ProductService { private final CategoryRepository categoryRepository; private final ProductMapper productMapper; private final OrderRepository orderRepository; + private final ProductImageRepository productImageRepository; + private final ProductImageMapper productImageMapper; @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 @@ -77,7 +84,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 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); +} 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() : ""; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b054a89..26bc5d6 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -13,6 +13,11 @@ 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} + storage: + upload-dir: ${APP_STORAGE_UPLOAD_DIR:./uploads/products} + max-file-size-mb: 5 jwt: secret: ${JWT_SECRET:dev-only-jwt-secret-please-override-in-production-0123456789} 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); 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'); 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; 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; diff --git a/src/main/resources/db/migration/V17__create_cart_tables.sql b/src/main/resources/db/migration/V17__create_cart_tables.sql new file mode 100644 index 0000000..3cfbe9f --- /dev/null +++ b/src/main/resources/db/migration/V17__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); 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; 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
+ +
+ + 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
+ +
+ + 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..469245d --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CartControllerTest.java @@ -0,0 +1,143 @@ +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.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.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. 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 + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@WebMvcTest(CartController.class) +@AutoConfigureMockMvc(addFilters = false) +@WithMockUser(username = "alice", roles = "USER") +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")) + .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") + .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") + .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") + .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") + .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")) + .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")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.items").isEmpty()); + } +} diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CategoryControllerTest.java index 9e82ec1..1ed5b0f 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.security.JwtService; @@ -91,7 +92,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", 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/CustomerControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java index 4c344ad..a192839 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/CustomerControllerTest.java @@ -26,6 +26,7 @@ import com.edgareldy.springboottutorial.service.BlacklistedTokenService; 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; @@ -83,7 +84,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 @@ -195,13 +197,15 @@ 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", 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, 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); + when(orderService.findAllByCustomerId(eq(1L), any())).thenReturn(page); mockMvc.perform(get("/api/v1/customers/1/orders")) .andExpect(status().isOk()) 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..17014d8 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/controller/EcommerceIntegrationTest.java @@ -0,0 +1,213 @@ +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()) + .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 + .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(); + } +} 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..494f0db --- /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.totalElements").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.totalElements", + 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(); + } +} diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/OrderControllerTest.java index 9c8a595..8e3511d 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,16 +14,19 @@ 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; import com.edgareldy.springboottutorial.service.BlacklistedTokenService; 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; @@ -31,15 +34,15 @@ 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 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 @@ -59,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; @@ -77,49 +78,62 @@ 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", List.of()); + 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); - return new PageResponse<>(List.of(entry), 0, 20, 1, 1); + 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 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.0)) - .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[1].product_id").value(2)) - .andExpect(jsonPath("$.data.content[0].total").value(300.0)); + .andExpect(jsonPath("$.data.content[0].order_number").value("ORD-TEST-0001")) + .andExpect(jsonPath("$.data.totalElements").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 - void _03_ShouldReturn404_WhenOrderMissing() throws Exception { - when(orderService.findById(99L)).thenThrow(new ResourceNotFoundException("Order not found with id 99")); + @WithMockUser(username = "admin", roles = "ADMIN") + void _03_ShouldReturn200_WhenOrderFound() throws Exception { + when(orderService.findById(eq(1L), eq("admin"), eq(true))).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 + @WithMockUser(username = "alice", roles = "USER") + void _03b_ShouldReturn404_WhenOrderMissing() throws Exception { + 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()) @@ -127,36 +141,42 @@ void _03_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.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 + @WithMockUser(username = "admin", roles = "ADMIN") void _07_ShouldReturn200_WhenUpdateRequestValid() throws Exception { when(orderService.update(eq(1L), any())).thenReturn(sampleResponse()); @@ -168,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")); @@ -179,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()) @@ -186,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); @@ -194,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)); + } } diff --git a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java index b9b2674..279c42e 100644 --- a/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/controller/ProductControllerTest.java @@ -14,23 +14,30 @@ 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.BusinessRuleException; import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.security.JwtService; import com.edgareldy.springboottutorial.service.BlacklistedTokenService; +import com.edgareldy.springboottutorial.service.ProductImageService; 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; 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.security.core.userdetails.UserDetailsService; 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: this @@ -68,9 +75,13 @@ class ProductControllerTest { @MockitoBean private BlacklistedTokenService blacklistedTokenService; + @MockitoBean + private ProductImageService productImageService; + @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", List.of()); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); when(productService.findAll(isNull(), isNull(), isNull(), isNull(), any())).thenReturn(page); @@ -81,7 +92,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", List.of()); PageResponse page = new PageResponse<>(List.of(product), 0, 20, 1, 1); when(productService.findAll(eq(1L), isNull(), isNull(), isNull(), any())).thenReturn(page); @@ -92,9 +104,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", List.of()); 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") @@ -115,8 +129,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", List.of())); mockMvc.perform(post("/api/v1/products") .contentType(MediaType.APPLICATION_JSON) @@ -127,7 +142,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) @@ -138,7 +153,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") @@ -149,9 +164,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", List.of())); mockMvc.perform(put("/api/v1/products/1") .contentType(MediaType.APPLICATION_JSON) @@ -162,7 +178,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)); @@ -175,7 +191,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")); @@ -201,4 +217,72 @@ 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", 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)); + } + + @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)); + } } 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..8e93e7e --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/event/OrderCreatedEventListenerTest.java @@ -0,0 +1,107 @@ +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; + +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; +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); + } + + @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); + } +} 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; } 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")); } } diff --git a/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java b/src/test/java/com/edgareldy/springboottutorial/mapper/OrderMapperTest.java index 5b3b465..952b602 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"), OrderStatus.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"), 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"), OrderStatus.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")); } } 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(); } } 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..3c36818 --- /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(); + + // 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(); + assertThatThrownBy(() -> cartRepository.save(duplicate)) + .isInstanceOf(DataIntegrityViolationException.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(); + + // 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(); + assertThatThrownBy(() -> cartItemRepository.save(duplicate)) + .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); + } +} 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(); diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/OrderRepositoryTest.java index 6eb0c3b..a063235 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,46 @@ 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")); + } + + @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() + .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); } } diff --git a/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java b/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java index 7baf035..18f5da4 100644 --- a/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/repository/ProductRepositoryTest.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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -47,9 +48,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 @@ -86,7 +87,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 @@ -95,7 +97,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); } 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..89aaddb --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/CartServiceImplTest.java @@ -0,0 +1,212 @@ +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); + // 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 + 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); + } +} 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..40b357a 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,17 @@ 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.entity.OrderStatus; 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 +69,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 +90,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 +106,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"), 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", 0.1f, 1L, "Electronics", 2, 0.2); + 2L, "Desk", new BigDecimal("0.10"), true, 1L, "Electronics", + 2, new BigDecimal("0.20"), OrderStatus.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 +150,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"), 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( 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 +214,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 +231,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); 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..ecc109e --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderEmailServiceImplTest.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.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.verify; + +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; +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.javamail.JavaMailSender; +import org.thymeleaf.context.Context; +import org.thymeleaf.context.IContext; +import org.thymeleaf.spring6.SpringTemplateEngine; + +/** + * 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 + * Date : 11/19/26 + * Project : spring-boot-tutorial + */ +@ExtendWith(MockitoExtension.class) +class OrderEmailServiceImplTest { + + @Mock + private JavaMailSender mailSender; + + @Mock + private SpringTemplateEngine templateEngine; + + @Mock + private NotificationProperties notificationProperties; + + private OrderEmailServiceImpl service; + + @BeforeEach + void setUp() { + service = new OrderEmailServiceImpl(mailSender, templateEngine, 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() { + 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 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() { + 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 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() { + 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(); + } +} 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..7b05bf3 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/OrderServiceImplTest.java @@ -13,17 +13,26 @@ 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.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; @@ -51,20 +60,13 @@ @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; @InjectMocks private OrderServiceImpl orderService; @@ -79,25 +81,31 @@ 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", List.of()); + orderResponse = new OrderResponse(1L, customerResponse, productResponse, 2, + "ORD-HIST-000001", "PENDING", new BigDecimal("100.00"), List.of()); } @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", 50.0f, 1L, "Electronics", 2, 100.0); - when(orderRepository.findAllProjected(null, null, pageable)) + 1L, "Keyboard", new BigDecimal("50.00"), true, 1L, "Electronics", + 2, new BigDecimal("100.00"), OrderStatus.PENDING, "ORD-HIST-000001"); + 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); } @@ -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"), 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", 0.1f, 1L, "Electronics", 2, 0.2); + 2L, "Desk", new BigDecimal("0.10"), true, 1L, "Electronics", + 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", 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"), 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)) .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); @@ -145,39 +156,146 @@ 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)); 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); + } + + @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_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 +324,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 +337,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); @@ -249,4 +373,143 @@ 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 + assertThat(cart.getItems()).isEmpty(); + 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()); + } + + @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_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") + .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")); + } } 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..4dbcd72 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductImageServiceImplTest.java @@ -0,0 +1,166 @@ +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(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 _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(); + 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()); + } +} 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 93dc093..675d776 100644 --- a/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java +++ b/src/test/java/com/edgareldy/springboottutorial/service/impl/ProductServiceCacheTest.java @@ -1,19 +1,24 @@ 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.OrderRepository; +import com.edgareldy.springboottutorial.repository.ProductImageRepository; 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; @@ -77,6 +82,12 @@ CacheManager cacheManager() { @MockitoBean private OrderRepository orderRepository; + @MockitoBean + private ProductImageRepository productImageRepository; + + @MockitoBean + private ProductImageMapper productImageMapper; + @BeforeEach void clearCache() { Cache products = cacheManager.getCache("products"); @@ -87,15 +98,17 @@ 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", 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); @@ -106,15 +119,17 @@ 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", 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())); 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); @@ -123,9 +138,10 @@ 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", 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); when(orderRepository.existsByProductId(1L)).thenReturn(false); 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 cbf76b5..1002532 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; @@ -15,10 +16,13 @@ import com.edgareldy.springboottutorial.entity.Product; import com.edgareldy.springboottutorial.exception.BusinessRuleException; 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.OrderRepository; +import com.edgareldy.springboottutorial.repository.ProductImageRepository; import com.edgareldy.springboottutorial.repository.ProductRepository; +import java.math.BigDecimal; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; @@ -56,6 +60,12 @@ class ProductServiceImplTest { @Mock private OrderRepository orderRepository; + @Mock + private ProductImageRepository productImageRepository; + + @Mock + private ProductImageMapper productImageMapper; + @InjectMocks private ProductServiceImpl productService; @@ -66,8 +76,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", List.of()); } @Test @@ -101,7 +112,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); @@ -111,7 +123,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); } @@ -126,7 +138,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); @@ -137,7 +149,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)) @@ -148,8 +160,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", List.of()); when(productRepository.findById(1L)).thenReturn(Optional.of(product)); when(categoryRepository.findById(1L)).thenReturn(Optional.of(category)); when(productRepository.save(product)).thenReturn(product); @@ -162,7 +175,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)) @@ -173,7 +186,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()); 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..13f7617 --- /dev/null +++ b/src/test/java/com/edgareldy/springboottutorial/storage/LocalFileStorageServiceTest.java @@ -0,0 +1,122 @@ +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"); + } + + @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"); + } +}