Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
192 commits
Select commit Hold shift + click to select a range
c3635aa
feat(flyway): add V13 migration for product description, active flag …
EdgarEldy Nov 17, 2026
584cab9
feat(entity): add description, active and BigDecimal unitPrice to Pro…
EdgarEldy Nov 17, 2026
2d5d733
feat(dto): add description to ProductRequest and change unitPrice to …
EdgarEldy Nov 17, 2026
bfc73e7
feat(dto): add description, active and BigDecimal unitPrice to Produc…
EdgarEldy Nov 17, 2026
cac3fd1
feat(mapper): ignore active on ProductMapper write methods
EdgarEldy Nov 17, 2026
8aad056
refactor(specification): change priceBetween parameter types to BigDe…
EdgarEldy Nov 17, 2026
ff62e34
refactor(service): change findAll price filter parameters to BigDecimal
EdgarEldy Nov 17, 2026
57855a8
refactor(service): change findAll price filter parameters to BigDecim…
EdgarEldy Nov 17, 2026
9d469e0
refactor(controller): change minPrice/maxPrice @RequestParam types to…
EdgarEldy Nov 17, 2026
ccbc569
test(service): update ProductServiceImplTest for BigDecimal price, de…
EdgarEldy Nov 17, 2026
ebc6f7f
test(controller): update ProductControllerTest for BigDecimal price, …
EdgarEldy Nov 17, 2026
3bfdc6b
test(mapper): update ProductMapperTest for BigDecimal and verify acti…
EdgarEldy Nov 17, 2026
a054e0f
test(repository): update ProductRepositoryTest for BigDecimal unitPrice
EdgarEldy Nov 17, 2026
dd74595
test(service): update ProductServiceCacheTest for BigDecimal price, d…
EdgarEldy Nov 17, 2026
dcb8a46
docs(readme): update feature/products section for e-commerce catalogu…
EdgarEldy Nov 17, 2026
e781c6a
fix(config): migrate DataSeeder unitPrice literals from float to BigD…
EdgarEldy Nov 17, 2026
fe53843
fix(test): update CategoryControllerTest for BigDecimal unitPrice and…
EdgarEldy Nov 17, 2026
a080efd
fix(test): update CategoryMapperTest for BigDecimal unitPrice in Prod…
EdgarEldy Nov 17, 2026
7efc60a
fix(test): update CategoryRepositoryTest for BigDecimal unitPrice in …
EdgarEldy Nov 17, 2026
f6ca4a4
fix(test): import JpaAuditingConfig in ProductRepositoryTest
EdgarEldy Nov 17, 2026
e46611e
fix(config): remove unused resetUserPasswords parameter from DataSeeder
EdgarEldy Nov 17, 2026
f521a04
docs(mapper): fix ProductMapper Javadoc - remove mention of nonexiste…
EdgarEldy Nov 17, 2026
831ee20
test(controller): verify active=false is serialised in ProductControl…
EdgarEldy Nov 17, 2026
4adb9eb
docs(readme): add e-commerce extension to global README sections
EdgarEldy Nov 17, 2026
430b8e3
fix(test): update DataSeederTest after removing resetUserPasswords pa…
EdgarEldy Nov 17, 2026
32d7a83
Merge branch 'feature/products' into feature/orders
EdgarEldy Nov 17, 2026
5afa157
feat(flyway): add V14 migration for multi-product orders, status and …
EdgarEldy Nov 17, 2026
b24e987
feat(entity): add OrderStatus enum with PENDING, CONFIRMED, CANCELLED…
EdgarEldy Nov 17, 2026
ff134cb
feat(entity): add OrderItem entity with product snapshot (name, unit …
EdgarEldy Nov 17, 2026
02eea47
feat(entity): evolve Order for e-commerce - add totalAmount, orderNum…
EdgarEldy Nov 17, 2026
3d97e2b
feat(dto): add OrderItemResponse with product snapshot fields
EdgarEldy Nov 17, 2026
16d6018
refactor(dto): add status, total_amount, order_number and items to Or…
EdgarEldy Nov 17, 2026
d5ea001
refactor(dto): migrate OrderedProductResponse unitPrice and total to …
EdgarEldy Nov 17, 2026
0029240
refactor(dto): migrate CustomerOrdersResponse total to BigDecimal
EdgarEldy Nov 17, 2026
bca8092
refactor(dto): migrate CustomerResponse total to BigDecimal
EdgarEldy Nov 17, 2026
46dd1f8
refactor(repository): migrate OrderProjection to BigDecimal, add stat…
EdgarEldy Nov 17, 2026
cd280b8
feat(mapper): add OrderItemMapper converting OrderItem to OrderItemRe…
EdgarEldy Nov 17, 2026
e5d2ef9
refactor(mapper): migrate CustomerMapper total parameter and default …
EdgarEldy Nov 17, 2026
f3b82e9
refactor(mapper): rewrite OrderMapper for BigDecimal, OrderItem mappi…
EdgarEldy Nov 17, 2026
8a7b255
refactor(repository): update OrderRepository JPQL for new projection …
EdgarEldy Nov 17, 2026
0402078
refactor(event): enrich OrderCreatedEvent with BigDecimal totalAmount…
EdgarEldy Nov 17, 2026
aa81f5e
refactor(service): rewrite OrderServiceImpl with BigDecimal totals, o…
EdgarEldy Nov 17, 2026
224e966
refactor(service): migrate CustomerServiceImpl total computation to B…
EdgarEldy Nov 17, 2026
8a86e47
test(service): rewrite OrderServiceImplTest for BigDecimal, OrderItem…
EdgarEldy Nov 17, 2026
82d5206
test(repository): update OrderRepositoryTest for BigDecimal prices, O…
EdgarEldy Nov 17, 2026
f679878
test(controller): update OrderControllerTest for BigDecimal, new Orde…
EdgarEldy Nov 17, 2026
77c1faa
test(service): update CustomerServiceImplTest for BigDecimal totals a…
EdgarEldy Nov 17, 2026
e795a94
test(controller): update CustomerControllerTest for BigDecimal prices…
EdgarEldy Nov 17, 2026
406c67d
test(mapper): add OrderMapperTest covering entity, projection and gro…
EdgarEldy Nov 17, 2026
7d2a61c
test(mapper): update CustomerMapperTest for BigDecimal prices and total
EdgarEldy Nov 17, 2026
3d59869
fix(event): update OrderCreatedEventListener to use totalAmount and o…
EdgarEldy Nov 17, 2026
a927966
fix(repository): change OrderProjection status field from String to O…
EdgarEldy Nov 17, 2026
f287682
fix(mapper): call status().name() on OrderProjection to serialize enu…
EdgarEldy Nov 17, 2026
9ec181c
test(mapper): update OrderMapperTest to pass OrderStatus enum instead…
EdgarEldy Nov 17, 2026
40c83df
test(service): update CustomerServiceImplTest to pass OrderStatus enu…
EdgarEldy Nov 17, 2026
a80cc10
test(service): update OrderServiceImplTest to pass OrderStatus enum i…
EdgarEldy Nov 17, 2026
82676fa
fix(flyway): add V15 migration to drop NOT NULL on legacy orders.tota…
EdgarEldy Nov 17, 2026
2306930
docs(mapper): fix Javadoc type double -> BigDecimal in CustomerMapper…
EdgarEldy Nov 17, 2026
2a5c9e3
docs(controller): update OrderControllerTest Javadoc to remove stale …
EdgarEldy Nov 17, 2026
87396e1
test(repository): add tests for existsByCustomerId, existsByProductId…
EdgarEldy Nov 17, 2026
bd25468
docs(readme): update feature/orders section for e-commerce order domain
EdgarEldy Nov 17, 2026
460a33d
feat(flyway): add V16 migration for product_images table
EdgarEldy Nov 17, 2026
3fe8bab
feat(entity): add ProductImage entity with audit fields
EdgarEldy Nov 17, 2026
d76fcc5
feat(storage): add StorageProperties and StorageConfig for configurab…
EdgarEldy Nov 17, 2026
759632a
feat(storage): add FileStorageService abstraction
EdgarEldy Nov 17, 2026
03be458
feat(storage): implement LocalFileStorageService with MIME and size v…
EdgarEldy Nov 17, 2026
a3a5200
fix(entity): rename isPrimary to primary in ProductImage to avoid Map…
EdgarEldy Nov 17, 2026
8e30cae
feat(dto): add ProductImageResponse DTO
EdgarEldy Nov 17, 2026
478dcf0
feat(mapper): add ProductImageMapper
EdgarEldy Nov 17, 2026
a855bac
feat(repository): add ProductImageRepository
EdgarEldy Nov 17, 2026
22a9bf3
refactor(mapper): add images mapping to ProductMapper.toResponse and …
EdgarEldy Nov 17, 2026
cba722b
feat(service): add ProductImageService interface
EdgarEldy Nov 17, 2026
fafdd8c
feat(service): add ProductImageServiceImpl
EdgarEldy Nov 17, 2026
1c45416
refactor(service): load images in ProductServiceImpl.findById via Pro…
EdgarEldy Nov 17, 2026
171e742
refactor(controller): add image upload and delete endpoints to Produc…
EdgarEldy Nov 17, 2026
8220c3e
refactor(dto): add images list to ProductResponse and update all call…
EdgarEldy Nov 17, 2026
b57bffa
test(service): add ProductImageServiceImplTest
EdgarEldy Nov 17, 2026
5a984db
test(storage): add LocalFileStorageServiceTest
EdgarEldy Nov 17, 2026
bc86c45
feat(config): add app.storage configuration to application.yml
EdgarEldy Nov 17, 2026
3badcc6
chore: add APP_STORAGE_UPLOAD_DIR to .env.example
EdgarEldy Nov 17, 2026
e87feb0
docs(readme): add feature/product-images section
EdgarEldy Nov 17, 2026
d282ca5
fix(test): remove redundant save(existingPrimary) stub in ProductImag…
EdgarEldy Nov 17, 2026
20fe2d5
fix(service): evict products cache on addImage and deleteImage in Pro…
EdgarEldy Nov 17, 2026
5911138
test(controller): add error case tests for image endpoints in Product…
EdgarEldy Nov 17, 2026
c45fd7d
test(service): add test for addImage when no previous primary exists
EdgarEldy Nov 17, 2026
e7219bf
test(storage): add MIME type mismatch test to LocalFileStorageService…
EdgarEldy Nov 17, 2026
365ee54
test(controller): add GET /orders/{id} 200 happy-path test to OrderCo…
EdgarEldy Nov 17, 2026
25e0615
merge(feature/orders): integrate e-commerce order domain into shoppin…
EdgarEldy Nov 19, 2026
9b24a93
feat(flyway): add V16 migration for carts and cart_items tables
EdgarEldy Nov 19, 2026
5b0a619
feat(entity): add Cart entity
EdgarEldy Nov 19, 2026
1856790
feat(entity): add CartItem entity
EdgarEldy Nov 19, 2026
bdb3612
feat(dto): add CartItemRequest and CartItemUpdateRequest DTOs
EdgarEldy Nov 19, 2026
1b7797f
feat(dto): add CartItemResponse and CartResponse DTOs
EdgarEldy Nov 19, 2026
66da525
feat(mapper): add CartMapper
EdgarEldy Nov 19, 2026
31ace03
feat(repository): add CartRepository
EdgarEldy Nov 19, 2026
145875d
feat(repository): add CartItemRepository
EdgarEldy Nov 19, 2026
f555747
feat(service): add CartService interface
EdgarEldy Nov 19, 2026
5aba208
feat(service): add CartServiceImpl with active product check and quan…
EdgarEldy Nov 19, 2026
2468042
feat(controller): add CartController with 5 cart endpoints
EdgarEldy Nov 19, 2026
bfc0580
refactor(security): protect /api/v1/cart/** with ROLE_USER in Securit…
EdgarEldy Nov 19, 2026
9adb85f
test(service): add CartServiceImplTest
EdgarEldy Nov 19, 2026
9ce61fe
test(controller): add CartControllerTest
EdgarEldy Nov 19, 2026
cc96bb2
test(repository): add CartRepositoryTest
EdgarEldy Nov 19, 2026
b51b709
docs(readme): add shopping cart section
EdgarEldy Nov 19, 2026
2d3ebf5
fix(config): restore @Value parameter on DataSeeder.seedDemoData
EdgarEldy Nov 19, 2026
2605dae
fix(test): update DataSeederTest calls to pass boolean to seedDemoData
EdgarEldy Nov 19, 2026
18ce9ab
fix(test): use @WithMockUser in CartControllerTest to resolve @Authen…
EdgarEldy Nov 19, 2026
7c78841
fix(test): correct save() invocation count in CartServiceImplTest
EdgarEldy Nov 19, 2026
11bf737
fix(test): wrap duplicate save() in assertThatThrownBy in CartReposit…
EdgarEldy Nov 19, 2026
ad95e63
fix(dto): add @JsonProperty("product_id") to CartItemRequest.productId
EdgarEldy Nov 19, 2026
468ff3a
refactor(flyway): rename V16 to V17 for cart tables migration
EdgarEldy Nov 19, 2026
5a83247
refactor(service): remove @Transactional(readOnly=true) from CartServ…
EdgarEldy Nov 19, 2026
ab0b6c9
docs(service): document lazy-cart behavior on CartService.getCart
EdgarEldy Nov 19, 2026
84b12c7
fix(test): narrow exception type in CartRepositoryTest duplicate-save…
EdgarEldy Nov 19, 2026
ffd2ab5
feat(flyway): add V18 migration for user_id column on orders
EdgarEldy Nov 19, 2026
78603bd
feat(entity): add AppUser user field to Order
EdgarEldy Nov 19, 2026
31f08db
feat(dto): add empty CheckoutRequest DTO
EdgarEldy Nov 19, 2026
53997f9
refactor(service): add checkout method to OrderService interface
EdgarEldy Nov 19, 2026
a1939ff
refactor(repository): add deleteAllByCartId to CartItemRepository
EdgarEldy Nov 19, 2026
457e887
feat(service): implement checkout in OrderServiceImpl with atomic car…
EdgarEldy Nov 19, 2026
5b440fb
refactor(controller): replace create endpoint with checkout from auth…
EdgarEldy Nov 19, 2026
76abf32
refactor(security): protect POST /api/v1/orders with ROLE_USER
EdgarEldy Nov 19, 2026
e56a203
test(service): add checkout tests in OrderServiceImplTest
EdgarEldy Nov 19, 2026
6da70fc
test(controller): update OrderControllerTest for checkout endpoint
EdgarEldy Nov 19, 2026
54c3533
docs(readme): add checkout flow section and update order-of-work
EdgarEldy Nov 19, 2026
8949721
refactor(dto): remove unused CheckoutRequest DTO
EdgarEldy Nov 19, 2026
51fc8f6
test(service): add _checkout_05_ for user-not-found path in checkout
EdgarEldy Nov 19, 2026
c6ff406
feat(config): add NotificationProperties for admin email configuration
EdgarEldy Nov 19, 2026
36aacbb
feat(config): register NotificationProperties in AsyncConfig
EdgarEldy Nov 19, 2026
7395675
feat(config): add app.notifications.admin-email to application.yml
EdgarEldy Nov 19, 2026
e47c1ea
feat(config): add APP_NOTIFICATION_ADMIN_EMAIL to .env.example
EdgarEldy Nov 19, 2026
cedce0c
feat(service): add OrderEmailService interface for order email notifi…
EdgarEldy Nov 19, 2026
4e0caa0
feat(service): implement OrderEmailServiceImpl with SMTP error handling
EdgarEldy Nov 19, 2026
3d8d4b8
refactor(repository): add findByIdWithItemsAndUser query to OrderRepo…
EdgarEldy Nov 19, 2026
91718da
refactor(event): extend OrderCreatedEventListener to send emails afte…
EdgarEldy Nov 19, 2026
a667eff
test(service): add OrderEmailServiceImplTest
EdgarEldy Nov 19, 2026
58efd97
test(event): add OrderCreatedEventListenerTest
EdgarEldy Nov 19, 2026
1bbbe08
docs(readme): add email notifications section and update order-of-work
EdgarEldy Nov 19, 2026
c2ee642
fix(test): move adminEmail stub to tests that consume it in OrderEmai…
EdgarEldy Nov 19, 2026
b552d68
fix(test): replace dead Java assert with AssertJ in OrderEmailService…
EdgarEldy Nov 19, 2026
a043580
test(event): add _03_ for order-not-found path in OrderCreatedEventLi…
EdgarEldy Nov 19, 2026
dd03e15
feat(email): add ORDER_CONFIRMATION and ORDER_ADMIN_NOTIFICATION to E…
EdgarEldy Nov 19, 2026
e5fe692
feat(template): add order_confirmation.html Thymeleaf email template
EdgarEldy Nov 19, 2026
5ac0c1c
feat(template): add order_admin_notification.html Thymeleaf email tem…
EdgarEldy Nov 19, 2026
5fc3a0a
refactor(service): rewrite OrderEmailServiceImpl with Thymeleaf HTML …
EdgarEldy Nov 19, 2026
cca59f2
test(service): update OrderEmailServiceImplTest for Thymeleaf HTML im…
EdgarEldy Nov 19, 2026
c1a7a7c
feat(dto): add OrderStatusUpdateRequest for PATCH /orders/{id}/status
EdgarEldy Nov 20, 2026
ea3130a
refactor(repository): add findByUserId and findByIdAndUserId to Order…
EdgarEldy Nov 20, 2026
2bfd688
refactor(service): update OrderService interface with role-aware methods
EdgarEldy Nov 20, 2026
91c100a
refactor(service): implement authorization logic in OrderServiceImpl
EdgarEldy Nov 20, 2026
bb08f44
feat(controller): rewrite OrderController with role-based access and …
EdgarEldy Nov 20, 2026
1d599ec
refactor(security): configure order and cart authorization rules in S…
EdgarEldy Nov 20, 2026
b09ff2b
test(controller): update OrderControllerTest for role-aware OrderCont…
EdgarEldy Nov 20, 2026
64e00e8
test(integration): add OrderAuthorizationTest with two users and admin
EdgarEldy Nov 20, 2026
a8475cd
docs(readme): add authorization section for feature/order-authorization
EdgarEldy Nov 20, 2026
d5cd4e7
feat(order): add findAllByCustomerId to OrderService interface
EdgarEldy Nov 20, 2026
652ec26
feat(order): implement findAllByCustomerId in OrderServiceImpl
EdgarEldy Nov 20, 2026
3f4bffd
fix(controller): update CustomerController to use findAllByCustomerId
EdgarEldy Nov 20, 2026
af2f6ba
test(order): update OrderServiceImplTest for new findAll and findById…
EdgarEldy Nov 20, 2026
85dc97f
test(customer): update CustomerControllerTest for findAllByCustomerId
EdgarEldy Nov 20, 2026
2ea33d3
test(order): fix totalElements JSONPath assertion in OrderControllerTest
EdgarEldy Nov 20, 2026
2e9ba81
test(order): fix totalElements JSONPath assertions in OrderAuthorizat…
EdgarEldy Nov 20, 2026
6d13ca5
fix(repository): use LEFT JOIN FETCH in findByIdWithDetails
EdgarEldy Nov 20, 2026
5119925
test(order): add missing unit tests for findAll, findById user path, …
EdgarEldy Nov 20, 2026
3b74d6c
merge(feature/product-images): integrate product image management int…
EdgarEldy Nov 20, 2026
38182a2
feat(docker): add image storage volume and notification env vars to d…
EdgarEldy Nov 20, 2026
8af9bc3
test(integration): add EcommerceIntegrationTest end-to-end scenario
EdgarEldy Nov 20, 2026
7d67cfe
fix(mapper): add missing images arg in OrderMapper.toResponse(OrderPr…
EdgarEldy Nov 20, 2026
a8e7212
fix(test): add missing images arg in CustomerControllerTest ProductRe…
EdgarEldy Nov 20, 2026
8086f84
fix(test): add missing images arg in OrderControllerTest ProductResponse
EdgarEldy Nov 20, 2026
592ed36
fix(test): add missing images arg in OrderServiceImplTest ProductResp…
EdgarEldy Nov 20, 2026
2e2a17b
fix(order): clear cart items via collection instead of direct reposit…
EdgarEldy Nov 20, 2026
5d4c80b
test(order): update checkout tests after removing CartItemRepository …
EdgarEldy Nov 20, 2026
0fe7526
test(integration): strengthen checkout assertions in EcommerceIntegra…
EdgarEldy Nov 20, 2026
f36d4c7
docs(readme): add feature/integration section and update order of work
EdgarEldy Nov 20, 2026
65f2268
docs(readme): complete global sections with full data model and proje…
EdgarEldy Nov 20, 2026
7f24e21
merge(feature/core-architecture): propagate full data model and proje…
EdgarEldy Nov 20, 2026
0e3deb4
Merge branch 'feature/products' into feature/customers
EdgarEldy Nov 20, 2026
ff5c8e8
Merge branch 'feature/customers' into feature/orders
EdgarEldy Nov 20, 2026
8b97ea4
merge(feature/orders): propagate data model and project structure to …
EdgarEldy Nov 20, 2026
77221f0
Merge branch 'feature/auth' into feature/roles-permissions
EdgarEldy Nov 20, 2026
8c3e13f
Merge branch 'feature/roles-permissions' into feature/token-management
EdgarEldy Nov 20, 2026
c5de971
merge(feature/token-management): propagate data model and project str…
EdgarEldy Nov 20, 2026
7cdf014
merge(feature/user-management): propagate data model and project stru…
EdgarEldy Nov 20, 2026
4a5d8fc
merge(feature/shopping-cart): propagate data model and project struct…
EdgarEldy Nov 20, 2026
484daf8
merge(feature/order-checkout): propagate data model and project struc…
EdgarEldy Nov 20, 2026
bf5637f
Merge branch 'feature/order-notifications' into feature/order-authori…
EdgarEldy Nov 20, 2026
851371a
merge(feature/order-authorization): propagate data model and project …
EdgarEldy Nov 20, 2026
960727d
Merge branch 'feature/integration' into feature/docs
EdgarEldy Nov 20, 2026
4ff87e4
docs: add e-commerce branch guides (product-images, shopping-cart, ch…
EdgarEldy Nov 20, 2026
778e219
docs(insomnia): add e-commerce endpoints (product images, cart, check…
EdgarEldy Nov 20, 2026
4d3c9af
Merge branch 'feature/docs' into develop
EdgarEldy Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
775 changes: 740 additions & 35 deletions README.md

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
107 changes: 107 additions & 0 deletions docs/en/15-product-images-branch.md
Original file line number Diff line number Diff line change
@@ -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<ProductImageResponse>`). 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 |
104 changes: 104 additions & 0 deletions docs/en/16-shopping-cart-branch.md
Original file line number Diff line number Diff line change
@@ -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<CartItem> 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 |
78 changes: 78 additions & 0 deletions docs/en/17-order-checkout-branch.md
Original file line number Diff line number Diff line change
@@ -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 |
86 changes: 86 additions & 0 deletions docs/en/18-order-notifications-branch.md
Original file line number Diff line number Diff line change
@@ -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 |
Loading
Loading