An open API service indexing awesome lists of open source software.

https://github.com/dedslash/buy-02

E-commerce with cart & order management โ€” 5 microservices, Spring Boot, Kafka, Docker
https://github.com/dedslash/buy-02

angular docker java kafka microservices mongodb springboot

Last synced: about 2 months ago
JSON representation

E-commerce with cart & order management โ€” 5 microservices, Spring Boot, Kafka, Docker

Awesome Lists containing this project

README

          

# Buy-02 - E-commerce Microservices Platform

![Database Design](Database-Design.png)

## ๐Ÿ“‹ Table of Contents
- [Overview](#overview)
- [Architecture](#architecture)
- [Tech Stack](#tech-stack)
- [Prerequisites](#prerequisites)
- [Getting Started](#getting-started)
- [Configuration](#configuration)
- [API Documentation](#api-documentation)
- [Security](#security)
- [Tests](#tests)
- [Troubleshooting](#troubleshooting)
- [Environment Variables](#environment-variables)
- [Frontend (Angular)](#frontend-angular)

## ๐ŸŽฏ Overview

Buy-02 is a full-featured e-commerce platform built with a microservices architecture using Spring Boot and Angular. The platform supports:

- **User Registration**: Clients and Sellers with avatar upload for sellers (max 2MB)
- **Secure Authentication**: JWT with role management and internal service tokens
- **Product Management**: CRUD restricted to authenticated sellers
- **Cart Management**: Add/update/remove items with real-time stock validation
- **Order Management**: Create, track, cancel, and reorder with client/seller workflow
- **Media Management**: Image upload with validation (JPEG, PNG, WebP - max 2MB)
- **Inter-service Communication**: Apache Kafka for event-driven messaging
- **User Interface**: Responsive Angular dashboard

## ๐Ÿ—๏ธ Architecture

### Microservices & Ports
```
๐Ÿ“ฆ Buy-02 Architecture
โ”œโ”€โ”€ ๐Ÿ” Discovery Server (Eureka) - Port 8761
โ”œโ”€โ”€ ๐Ÿšช Gateway Service (HTTPS) - Port 8443
โ”œโ”€โ”€ ๐Ÿ‘ฅ User Service - Port 8081
โ”œโ”€โ”€ ๐Ÿ“ฆ Product Service - Port 8082
โ”œโ”€โ”€ ๐Ÿ–ผ๏ธ Media Service - Port 8083
โ”œโ”€โ”€ ๐Ÿ›’ Cart Service - Port 8084
โ”œโ”€โ”€ ๐Ÿ“‹ Order Service - Port 8085
โ”œโ”€โ”€ ๐ŸŒ Frontend (Angular) - Port 4200
โ”œโ”€โ”€ ๐Ÿ“Š MongoDB User DB - Port 27017 (user_db)
โ”œโ”€โ”€ ๐Ÿ“Š MongoDB Product DB - Port 27018 (product_db)
โ”œโ”€โ”€ ๐Ÿ“Š MongoDB Media DB - Port 27019 (media_db)
โ”œโ”€โ”€ ๐Ÿ“Š MongoDB Cart DB - Port 27020 (cart_db)
โ”œโ”€โ”€ ๐Ÿ“Š MongoDB Order DB - Port 27021 (order_db)
โ”œโ”€โ”€ ๐Ÿ”„ Kafka Broker - Port 9092
โ””โ”€โ”€ ๐Ÿ˜ Zookeeper - Port 2181
```

### Communication
- **Service Discovery**: Netflix Eureka (Spring Cloud 2025.0.0)
- **API Gateway**: Spring Cloud Gateway with SSL/HTTPS
- **Message Broker**: Apache Kafka 7.5.3 for inter-service events
- **Databases**: Isolated MongoDB instance per service
- **Authentication**: JWT + internal tokens for service-to-service communication

## ๐Ÿ› ๏ธ Tech Stack

### Backend
- **Spring Boot 3.5.3** (Java 17)
- **Spring Cloud 2025.0.0** (Eureka Client, Gateway)
- **Spring Security** + JWT (jjwt 0.11.5)
- **Spring Data MongoDB**
- **Apache Kafka** with Zookeeper
- **Springdoc OpenAPI 2.7.0** (Swagger)
- **Bucket4j 7.6.0** (Rate Limiting)
- **Spring Validation**
- **Docker & Docker Compose**

### Infrastructure
- **MongoDB** (latest)
- **Confluent Kafka & Zookeeper**
- **SSL/HTTPS** with PKCS12 certificates

## ๐Ÿ“‹ Prerequisites

- **Docker** and **Docker Compose**
- **Java 17** (for local development)
- **Maven 3.6+** (to build services)
- **mkcert** (for SSL certificates in development)
- **Node.js** (LTS version, e.g., 18.x or 20.x)
- **npm** (comes with Node.js)
- **Angular CLI** (`npm install -g @angular/cli`)

## ๐Ÿš€ Getting Started

**Clone the repository**
```bash
git clone https://github.com/DedSlash/buy-02.git
cd buy-02
```

### Option 1: Docker via script (Quick Start)

1. **Make scripts executable**
```bash
chmod +x commit.sh run_microservice.sh start-project.sh stop-project.sh toggle-config.sh run-all-tests.sh
```

2. **Start the project**
```bash
./start-project.sh
```

3. **Stop the project**
```bash
./stop-project.sh
```

### Option 2: Docker manual (Recommended)

1. **Build and start all services**
```bash
docker-compose up --build
```

2. **Verify services are running**
```bash
# Eureka Dashboard
http://localhost:8761

# Gateway (HTTPS only)
https://localhost:8443

# Centralized API Documentation
https://localhost:8443/swagger-ui.html
```

3. **Start the Angular frontend**
```bash
cd frontend
npm install
npm start
```

### Option 3: Manual start (Development)

```bash
./run_microservice.sh
```

## โš™๏ธ Configuration

### SSL/HTTPS Setup

The project enforces **HTTPS** via the Gateway Service using PKCS12 certificates.

#### Generating a certificate for local development

1. **Install mkcert**
```bash
# Ubuntu/Debian
sudo apt install libnss3-tools mkcert

# macOS
brew install mkcert
```

2. **Create and install the certificate**
```bash
mkcert localhost

openssl pkcs12 -export \
-in localhost.pem \
-inkey localhost-key.pem \
-out keystore.p12 \
-name springboot \
-password pass:changeit

mv keystore.p12 backend/api/gateway-service/src/main/resources/
```

### MongoDB Databases

Each service has its own isolated database:

| Service | Database | Port | Container |
|---------|----------|------|-----------|
| User Service | `user_db` | 27017 | `user-mongodb` |
| Product Service | `product_db` | 27018 | `product-mongodb` |
| Media Service | `media_db` | 27019 | `media-mongodb` |
| Cart Service | `cart_db` | 27020 | `cart-mongodb` |
| Order Service | `order_db` | 27021 | `order-mongodb` |

### Kafka Configuration

- **Bootstrap Servers**: `kafka:29092` (internal) / `localhost:9092` (external)
- **Topics**: Auto-creation enabled
- **Consumer Groups**:
- `user-service-group`
- `product-service-group`
- `media-service-group`
- `cart-service-group`
- `order-service-group`

## ๐Ÿ“š API Documentation

### Centralized Swagger UI
- **Gateway Swagger**: https://localhost:8443/swagger-ui.html
- Aggregates all services: User, Product, Media, Cart, Order

### Per-service Swagger (development)
| Service | URL |
|---------|-----|
| User | http://localhost:8081/swagger-ui.html |
| Product | http://localhost:8082/swagger-ui.html |
| Media | http://localhost:8083/swagger-ui.html |
| Cart | http://localhost:8084/swagger-ui.html |
| Order | http://localhost:8085/swagger-ui.html |

### Frontend Documentation (hot-reload)
```bash
cd frontend
npm install
npm run serve-docs
```
Available at: [http://localhost:4212/](http://localhost:4212/)

### Gateway Routes

| Route | Target Service | Description |
|-------|---------------|-------------|
| `/api/auth/**` | user-service | Authentication (with rate limiting) |
| `/api/users/**` | user-service | User management |
| `/api/admin/**` | user-service | Administration |
| `/avatars/**` | user-service | Avatar images |
| `/api/products/**` | product-service | Product CRUD |
| `/api/media/**` | media-service | Media upload/management |
| `/productsImages/**` | media-service | Product images |
| `/api/cart/**` | cart-service | Cart management |
| `/api/orders/**` | order-service | Order management (CLIENT) |
| `/api/seller/orders/**` | order-service | Order management (SELLER) |

### Main Endpoints

#### User Service (Port 8081)
```bash
POST /api/auth/register # Register (CLIENT/SELLER)
POST /api/auth/login # Login (returns JWT)
GET /api/users/me # Get current user profile
PUT /api/users/me # Update profile
POST /api/users/avatar # Upload avatar (SELLER)
GET /avatars/{filename} # Retrieve avatar
```

#### Product Service (Port 8082)
```bash
GET /api/products # Public product list
POST /api/products # Create product (SELLER only)
GET /api/products/{id} # Product detail
PUT /api/products/{id} # Update product (owner only)
DELETE /api/products/{id} # Delete product (owner only)
```

#### Media Service (Port 8083)
```bash
POST /api/media/upload # Upload product image (max 2MB, JPEG/PNG/WebP)
GET /api/media/{id} # Image metadata
GET /productsImages/{filename} # Retrieve image
DELETE /api/media/{id} # Delete image (owner only)
```

#### Cart Service (Port 8084)
```bash
GET /api/cart/mycart # View cart (CLIENT)
POST /api/cart/add/item/{productId} # Add item to cart
DELETE /api/cart/remove/{itemId} # Remove item
PUT /api/cart/update/{itemId} # Update quantity
DELETE /api/cart/clear # Empty cart
```

#### Order Service (Port 8085)

**CLIENT routes** (`/api/orders`)
```bash
POST /api/orders/create # Create order from cart
POST /api/orders/reorder/{oldOrderId} # Reorder from previous order
GET /api/orders/myorders # View all orders
PUT /api/orders/cancel/{orderId} # Cancel order (if pending)
DELETE /api/orders/remove/{orderId} # Remove from history
GET /api/orders/total-spent # View total spent
```

**SELLER routes** (`/api/seller/orders`)
```bash
PUT /api/seller/orders/confirm-item/{itemId} # Confirm/cancel item
GET /api/seller/orders/my-sales # View all sales
PUT /api/seller/orders/{itemId}/delivery-status # Update delivery status
GET /api/seller/orders/total-earned # View total earned
```

## ๐Ÿ›ก๏ธ Security

- **Mandatory HTTPS**: All communication via SSL/TLS
- **JWT Authentication**: Tokens with 1-hour expiration
- **Role-Based Access Control**: CLIENT vs SELLER
- **Internal Tokens**: Secure service-to-service communication
- **Password Hashing**: BCrypt via Spring Security
- **File Validation**: JPEG/PNG/WebP only, max 2MB per file, 10MB per request
- **Rate Limiting**: Applied on `/api/auth/**`
- **CORS Configuration**: Secured headers
- **Real-time Stock Validation**: Before cart addition and order creation

> โš ๏ธ Never commit real secrets. Use environment variables or a secrets manager (e.g. HashiCorp Vault) in production. See `.env.example` for the expected variables.

## ๐Ÿงช Tests

```bash
# Run tests per service
cd backend/api/user && ./mvnw test
cd backend/api/product && ./mvnw test
cd backend/api/media && ./mvnw test
cd backend/api/cart && ./mvnw test
cd backend/api/order && ./mvnw test

# Or run all tests at once
./run-all-tests.sh
```

## ๐Ÿ› Troubleshooting

### Services not starting
```bash
# Check ports in use
netstat -tulpn | grep -E ":(8761|8443|8081|8082|8083|8084|8085)"

# Full Docker cleanup
docker-compose down -v
docker system prune -af
docker volume prune -f
```

### MongoDB issues
```bash
docker logs user-mongodb
docker logs cart-mongodb

# Direct DB access
docker exec -it user-mongodb mongosh -u root -p $MONGO_ROOT_PASSWORD
```

### SSL/HTTPS errors
```bash
# Check certificate
keytool -list -keystore backend/api/gateway-service/src/main/resources/keystore.p12 -storepass changeit
```

### Kafka not working
```bash
docker-compose restart zookeeper kafka
docker exec -it kafka kafka-topics --bootstrap-server localhost:9092 --list
```

### Useful logs
```bash
docker-compose logs -f # All services
docker-compose logs -f user-service # Specific service
docker-compose logs -f --tail=100 gateway-service
```

## ๐Ÿ”ง Environment Variables

Create a `.env` file at the root of the project based on `.env.example`:

```env
# JWT
JWT_SECRET=your-very-long-and-secure-jwt-secret-minimum-256-bits

# MongoDB
MONGO_ROOT_USERNAME=root
MONGO_ROOT_PASSWORD=your-secure-password

# Kafka
KAFKA_BOOTSTRAP_SERVERS=kafka:29092

# SSL
SSL_KEYSTORE_PASSWORD=your-keystore-password

# Internal service token
INTERNAL_TOKEN=your-secure-internal-token

# Eureka
EUREKA_DEFAULT_ZONE=http://discovery-server:8761/eureka
```

## ๐Ÿ“Š Service Status

| Service | Port | Health Check | Swagger |
|---------|------|--------------|---------|
| Discovery Server | 8761 | http://localhost:8761 | โ€” |
| Gateway Service | 8443 | https://localhost:8443/actuator/health | https://localhost:8443/swagger-ui.html |
| User Service | 8081 | http://localhost:8081/actuator/health | http://localhost:8081/swagger-ui.html |
| Product Service | 8082 | http://localhost:8082/actuator/health | http://localhost:8082/swagger-ui.html |
| Media Service | 8083 | http://localhost:8083/actuator/health | http://localhost:8083/swagger-ui.html |
| Cart Service | 8084 | http://localhost:8084/actuator/health | http://localhost:8084/swagger-ui.html |
| Order Service | 8085 | http://localhost:8085/actuator/health | http://localhost:8085/swagger-ui.html |
| Frontend | 4200 | http://localhost:4200 | โ€” |

## ๐Ÿ“ Volume Structure

```
./uploads/
โ”œโ”€โ”€ avatars/ # User Service - User avatars
โ””โ”€โ”€ productsImages/ # Media Service - Product images
```

## ๐Ÿ”„ Order Workflow

### Order Lifecycle

#### 1๏ธโƒฃ Order Creation (CLIENT)
- Client creates order from cart
- Automatic stock validation
- Unique order number generated (`ORD-YYYYMMDD-XXXXXX`)
- All items initially set to `pending`
- Cart automatically cleared after creation

#### 2๏ธโƒฃ Item Confirmation (SELLER)
- Each seller sees their own items
- Seller can **confirm** or **cancel** each item individually
- **Confirm**: stock is automatically decremented
- **Cancel**: item marked as cancelled, stock unaffected

#### 3๏ธโƒฃ Delivery Management (SELLER)
- After confirmation, seller manages delivery status:
- `non_livre`: Awaiting delivery
- `livre`: Delivered to client
- `annule`: Delivery cancelled (stock restocked)

#### 4๏ธโƒฃ Order Cancellation (CLIENT)
- Client can cancel if **all** items are still `pending`
- Once any item is confirmed, full cancellation is blocked
- Client can only remove completed orders (delivered or cancelled) from history

#### 5๏ธโƒฃ Reorder (CLIENT)
- Client can reorder from a previous order
- System checks current product availability
- Available items added to cart with stock-adjusted quantities

### Order Statuses

| Status | Description |
|--------|-------------|
| `pending` | Awaiting seller confirmation |
| `confirmed` | All items confirmed by sellers |
| `canceled` | Order cancelled (all items cancelled) |
| `removed` | Removed from client history |

### Delivery Statuses

| Status | Description |
|--------|-------------|
| `non_livre` | Awaiting delivery |
| `livre` | Delivered to client |
| `annule` | Delivery cancelled |

### Stock Management

| Action | Stock Effect |
|--------|-------------|
| Add to cart | Validation only, no reservation |
| Create order | Validation only, no reservation |
| Seller confirms | Stock decremented automatically |
| Delivery cancelled | Stock restocked automatically |

## ๐ŸŒ Frontend (Angular)

### Key Technologies
- **Angular** (latest stable)
- **TypeScript**
- **RxJS** for async data streams
- **Angular Material** (MatButtonToggleModule, MatIconModule, MatDialogModule)
- **HTML5 & SCSS**

### Features
- Secure auth with role-based access (Client / Seller)
- Profile management with avatar upload
- Product list with filtering, search, and sorting
- Product detail view with images and seller info
- Seller product management (add, edit, delete + media)
- Real-time cart with stock validation
- Full order management (create, track, cancel, reorder)
- Seller dashboard (confirm items, manage delivery)
- Toast notification system

### Frontend Structure
```
frontend/
โ”œโ”€โ”€ src/
โ”‚ โ”œโ”€โ”€ app/
โ”‚ โ”‚ โ”œโ”€โ”€ auth/ # Sign-in, sign-up components
โ”‚ โ”‚ โ”œโ”€โ”€ cart/ # Cart management
โ”‚ โ”‚ โ”œโ”€โ”€ error/ # Toast error component
โ”‚ โ”‚ โ”œโ”€โ”€ models/ # TypeScript interfaces (User, Product, Cart, Order...)
โ”‚ โ”‚ โ”œโ”€โ”€ navbar/ # Navigation component
โ”‚ โ”‚ โ”œโ”€โ”€ orders/ # Order management
โ”‚ โ”‚ โ”œโ”€โ”€ products/ # Product list, card, circular-image
โ”‚ โ”‚ โ”œโ”€โ”€ profile/ # Profile & update form
โ”‚ โ”‚ โ”œโ”€โ”€ seller/ # Seller dashboard, product & order management
โ”‚ โ”‚ โ”œโ”€โ”€ services/ # API services (auth, user, product, cart, order...)
โ”‚ โ”‚ โ””โ”€โ”€ utils/ # Utility functions
โ”‚ โ”œโ”€โ”€ assets/ # Static files
โ”‚ โ”œโ”€โ”€ environments/ # Dev & prod config
โ”‚ โ””โ”€โ”€ styles.css # Global styles
```

### Start the Frontend
```bash
cd frontend
npm install
ng serve --open
```
Available at `http://localhost:4200` โ€” connects automatically to the Gateway on `https://localhost:8443`.

---

**Author**: [DedSlash](https://github.com/DedSlash)
**Repository**: [github.com/DedSlash/buy-02](https://github.com/DedSlash/buy-02)
**Version**: 2.0.0 | **Spring Boot**: 3.5.3 | **Spring Cloud**: 2025.0.0