Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - Manoj4689/CommerceHub: A Cloud-Native E-Commerce Platform · GitHub
Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Manoj4689/CommerceHub: A Cloud-Native E-Commerce Platform · GitHub
Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Manoj4689/CommerceHub: A Cloud-Native E-Commerce Platform · GitHub
Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - Manoj4689/CommerceHub: A Cloud-Native E-Commerce Platform · GitHub
Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Manoj4689/CommerceHub: A Cloud-Native E-Commerce Platform · GitHub
Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Manoj4689/CommerceHub: A Cloud-Native E-Commerce Platform · GitHub
Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - Manoj4689/CommerceHub: A Cloud-Native E-Commerce Platform · GitHub
Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

CommerceHub

A full-stack E-commerce Order Management System built with Spring Boot and React. It covers a multi-category catalog, server-side cart and checkout, multi-warehouse inventory that cannot be oversold under concurrency, atomic order placement (cart + inventory + payment), a non-blocking async fulfillment/notification/audit pipeline, an order lifecycle state machine, discounts, taxes, returns and refunds, and role-based access control for three roles.

LayerStackDocs
BackendSpring Boot 3.3.9, Java 23, JPA, JWTecom-backend/README.md
FrontendReact 18, Vite, Bootstrapecom-frontend/README.md
AI / contributorsConventions & pitfallsAgent.md

Table of contents


Architecture overview

Backend (ecom-backend) — Spring Boot 3.3.9, Java 23, Spring Data JPA, Spring Security + JWT, organized package-by-feature under com.manoj.ecom_proj:

ModuleResponsibility
common/errorException hierarchy + global @RestControllerAdvice → consistent ApiError
common/auditAuditable base, AuditLog + admin read endpoint
securityJWT util/filter, SecurityUser principal (carries userId), JSON 401/403 handlers, ownership provider
auth / userRegistration, login, User/Address/Role, BCrypt
catalogProduct + image CRUD, Category
inventoryWarehouse, Stock (per product+warehouse), Reservation, atomic reservation
cartServer-backed cart per user
discountDiscount codes (percentage/fixed), validation, preview
orderCustomerOrder/OrderItem, pricing, tax, atomic placement, state machine, history, query
paymentPayment, PaymentGateway interface + MockPaymentGateway
fulfillmentWarehouse-staff status transitions + queue
returnsReturn requests, refunds, restock-on-approval
notificationIn-app/log notifications

Frontend (ecom-frontend) — React 18 + Vite + Bootstrap. Catalog/cart/auth UI extended with customer registration, real checkout, order history + tracking timeline, return requests, an admin console (warehouses / inventory / discounts / return approval), and a warehouse-staff fulfillment board. Role-gated routes via ProtectedRoute.


Key design decisions

1. Inventory cannot be oversold (concurrency safety)

Stock holds onHandQuantity and reservedQuantity per (product, warehouse) (unique constraint); available = onHand − reserved is derived, never stored. Reservation is a single atomic conditional UPDATE:

UPDATE stock SET reserved_quantity = reserved_quantity + :qty
WHERE id = :id AND (on_hand_quantity - reserved_quantity) >= :qty

The database evaluates the availability guard and the increment in one statement under its own row lock, so it is immune to lost-update and check-then-act races. Because this relies on single-statement atomicity (not SELECT … FOR UPDATE), the guarantee holds identically on H2 and Postgres — the concurrency test runs on the default H2. Multi-warehouse allocation is a greedy loop of these atomic reserves; correctness comes entirely from the atomic statement, never from the (stale-tolerant) candidate ordering. A pessimistic @Lock finder exists but is reserved for admin manual stock adjustments, never the checkout hot path.

Proof:InventoryConcurrencyTest fires 20 concurrent buyers at the last unit and asserts exactly one wins, 19 get 409 INSUFFICIENT_STOCK, and stock never goes negative.

2. Atomic order placement

OrderService.placeOrder runs the whole flow — price → reserve → persist order → charge → confirm — in one @Transactional (READ_COMMITTED). If stock is insufficient or payment is declined, everything rolls back: no order, no leaked reservation. Because reservation is single-statement atomic, no row lock is held across the (mock) payment call — avoiding the classic pessimistic-locking throughput anti-pattern. Line prices and product names are snapshotted onto the order so later catalog edits never mutate historical orders.

3. Non-blocking downstream pipeline

On confirmation, OrderService publishes an OrderConfirmedEvent carrying an immutable snapshot. Three independent listeners — fulfillment routing, notification, audit — each run with @Async("orderPipelineExecutor") + @TransactionalEventListener(phase = AFTER_COMMIT). AFTER_COMMIT guarantees listeners never act on rolled-back state; @Async keeps them off the checkout response thread. DB-writing listeners use REQUIRES_NEW. One listener failing doesn't affect the others. The published-event seam is exactly where a real message queue/outbox would later slot in.

4. Order state machine

OrderStatus centralizes legal transitions (PLACED → CONFIRMED → PACKED → SHIPPED → DELIVERED → RETURNED, plus CANCELLED). OrderStatusService.transition validates legality (else 409 INVALID_STATE_TRANSITION), applies side effects (SHIP commits reservations → on-hand decremented; pre-ship CANCEL releases reservations + refunds), and records OrderStatusHistory. The order's @Version guards against concurrent double-transitions.

5. Returns & refunds

Two reversal paths are kept distinct: cancel before shipment releases reservations (on-hand untouched); return after delivery restocks on-hand, gated on admin approval (returned goods may be damaged). Approval transitions the order to RETURNED, restocks the committed units, refunds the payment (full or partial supported via refundedAmount), and records a Refund.

6. RBAC

Real User entity with BCrypt passwords replaces the previous hardcoded admin. JWT carries uid + role; the filter reconstructs a SecurityUser principal (stateless, no per-request DB hit) that carries the user id so ownership checks never trust client-supplied ids (findByIdAndUserId → 404, not 403, to avoid leaking existence). Coarse URL rules in SecurityConfig plus @PreAuthorize for fine-grained/ownership checks.


Roles & seeded accounts

DataLoader seeds three accounts on first run (and 6 products across 2 warehouses):

UsernamePasswordRoleCan do
adminadminADMINeverything: catalog, warehouses, inventory, discounts, all orders, approve returns, audit log
warehousewarehouseWAREHOUSE_STAFFview inventory, advance fulfillment status (pack/ship/deliver)
customercustomerCUSTOMERbrowse, cart, checkout, track own orders, request returns

Register new customers at POST /api/auth/register (always CUSTOMER).


Getting started

Prerequisites

  • JDK 23 (the pom.xml targets Java 23)
  • Node.js 18+
  • Maven (wrapper included in ecom-backend)

1. Start the backend

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23 # Maven needs a real JDK 23, not just a jenv shim
./mvnw spring-boot:run

Runs on http://localhost:8080 with an in-memory H2 database (zero setup; resets on restart).

Optional profiles:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=postgres
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=redis

2. Start the frontend

cd ecom-frontend
cp .env.example .env # optional — defaults to http://localhost:8080/api
npm install
npm run dev # http://localhost:5173

Log in with a demo account from the table above.

Running all three roles at once

The JWT is stored in localStorage, which is per-origin — one port = one logged-in user. To drive admin, customer, and warehouse staff simultaneously, run a dev server per role:

cd ecom-frontend
npm run dev:customer # http://localhost:5173
npm run dev:admin # http://localhost:5174
npm run dev:warehouse # http://localhost:5175

All localhost ports are allow-listed in the backend CORS config (app.cors.allowed-origin-patterns in application.properties).

Quick end-to-end (curl)

TOKEN=$(curl -s -X POST localhost:8080/api/auth/login -H 'Content-Type: application/json' \ -d '{"username":"customer","password":"customer"}'| sed -E 's/.*"token":"([^"]+)".*/\1/')
curl -s -X POST localhost:8080/api/cart/items -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"productId":1,"quantity":1}'
curl -s -X POST localhost:8080/api/orders/checkout -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"paymentMethod":"card"}'

API surface

All errors return a consistent ApiError body: { timestamp, status, errorCode, message, path, fieldErrors? }.

AreaEndpointRole
AuthPOST /api/auth/register, POST /api/auth/loginpublic
GET /api/auth/meauthenticated
CatalogGET /api/products, /product/{id}, /product/{id}/image, /products/search, /categoriespublic
POST/PUT/DELETE /api/product, /api/categories/**ADMIN
InventoryGET /api/inventory/products/{id}/availabilitypublic
PUT /api/inventory/warehouses/{wid}/products/{pid}, GET /api/inventory/products/{pid}ADMIN, WAREHOUSE_STAFF
GET/POST/PUT/DELETE /api/warehouses/**ADMIN
CartGET /api/cart, POST /api/cart/items, PUT/DELETE /api/cart/items/{id}, DELETE /api/cartCUSTOMER, ADMIN
OrdersPOST /api/orders/checkout, GET /api/orders, GET /api/orders/{id}, GET /api/orders/{id}/trackingCUSTOMER (own) / ADMIN (all)
FulfillmentGET /api/fulfillment/orders, PUT /api/fulfillment/orders/{id}/statusWAREHOUSE_STAFF, ADMIN
ReturnsPOST /api/returns, GET /api/returns, GET /api/returns/{id}CUSTOMER (own) / ADMIN
PUT /api/returns/{id}/approveADMIN
DiscountsGET/POST/PUT/DELETE /api/discounts/**ADMIN
POST /api/discounts/previewCUSTOMER, ADMIN
NotificationsGET /api/notificationsauthenticated (own)
AuditGET /api/admin/auditADMIN

Testing

cd ecom-backend
export JAVA_HOME=/path/to/jdk-23
./mvnw test# unit, integration, and concurrency tests
./mvnw verify # also produces a JaCoCo coverage report (target/site/jacoco)
cd ecom-frontend
npm run lint
npm run build

Coverage includes:

  • Unit (Mockito): inventory reservation, order placement + payment-decline rollback, discount math, pricing/tax allocation, state-machine guards, return/refund logic, registration, global error mapping.
  • Integration (@SpringBootTest + MockMvc): register → login → cart → checkout → track → pack/ship/deliver → return → refund; authorization matrix; empty-cart rejection.
  • Concurrency:InventoryConcurrencyTest proves no overselling under 20 concurrent buyers for the last unit.

Assumptions & scope

  • Payment is mocked (MockPaymentGateway) — approves positive charges and can be toggled to decline. The PaymentGateway interface is the swap-in seam.
  • H2 in-memory by default for zero-setup runs; data resets on restart. Postgres/Redis remain optional profiles.
  • Restock-on-approval: returned goods are added back to sellable stock only when an admin approves the return.
  • Order-level returns/refunds: the API exposes full-order returns; Payment.refundedAmount supports partial refunds in the data model.
  • Single role per user / JWT — sufficient for the three required roles.
  • Product lives in catalog/ with int id (frontend depends on /api/product/**); newer entities use Long ids. Product.stockQuantity is a display hint — Stock rows are the authoritative inventory.
  • Schema via ddl-auto (no Flyway); warehouses/stock/users are seeded by DataLoader.
  • Async pipeline is in-process (Spring events + @Async); a broker/outbox would be the next step for at-least-once delivery at scale.

About

A Cloud-Native E-Commerce Platform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages