From 1a2199a4b0008798d9c622087d82d0cdf85a47f0 Mon Sep 17 00:00:00 2001 From: 3ein39 Date: Tue, 8 Jul 2025 11:02:26 +0300 Subject: [PATCH 1/8] feat: Add comprehensive feature documentation for Service Sphere platform docs: Update README with project overview, core features, and technology stack chore: Update package.json with new project name, description, and metadata --- API_DOCUMENTATION.md | 834 ++++++++++++++++++++++++++++++++++++ ARCHITECTURE.md | 492 ++++++++++++++++++++++ DEPLOYMENT.md | 984 +++++++++++++++++++++++++++++++++++++++++++ FEATURES.md | 452 ++++++++++++++++++++ README.md | 323 +++++++++++++- package.json | 29 +- 6 files changed, 3087 insertions(+), 27 deletions(-) create mode 100644 API_DOCUMENTATION.md create mode 100644 ARCHITECTURE.md create mode 100644 DEPLOYMENT.md create mode 100644 FEATURES.md diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md new file mode 100644 index 0000000..37ec66a --- /dev/null +++ b/API_DOCUMENTATION.md @@ -0,0 +1,834 @@ +# 📚 Service Sphere - API Documentation + +## 📋 Table of Contents +- [API Overview](#api-overview) +- [Authentication Endpoints](#authentication-endpoints) +- [User Management](#user-management) +- [Service Management](#service-management) +- [Booking System](#booking-system) +- [Real-time Chat](#real-time-chat) +- [Feedback System](#feedback-system) +- [Category Management](#category-management) +- [Administrative APIs](#administrative-apis) +- [Error Handling](#error-handling) + +## 🌐 API Overview + +### Base Configuration +- **Base URL**: `http://localhost:3000/api/v1` +- **Content-Type**: `application/json` +- **Authentication**: Bearer Token (JWT) +- **API Version**: v1 + +### Response Format (JSend Standard) +```json +{ + "status": "success|fail|error", + "data": { /* response data */ }, + "message": "Optional message" +} +``` + +### Common Headers +```http +Authorization: Bearer +Content-Type: application/json +Accept: application/json +``` + +## 🔐 Authentication Endpoints + +### Customer Registration +```http +POST /api/v1/auth/register/customer +``` + +**Request Body:** +```json +{ + "first_name": "John", + "last_name": "Doe", + "email": "john.doe@example.com", + "password": "SecurePassword123!", + "phone_number": "+1234567890" +} +``` + +**Response (201 Created):** +```json +{ + "status": "success", + "data": { + "user": { + "_id": "user_id_here", + "first_name": "John", + "last_name": "Doe", + "email": "john.doe@example.com", + "role": "customer", + "email_verified": false, + "profile_image": "default_image_url" + }, + "emailSent": true + }, + "message": "Customer registered successfully. Please verify your email." +} +``` + +### Service Provider Registration +```http +POST /api/v1/auth/register/service-provider +``` + +**Request Body:** +```json +{ + "first_name": "Jane", + "last_name": "Smith", + "email": "jane@business.com", + "password": "SecurePassword123!", + "phone_number": "+1234567890", + "business_name": "Jane's Professional Services", + "business_address": "123 Business Street, City, State 12345", + "tax_id": "TAX123456789" +} +``` + +**Response (201 Created):** +```json +{ + "status": "success", + "data": { + "user": { + "_id": "provider_id_here", + "first_name": "Jane", + "last_name": "Smith", + "email": "jane@business.com", + "role": "service_provider", + "business_name": "Jane's Professional Services", + "verification_status": "pending", + "rating_average": 0 + }, + "emailSent": true + } +} +``` + +### User Login +```http +POST /api/v1/auth/login +``` + +**Request Body:** +```json +{ + "email": "user@example.com", + "password": "UserPassword123!" +} +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": { + "user": { + "_id": "user_id", + "email": "user@example.com", + "role": "customer", + "email_verified": true + }, + "tokens": { + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "refresh_token": "refresh_token_here", + "expires_in": 900 + } + } +} +``` + +### Email Verification +```http +POST /api/v1/auth/verify-email +``` + +**Request Body:** +```json +{ + "userId": "user_id_here", + "otp": "123456" +} +``` + +### Refresh Token +```http +POST /api/v1/auth/refresh +``` + +**Request Body:** +```json +{ + "refreshToken": "refresh_token_here" +} +``` + +### Password Reset Request +```http +POST /api/v1/auth/forgot-password +``` + +**Request Body:** +```json +{ + "email": "user@example.com" +} +``` + +### Password Reset Confirmation +```http +PATCH /api/v1/auth/reset-password/:token +``` + +**Request Body:** +```json +{ + "newPassword": "NewSecurePassword123!" +} +``` + +### Logout +```http +POST /api/v1/auth/logout +``` + +**Request Body:** +```json +{ + "refreshToken": "refresh_token_here" +} +``` + +## 👥 User Management + +### Get All Customers (Admin Only) +```http +GET /api/v1/users/customers +Authorization: Bearer +``` + +### Get Customer by ID +```http +GET /api/v1/users/customers/:id +Authorization: Bearer +``` + +### Update Customer Profile +```http +PATCH /api/v1/users/customers/:id +Content-Type: multipart/form-data +Authorization: Bearer +``` + +**Form Data:** +``` +first_name: Updated Name +phone_number: +1987654321 +profile_image: +``` + +### Get All Service Providers +```http +GET /api/v1/users/service-providers +Authorization: Bearer +``` + +### Get Service Provider by ID +```http +GET /api/v1/users/service-providers/:id +Authorization: Bearer +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": { + "_id": "provider_id", + "first_name": "Jane", + "last_name": "Smith", + "business_name": "Jane's Services", + "verification_status": "approved", + "rating_average": 4.8, + "profile_image": "profile_image_url" + } +} +``` + +## 🛍️ Service Management + +### Get All Services +```http +GET /api/v1/services +Authorization: Bearer +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": [ + { + "_id": "service_id", + "service_name": "Premium House Cleaning", + "description": "Professional deep cleaning service", + "base_price": 150.00, + "status": "active", + "service_provider": { + "_id": "provider_id", + "business_name": "Clean Pro Services", + "rating_average": 4.9 + }, + "categories": [ + { + "_id": "category_id", + "name": "Cleaning" + } + ], + "images": ["image1_url", "image2_url"], + "service_attributes": { + "duration": "3-4 hours", + "equipment_included": true + } + } + ] +} +``` + +### Get Service by ID +```http +GET /api/v1/services/:id +Authorization: Bearer +``` + +### Create New Service (Service Provider Only) +```http +POST /api/v1/services +Content-Type: multipart/form-data +Authorization: Bearer +``` + +**Form Data:** +``` +service_name: Premium House Cleaning +description: Professional deep cleaning service with eco-friendly products +base_price: 150.00 +categories: ["cleaning_category_id", "home_services_category_id"] +service_attributes: {"duration": "3-4 hours", "equipment_included": true} +images: , +``` + +**Response (201 Created):** +```json +{ + "status": "success", + "data": { + "_id": "new_service_id", + "service_name": "Premium House Cleaning", + "description": "Professional deep cleaning service", + "base_price": 150.00, + "status": "active", + "service_provider": "provider_id", + "categories": ["category_id_1", "category_id_2"], + "images": ["uploaded_image_url_1", "uploaded_image_url_2"], + "creation_time": "2024-07-08T10:00:00.000Z" + } +} +``` + +### Update Service +```http +PATCH /api/v1/services/:id +Content-Type: multipart/form-data +Authorization: Bearer +``` + +### Delete Service +```http +DELETE /api/v1/services/:id +Authorization: Bearer +``` + +### Get My Services (Provider Only) +```http +GET /api/v1/services/my-services +Authorization: Bearer +``` + +### Get Services by Provider ID +```http +GET /api/v1/services/provider/:providerId +Authorization: Bearer +``` + +## 📅 Booking System + +### Create Booking +```http +POST /api/v1/bookings/:serviceId +Authorization: Bearer +``` + +**Request Body:** +```json +{ + "preferred_date": "2024-07-15T10:00:00Z", + "special_instructions": "Please use eco-friendly cleaning supplies" +} +``` + +**Response (201 Created):** +```json +{ + "status": "success", + "data": { + "_id": "booking_id", + "customer": "customer_id", + "service": { + "_id": "service_id", + "service_name": "Premium House Cleaning", + "service_provider": { + "_id": "provider_id", + "business_name": "Clean Pro Services" + } + }, + "status": "pending", + "booking_date": "2024-07-15T10:00:00Z", + "total_amount": 150.00, + "created_at": "2024-07-08T12:00:00Z" + } +} +``` + +### Get Customer Bookings +```http +GET /api/v1/bookings +Authorization: Bearer +``` + +### Get Provider Bookings +```http +GET /api/v1/bookings/provider +Authorization: Bearer +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": [ + { + "_id": "booking_id", + "customer": { + "_id": "customer_id", + "full_name": "John Doe", + "email": "john@example.com", + "profile_image": "customer_image_url" + }, + "service": { + "_id": "service_id", + "service_name": "Premium House Cleaning" + }, + "status": "confirmed", + "booking_date": "2024-07-15T10:00:00Z", + "total_amount": 150.00 + } + ] +} +``` + +### Update Booking Status +```http +PATCH /api/v1/bookings/:id/status +Authorization: Bearer +``` + +**Request Body:** +```json +{ + "status": "confirmed" +} +``` + +**Status Options:** +- `pending` - Initial booking state +- `confirmed` - Provider accepted booking +- `completed` - Service was delivered +- `cancelled` - Booking was cancelled + +### Get Booking by ID +```http +GET /api/v1/bookings/:id +Authorization: Bearer +``` + +## 💬 Real-time Chat + +### WebSocket Connection +```javascript +// Connect to WebSocket +const socket = io('http://localhost:3000', { + auth: { + token: 'your_jwt_token' + } +}); + +// Join booking-specific chat room +socket.emit('joinBookingRoom', { + userId: 'user_id', + bookingId: 'booking_id' +}); + +// Listen for new messages +socket.on('newMessage', (message) => { + console.log('New message received:', message); +}); + +// Send message +socket.emit('sendMessage', { + bookingId: 'booking_id', + content: 'Hello, when can you start the service?' +}); +``` + +### Get Chat History +```http +GET /api/v1/chat/history/:bookingId +Authorization: Bearer +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": { + "booking": { + "_id": "booking_id", + "service": { + "service_name": "House Cleaning" + } + }, + "messages": [ + { + "_id": "message_id", + "sender": { + "_id": "user_id", + "first_name": "John", + "profile_image": "image_url" + }, + "content": "Hello, when can you start?", + "timestamp": "2024-07-08T12:30:00Z" + } + ] + } +} +``` + +## ⭐ Feedback System + +### Submit Feedback +```http +POST /api/v1/feedback +Authorization: Bearer +``` + +**Request Body:** +```json +{ + "service": "service_id", + "booking": "booking_id", + "rating": 5, + "review_text": "Excellent service! Very professional and thorough cleaning." +} +``` + +**Response (201 Created):** +```json +{ + "status": "success", + "data": { + "_id": "feedback_id", + "user": "customer_id", + "service": "service_id", + "booking": "booking_id", + "rating": 5, + "review_text": "Excellent service! Very professional and thorough cleaning.", + "sentiment_score": 0.9, + "sentiment_magnitude": 0.8, + "created_at": "2024-07-08T15:00:00Z" + } +} +``` + +### Get Service Feedback +```http +GET /api/v1/feedback/service/:serviceId +Authorization: Bearer +``` + +### Get Provider Feedback +```http +GET /api/v1/feedback/provider/:providerId +Authorization: Bearer +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": [ + { + "_id": "feedback_id", + "user": { + "_id": "customer_id", + "first_name": "John", + "last_name": "Doe", + "profile_image": "customer_image" + }, + "service": { + "_id": "service_id", + "service_name": "Premium House Cleaning" + }, + "rating": 5, + "review_text": "Outstanding service quality!", + "created_at": "2024-07-08T15:00:00Z" + } + ] +} +``` + +### Delete Feedback +```http +DELETE /api/v1/feedback/:id +Authorization: Bearer +``` + +## 🏷️ Category Management + +### Get All Categories +```http +GET /api/v1/categories +Authorization: Bearer +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": [ + { + "_id": "category_id_1", + "name": "Cleaning Services" + }, + { + "_id": "category_id_2", + "name": "Home Maintenance" + }, + { + "_id": "category_id_3", + "name": "Garden & Landscaping" + } + ] +} +``` + +### Create Category (Admin Only) +```http +POST /api/v1/categories +Authorization: Bearer +``` + +**Request Body:** +```json +{ + "name": "Pet Services" +} +``` + +### Update Category (Admin Only) +```http +PATCH /api/v1/categories/:id +Authorization: Bearer +``` + +### Delete Category (Admin Only) +```http +DELETE /api/v1/categories/:id +Authorization: Bearer +``` + +## 🔧 Administrative APIs + +### Get Platform Statistics (Admin Only) +```http +GET /api/v1/admin/statistics +Authorization: Bearer +``` + +**Response (200 OK):** +```json +{ + "status": "success", + "data": { + "users": { + "total_customers": 1250, + "total_providers": 180, + "verified_providers": 165, + "new_registrations_this_month": 45 + }, + "bookings": { + "total_bookings": 3420, + "completed_bookings": 3100, + "pending_bookings": 85, + "bookings_this_month": 340 + }, + "services": { + "total_services": 450, + "active_services": 420, + "most_popular_category": "Cleaning Services" + }, + "revenue": { + "total_platform_revenue": 125000.00, + "revenue_this_month": 12500.00, + "average_booking_value": 165.50 + } + } +} +``` + +### Approve Service Provider (Admin Only) +```http +PATCH /api/v1/admin/providers/:id/verify +Authorization: Bearer +``` + +**Request Body:** +```json +{ + "verification_status": "approved", + "admin_notes": "All documents verified and approved" +} +``` + +## ❌ Error Handling + +### Error Response Format +```json +{ + "status": "error", + "message": "Detailed error message", + "error": { + "code": "ERROR_CODE", + "details": "Additional error details", + "timestamp": "2024-07-08T12:00:00Z" + } +} +``` + +### Common HTTP Status Codes + +#### Authentication Errors +- **401 Unauthorized**: Invalid or missing token +- **403 Forbidden**: Insufficient permissions +- **422 Unprocessable Entity**: Email not verified + +#### Client Errors +- **400 Bad Request**: Invalid request data +- **404 Not Found**: Resource not found +- **409 Conflict**: Duplicate resource (email exists) + +#### Server Errors +- **500 Internal Server Error**: Unexpected server error +- **503 Service Unavailable**: External service unavailable + +### Example Error Responses + +#### Validation Error (400) +```json +{ + "status": "fail", + "data": { + "validation_errors": [ + { + "field": "email", + "message": "Email must be a valid email address" + }, + { + "field": "password", + "message": "Password must be at least 8 characters long" + } + ] + } +} +``` + +#### Authentication Error (401) +```json +{ + "status": "error", + "message": "Invalid or expired token", + "error": { + "code": "INVALID_TOKEN", + "details": "Please login again to get a new token" + } +} +``` + +#### Permission Error (403) +```json +{ + "status": "error", + "message": "Insufficient permissions to access this resource", + "error": { + "code": "INSUFFICIENT_PERMISSIONS", + "required_role": "service_provider", + "user_role": "customer" + } +} +``` + +#### Resource Not Found (404) +```json +{ + "status": "fail", + "data": { + "resource": "service", + "id": "invalid_service_id", + "message": "Service with ID 'invalid_service_id' not found" + } +} +``` + +## 📊 Rate Limiting + +### API Rate Limits +- **Authentication endpoints**: 5 requests per minute per IP +- **General API endpoints**: 100 requests per minute per user +- **File upload endpoints**: 10 requests per minute per user +- **WebSocket connections**: 1 connection per user per booking + +### Rate Limit Headers +```http +X-RateLimit-Limit: 100 +X-RateLimit-Remaining: 95 +X-RateLimit-Reset: 1625097600 +``` + +--- + +This API documentation demonstrates: + +- **RESTful Design**: Clean and intuitive API endpoints +- **Comprehensive Coverage**: All major platform features +- **Security Implementation**: Authentication and authorization +- **Real-world Complexity**: Production-ready API design +- **Error Handling**: Professional error management +- **Documentation Quality**: Enterprise-level documentation standards diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..d76b326 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,492 @@ +# 🏗️ Service Sphere - System Architecture + +## 📋 Table of Contents +- [System Overview](#system-overview) +- [Architecture Patterns](#architecture-patterns) +- [Module Structure](#module-structure) +- [Data Flow](#data-flow) +- [Security Architecture](#security-architecture) +- [Real-time Communication](#real-time-communication) +- [Database Design](#database-design) +- [Deployment Architecture](#deployment-architecture) + +## 🌐 System Overview + +Service Sphere follows a **modular monolith architecture** with clear separation of concerns, designed to be easily scalable into microservices when needed. The system is built using **Domain-Driven Design (DDD)** principles with clean architecture patterns. + +### High-Level Architecture + +```mermaid +graph TB + subgraph "Client Layer" + A[Mobile App] --> B[API Gateway] + C[Web App] --> B + D[Admin Panel] --> B + end + + subgraph "Application Layer" + B --> E[Authentication Service] + B --> F[User Management] + B --> G[Service Management] + B --> H[Booking System] + B --> I[Chat Service] + B --> J[Notification Service] + end + + subgraph "Infrastructure Layer" + E --> K[(MongoDB)] + F --> K + G --> K + H --> K + I --> K + J --> L[Email Service] + G --> M[Cloudinary] + I --> N[WebSocket Gateway] + end +``` + +## 🔧 Architecture Patterns + +### 1. Modular Monolith +- **Bounded Contexts**: Each module represents a distinct business domain +- **Loose Coupling**: Modules interact through well-defined interfaces +- **Independent Development**: Teams can work on different modules simultaneously +- **Migration Ready**: Easy transition to microservices architecture + +### 2. Dependency Injection Pattern +```typescript +@Injectable() +export class BookingsService { + constructor( + @InjectModel(ServiceBookings.name) private bookingModel: Model, + private readonly servicesService: ServicesService, + private readonly usersService: UsersService, + private readonly notificationService: NotificationService, + ) {} +} +``` + +### 3. Repository Pattern +- Abstract data access layer +- Centralized query logic +- Easy testing with mock repositories +- Database-agnostic business logic + +### 4. Observer Pattern (Event-Driven) +```typescript +// Booking status changes trigger notifications +async updateBookingStatus(bookingId: string, status: string) { + const updatedBooking = await booking.save(); + + // Emit event for notification service + await this.notificationService.sendBookingStatusUpdate(/* ... */); +} +``` + +## 🏢 Module Structure + +### Core Modules + +#### 1. Authentication Module (`auth/`) +``` +auth/ +├── auth.controller.ts # Auth endpoints +├── auth.service.ts # Authentication logic +├── auth.module.ts # Module configuration +├── strategies/ # Passport strategies +├── guards/ # Route guards +├── decorators/ # Custom decorators +├── dto/ # Data transfer objects +└── interfaces/ # Type definitions +``` + +**Responsibilities:** +- User registration and login +- JWT token management +- Email verification +- Password reset functionality +- Role-based access control + +#### 2. User Management Module (`users/`) +``` +users/ +├── users.controller.ts # User CRUD operations +├── users.service.ts # User business logic +├── user.module.ts # Module configuration +├── dto/ # User DTOs +├── interfaces/ # User interfaces +└── schemas/ # Database schemas + ├── user.schema.ts + └── service-provider.schema.ts +``` + +**Responsibilities:** +- User profile management +- Service provider verification +- Admin user management +- Profile image handling + +#### 3. Service Management Module (`services/`) +``` +services/ +├── services.controller.ts # Service endpoints +├── services.service.ts # Service business logic +├── services.module.ts # Module configuration +├── dto/ # Service DTOs +├── interfaces/ # Service interfaces +└── schemas/ # Service database schema +``` + +**Responsibilities:** +- Service listing creation +- Service categorization +- Image upload and management +- Service search and filtering + +#### 4. Booking System Module (`service-bookings/`) +``` +service-bookings/ +├── service-bookings.controller.ts +├── service-bookings.service.ts +├── service-bookings.module.ts +├── dto/ +└── schemas/ +``` + +**Responsibilities:** +- Booking creation and management +- Status tracking +- Provider-customer booking coordination +- Booking analytics + +#### 5. Real-time Chat Module (`chat/`) +``` +chat/ +├── chat.gateway.ts # WebSocket gateway +├── chat.service.ts # Chat business logic +├── chat.module.ts # Module configuration +├── dto/ # Chat DTOs +├── guards/ # WebSocket guards +└── schemas/ # Chat message schema +``` + +**Responsibilities:** +- Real-time messaging +- Message persistence +- Chat access control +- Online status management + +#### 6. Feedback System Module (`feedback/`) +``` +feedback/ +├── feedback.controller.ts +├── feedback.service.ts +├── sentiment-analysis.service.ts +├── feedback.module.ts +├── dto/ +└── schemas/ +``` + +**Responsibilities:** +- Review and rating management +- Sentiment analysis +- Feedback categorization +- Provider rating calculation + +## 🔄 Data Flow + +### 1. Authentication Flow +```mermaid +sequenceDiagram + participant Client + participant AuthController + participant AuthService + participant UserService + participant Database + participant EmailService + + Client->>AuthController: POST /auth/register + AuthController->>AuthService: registerUser(userData) + AuthService->>UserService: createUser(userData) + UserService->>Database: save(user) + AuthService->>EmailService: sendVerificationEmail(user) + AuthService->>Client: { user, message } +``` + +### 2. Service Booking Flow +```mermaid +sequenceDiagram + participant Customer + participant BookingController + participant BookingService + participant ServiceService + participant NotificationService + participant Provider + + Customer->>BookingController: POST /bookings/:serviceId + BookingController->>BookingService: createBooking(serviceId, customerId) + BookingService->>ServiceService: getServiceById(serviceId) + BookingService->>Database: save(booking) + BookingService->>NotificationService: notifyProvider(booking) + NotificationService->>Provider: New booking notification +``` + +### 3. Real-time Chat Flow +```mermaid +sequenceDiagram + participant User + participant ChatGateway + participant ChatService + participant Database + participant RecipientUser + + User->>ChatGateway: sendMessage(bookingId, message) + ChatGateway->>ChatService: validateAccess(userId, bookingId) + ChatService->>ChatService: createMessage(senderId, bookingId, content) + ChatService->>Database: save(message) + ChatService->>ChatGateway: message saved + ChatGateway->>RecipientUser: emit('newMessage', message) +``` + +## 🔐 Security Architecture + +### Authentication & Authorization Layers + +```mermaid +graph TD + A[Request] --> B[CORS Middleware] + B --> C[Rate Limiting] + C --> D[JWT Validation] + D --> E[Role-based Access Control] + E --> F[Route Handler] + F --> G[Input Validation] + G --> H[Business Logic] +``` + +### Security Features Implemented + +1. **JWT Authentication** + - Access tokens (15 minutes) + - Refresh tokens (7 days) + - Token rotation on refresh + +2. **Role-Based Access Control (RBAC)** + ```typescript + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('admin', 'service_provider') + async createService() { /* ... */ } + ``` + +3. **Input Validation** + ```typescript + @IsEmail() + @IsNotEmpty() + email: string; + + @MinLength(8) + @Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/) + password: string; + ``` + +4. **Data Sanitization** + - XSS prevention + - SQL injection protection + - File upload validation + +## 🔄 Real-time Communication + +### WebSocket Architecture + +```typescript +@WebSocketGateway({ + cors: { + origin: '*', + }, +}) +export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect { + @SubscribeMessage('joinBookingRoom') + async handleJoinRoom(client: Socket, payload: JoinRoomDto) { + // Validate user access to booking + const { booking } = await this.chatService.validateUserAccess( + payload.userId, + payload.bookingId, + ); + + // Join room for real-time updates + client.join(`booking-${payload.bookingId}`); + } +} +``` + +### Real-time Features +- **Chat messaging** between customers and providers +- **Booking status updates** in real-time +- **Online status** indicators +- **Typing indicators** for enhanced UX + +## 💾 Database Design + +### MongoDB Schema Design + +#### User Collection +```typescript +{ + _id: ObjectId, + email: String (unique), + password: String (hashed), + first_name: String, + last_name: String, + role: Enum['customer', 'service_provider', 'admin'], + profile_image: String, + email_verified: Boolean, + created_at: Date, + + // Service Provider specific fields + business_name?: String, + business_address?: String, + tax_id?: String, + verification_status?: Enum['pending', 'approved', 'rejected'], + rating_average?: Number +} +``` + +#### Service Collection +```typescript +{ + _id: ObjectId, + service_name: String, + description: String, + base_price: Number, + status: Enum['active', 'inactive'], + service_provider: ObjectId (ref: User), + categories: [ObjectId] (ref: Category), + images: [String], + service_attributes: Object, + creation_time: Date +} +``` + +#### Booking Collection +```typescript +{ + _id: ObjectId, + customer: ObjectId (ref: User), + service: ObjectId (ref: Service), + status: Enum['pending', 'confirmed', 'completed', 'cancelled'], + booking_date: Date, + total_amount: Number, + created_at: Date, + updated_at: Date +} +``` + +### Indexing Strategy +```javascript +// User indices +db.users.createIndex({ email: 1 }, { unique: true }) +db.users.createIndex({ role: 1 }) + +// Service indices +db.services.createIndex({ service_provider: 1 }) +db.services.createIndex({ categories: 1 }) +db.services.createIndex({ status: 1 }) + +// Booking indices +db.bookings.createIndex({ customer: 1 }) +db.bookings.createIndex({ service: 1 }) +db.bookings.createIndex({ status: 1 }) +``` + +## 🚀 Deployment Architecture + +### Container Architecture +```dockerfile +# Multi-stage build for production optimization +FROM node:18-alpine AS builder +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production + +FROM node:18-alpine AS production +WORKDIR /app +COPY --from=builder /app/node_modules ./node_modules +COPY dist ./dist +EXPOSE 3000 +CMD ["node", "dist/main.js"] +``` + +### Docker Compose Setup +```yaml +version: '3.8' +services: + app: + build: . + ports: + - "3000:3000" + environment: + - NODE_ENV=production + depends_on: + - mongodb + - redis + + mongodb: + image: mongo:7 + volumes: + - mongo_data:/data/db + + redis: + image: redis:7-alpine + volumes: + - redis_data:/data +``` + +### Production Considerations + +1. **Horizontal Scaling** + - Load balancer configuration + - Session management with Redis + - Database connection pooling + +2. **Monitoring & Logging** + - Application performance monitoring + - Error tracking and alerting + - Request/response logging + +3. **Security Hardening** + - Environment variable management + - SSL/TLS configuration + - Network security groups + +4. **Backup & Recovery** + - Automated database backups + - Disaster recovery procedures + - Data retention policies + +## 📊 Performance Optimization + +### Caching Strategy +- **Redis** for session storage and temporary data +- **MongoDB** query optimization with proper indexing +- **Cloudinary** for image optimization and CDN delivery + +### Database Optimization +- Connection pooling for database connections +- Aggregation pipelines for complex queries +- Proper indexing strategy for frequently accessed data + +### API Optimization +- Response compression with gzip +- Request/response caching where appropriate +- Pagination for large datasets +- Rate limiting to prevent abuse + +--- + +This architecture documentation demonstrates enterprise-level system design and implementation skills, showcasing: + +- **Scalable Architecture Design** +- **Security Best Practices** +- **Real-time System Implementation** +- **Database Design & Optimization** +- **Modern Development Practices** +- **Production-Ready Deployment** diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 0000000..dcc7225 --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,984 @@ +# 🚀 Service Sphere - Deployment Guide + +## 📋 Table of Contents +- [Deployment Overview](#deployment-overview) +- [Development Environment](#development-environment) +- [Docker Deployment](#docker-deployment) +- [Production Deployment](#production-deployment) +- [Cloud Deployment](#cloud-deployment) +- [Environment Configuration](#environment-configuration) +- [Database Setup](#database-setup) +- [Monitoring & Logging](#monitoring--logging) +- [Security Considerations](#security-considerations) +- [Troubleshooting](#troubleshooting) + +## 🌐 Deployment Overview + +Service Sphere supports multiple deployment strategies, from local development to production-ready cloud deployments. This guide covers all deployment scenarios with step-by-step instructions. + +### Deployment Options +- **Development**: Local development with hot reload +- **Docker**: Containerized deployment for consistency +- **Production**: Optimized production deployment +- **Cloud**: AWS, Google Cloud, or Azure deployment +- **Kubernetes**: Container orchestration for scalability + +## 💻 Development Environment + +### Prerequisites +```bash +# Node.js (v18+ recommended) +node --version # Should be v18.0.0 or higher +npm --version # Should be v8.0.0 or higher + +# MongoDB (optional if using Docker) +mongod --version + +# Git +git --version +``` + +### Local Development Setup + +#### 1. Clone Repository +```bash +git clone git@github.com:Service-Sphere-GP/backend.git +cd backend +``` + +#### 2. Install Dependencies +```bash +# Install all dependencies +npm install + +# Install development dependencies +npm install --include=dev +``` + +#### 3. Environment Configuration +```bash +# Copy environment template +cp .env.example .env.development.local + +# Edit environment variables +nano .env.development.local +``` + +**Required Environment Variables:** +```env +# Database Configuration +DATABASE_URI=mongodb://localhost:27017/service-sphere-dev + +# JWT Configuration +JWT_SECRET=your-super-secret-development-key-here +JWT_ACCESS_TOKEN_EXPIRATION_TIME=15m +JWT_REFRESH_TOKEN_EXPIRATION_TIME=7d + +# Email Configuration (for development) +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USER=your-dev-email@gmail.com +SMTP_PASS=your-app-password + +# Cloudinary Configuration +CLOUDINARY_CLOUD_NAME=your-cloudinary-name +CLOUDINARY_API_KEY=your-api-key +CLOUDINARY_API_SECRET=your-api-secret + +# Application Configuration +APP_PORT=3000 +NODE_ENV=development +CORS_ORIGIN=http://localhost:3001 +``` + +#### 4. Start Development Server +```bash +# Start with hot reload +npm run start:dev + +# Start with debug mode +npm run start:debug + +# Run tests during development +npm run test:watch +``` + +#### 5. Database Seeding (Optional) +```bash +# Seed with sample data +npm run seed + +# Seed with minimal data +npm run seed:minimal +``` + +### Development Tools +```bash +# Code formatting +npm run format + +# Linting +npm run lint + +# Type checking +npx tsc --noEmit + +# Test coverage +npm run test:cov +``` + +## 🐳 Docker Deployment + +### Docker Compose (Recommended for Development) + +#### 1. Basic Docker Setup +```yaml +# docker-compose.yml +version: '3.8' + +services: + app: + build: . + ports: + - "3000:3000" + environment: + - NODE_ENV=development + env_file: + - .env.development.local + depends_on: + - mongodb + volumes: + - .:/app + - /app/node_modules + command: npm run start:dev + + mongodb: + image: mongo:7 + ports: + - "27017:27017" + volumes: + - mongo_data:/data/db + environment: + - MONGO_INITDB_DATABASE=service-sphere + +volumes: + mongo_data: +``` + +#### 2. Start Docker Environment +```bash +# Build and start all services +docker-compose up --build + +# Run in background +docker-compose up -d + +# View logs +docker-compose logs -f app + +# Stop services +docker-compose down + +# Remove volumes (clean database) +docker-compose down -v +``` + +#### 3. Docker Development Commands +```bash +# Execute commands in running container +docker-compose exec app npm run test +docker-compose exec app npm run seed + +# Access MongoDB shell +docker-compose exec mongodb mongosh service-sphere + +# Rebuild specific service +docker-compose build app +``` + +### Production Docker Setup + +#### 1. Multi-stage Dockerfile +```dockerfile +# Multi-stage build for production +FROM node:18-alpine AS builder + +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production && npm cache clean --force + +FROM node:18-alpine AS development +WORKDIR /app +COPY package*.json ./ +RUN npm ci +COPY . . +CMD ["npm", "run", "start:dev"] + +FROM node:18-alpine AS build +WORKDIR /app +COPY package*.json ./ +RUN npm ci +COPY . . +RUN npm run build + +FROM node:18-alpine AS production +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production && npm cache clean --force +COPY --from=build /app/dist ./dist +EXPOSE 3000 +USER node +CMD ["node", "dist/main.js"] +``` + +#### 2. Production Docker Compose +```yaml +# docker-compose.prod.yml +version: '3.8' + +services: + app: + build: + context: . + target: production + ports: + - "3000:3000" + environment: + - NODE_ENV=production + env_file: + - .env.production.local + depends_on: + - mongodb + - redis + restart: unless-stopped + + mongodb: + image: mongo:7 + ports: + - "27017:27017" + volumes: + - mongo_data:/data/db + - ./mongo-init:/docker-entrypoint-initdb.d + environment: + - MONGO_INITDB_ROOT_USERNAME=admin + - MONGO_INITDB_ROOT_PASSWORD=secure_password + restart: unless-stopped + + redis: + image: redis:7-alpine + ports: + - "6379:6379" + volumes: + - redis_data:/data + restart: unless-stopped + + nginx: + image: nginx:alpine + ports: + - "80:80" + - "443:443" + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf + - ./ssl:/etc/nginx/ssl + depends_on: + - app + restart: unless-stopped + +volumes: + mongo_data: + redis_data: +``` + +#### 3. Production Deployment +```bash +# Build production images +docker-compose -f docker-compose.prod.yml build + +# Start production environment +docker-compose -f docker-compose.prod.yml up -d + +# Scale application +docker-compose -f docker-compose.prod.yml up -d --scale app=3 + +# Health check +docker-compose -f docker-compose.prod.yml ps +``` + +## 🏭 Production Deployment + +### Server Requirements +- **CPU**: 2+ cores recommended +- **RAM**: 4GB minimum, 8GB recommended +- **Storage**: 20GB minimum SSD +- **Network**: Stable internet connection +- **OS**: Ubuntu 20.04+ or CentOS 8+ + +### Manual Production Setup + +#### 1. Server Preparation +```bash +# Update system +sudo apt update && sudo apt upgrade -y + +# Install Node.js 18 +curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - +sudo apt-get install -y nodejs + +# Install MongoDB +wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add - +echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list +sudo apt-get update +sudo apt-get install -y mongodb-org + +# Install PM2 for process management +sudo npm install -g pm2 + +# Install Nginx for reverse proxy +sudo apt install nginx -y +``` + +#### 2. Application Deployment +```bash +# Clone repository +git clone git@github.com:Service-Sphere-GP/backend.git +cd backend + +# Install dependencies +npm ci --only=production + +# Build application +npm run build + +# Set up environment +cp .env.example .env.production.local +# Edit .env.production.local with production values +``` + +#### 3. PM2 Process Management +```javascript +// ecosystem.config.js +module.exports = { + apps: [{ + name: 'service-sphere-api', + script: 'dist/main.js', + instances: 'max', + exec_mode: 'cluster', + env: { + NODE_ENV: 'production', + PORT: 3000 + }, + error_file: './logs/err.log', + out_file: './logs/out.log', + log_file: './logs/combined.log', + time: true + }] +}; +``` + +```bash +# Start application with PM2 +pm2 start ecosystem.config.js + +# Save PM2 configuration +pm2 save + +# Set up PM2 startup +pm2 startup + +# Monitor application +pm2 monit +``` + +#### 4. Nginx Configuration +```nginx +# /etc/nginx/sites-available/service-sphere +server { + listen 80; + server_name your-domain.com; + + location / { + proxy_pass http://localhost:3000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + } +} +``` + +```bash +# Enable site +sudo ln -s /etc/nginx/sites-available/service-sphere /etc/nginx/sites-enabled/ + +# Test configuration +sudo nginx -t + +# Restart Nginx +sudo systemctl restart nginx +``` + +#### 5. SSL Configuration with Let's Encrypt +```bash +# Install Certbot +sudo apt install certbot python3-certbot-nginx -y + +# Obtain SSL certificate +sudo certbot --nginx -d your-domain.com + +# Auto-renewal +sudo crontab -e +# Add: 0 12 * * * /usr/bin/certbot renew --quiet +``` + +## ☁️ Cloud Deployment + +### AWS Deployment + +#### 1. EC2 Instance Setup +```bash +# Launch EC2 instance (t3.medium recommended) +# Security groups: HTTP (80), HTTPS (443), SSH (22), Custom (3000) + +# Connect to instance +ssh -i your-key.pem ubuntu@your-ec2-ip + +# Follow manual production setup above +``` + +#### 2. Amazon ECS Deployment +```json +{ + "family": "service-sphere-task", + "networkMode": "awsvpc", + "requiresCompatibilities": ["FARGATE"], + "cpu": "512", + "memory": "1024", + "executionRoleArn": "arn:aws:iam::account:role/ecsTaskExecutionRole", + "containerDefinitions": [ + { + "name": "service-sphere-api", + "image": "your-account.dkr.ecr.region.amazonaws.com/service-sphere:latest", + "portMappings": [ + { + "containerPort": 3000, + "protocol": "tcp" + } + ], + "environment": [ + { + "name": "NODE_ENV", + "value": "production" + } + ], + "logConfiguration": { + "logDriver": "awslogs", + "options": { + "awslogs-group": "/ecs/service-sphere", + "awslogs-region": "us-east-1", + "awslogs-stream-prefix": "ecs" + } + } + } + ] +} +``` + +#### 3. MongoDB Atlas Integration +```env +# Use MongoDB Atlas for managed database +DATABASE_URI=mongodb+srv://username:password@cluster.mongodb.net/service-sphere?retryWrites=true&w=majority +``` + +### Google Cloud Platform Deployment + +#### 1. Cloud Run Deployment +```yaml +# cloudbuild.yaml +steps: + - name: 'gcr.io/cloud-builders/docker' + args: ['build', '-t', 'gcr.io/$PROJECT_ID/service-sphere', '.'] + - name: 'gcr.io/cloud-builders/docker' + args: ['push', 'gcr.io/$PROJECT_ID/service-sphere'] + - name: 'gcr.io/cloud-builders/gcloud' + args: + - 'run' + - 'deploy' + - 'service-sphere-api' + - '--image' + - 'gcr.io/$PROJECT_ID/service-sphere' + - '--region' + - 'us-central1' + - '--platform' + - 'managed' + - '--allow-unauthenticated' +``` + +```bash +# Deploy to Cloud Run +gcloud builds submit --config cloudbuild.yaml +``` + +### Azure Deployment + +#### 1. Azure Container Instances +```bash +# Create resource group +az group create --name service-sphere-rg --location eastus + +# Deploy container +az container create \ + --resource-group service-sphere-rg \ + --name service-sphere-api \ + --image your-registry/service-sphere:latest \ + --dns-name-label service-sphere \ + --ports 3000 +``` + +## 🔧 Environment Configuration + +### Environment Files Structure +``` +.env.development.local # Development environment +.env.test.local # Testing environment +.env.staging.local # Staging environment +.env.production.local # Production environment +``` + +### Complete Environment Template +```env +# Application Configuration +NODE_ENV=production +APP_PORT=3000 +CORS_ORIGIN=https://your-frontend-domain.com + +# Database Configuration +DATABASE_URI=mongodb://localhost:27017/service-sphere +DATABASE_NAME=service-sphere + +# JWT Configuration +JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters +JWT_ACCESS_TOKEN_EXPIRATION_TIME=15m +JWT_REFRESH_TOKEN_EXPIRATION_TIME=7d + +# Email Configuration +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_SECURE=false +SMTP_USER=your-email@gmail.com +SMTP_PASS=your-app-specific-password + +# Cloudinary Configuration +CLOUDINARY_CLOUD_NAME=your-cloud-name +CLOUDINARY_API_KEY=your-api-key +CLOUDINARY_API_SECRET=your-api-secret + +# Admin Configuration +ADMIN_API_KEY=your-admin-api-key-for-creating-admin-users + +# Redis Configuration (Optional) +REDIS_URL=redis://localhost:6379 + +# Monitoring & Logging +LOG_LEVEL=info +SENTRY_DSN=your-sentry-dsn-for-error-tracking + +# Rate Limiting +RATE_LIMIT_WINDOW_MS=900000 +RATE_LIMIT_MAX_REQUESTS=100 + +# File Upload Limits +MAX_FILE_SIZE=5242880 # 5MB in bytes +ALLOWED_FILE_TYPES=jpg,jpeg,png,gif,webp +``` + +### Environment Validation +```typescript +// src/config/validation.schema.ts +import * as Joi from 'joi'; + +export const configValidationSchema = Joi.object({ + NODE_ENV: Joi.string() + .valid('development', 'production', 'test', 'staging') + .default('development'), + APP_PORT: Joi.number().default(3000), + DATABASE_URI: Joi.string().required(), + JWT_SECRET: Joi.string().min(32).required(), + JWT_ACCESS_TOKEN_EXPIRATION_TIME: Joi.string().default('15m'), + JWT_REFRESH_TOKEN_EXPIRATION_TIME: Joi.string().default('7d'), + SMTP_HOST: Joi.string().required(), + SMTP_PORT: Joi.number().default(587), + SMTP_USER: Joi.string().required(), + SMTP_PASS: Joi.string().required(), + CLOUDINARY_CLOUD_NAME: Joi.string().required(), + CLOUDINARY_API_KEY: Joi.string().required(), + CLOUDINARY_API_SECRET: Joi.string().required(), +}); +``` + +## 🗄️ Database Setup + +### MongoDB Configuration + +#### 1. Local MongoDB Setup +```bash +# Install MongoDB +sudo apt-get install -y mongodb-org + +# Start MongoDB service +sudo systemctl start mongod +sudo systemctl enable mongod + +# Create database user +mongosh +``` + +```javascript +// MongoDB shell commands +use service-sphere + +// Create application user +db.createUser({ + user: "service_sphere_user", + pwd: "secure_password", + roles: [ + { role: "readWrite", db: "service-sphere" } + ] +}) + +// Create indexes for performance +db.users.createIndex({ email: 1 }, { unique: true }) +db.users.createIndex({ role: 1 }) +db.services.createIndex({ service_provider: 1 }) +db.services.createIndex({ categories: 1 }) +db.bookings.createIndex({ customer: 1 }) +db.bookings.createIndex({ service: 1 }) +db.feedback.createIndex({ service: 1 }) +``` + +#### 2. MongoDB Atlas (Cloud) Setup +```bash +# 1. Create MongoDB Atlas account +# 2. Create cluster +# 3. Configure network access (whitelist your IP) +# 4. Create database user +# 5. Get connection string +``` + +```env +# Atlas connection string +DATABASE_URI=mongodb+srv://username:password@cluster.mongodb.net/service-sphere?retryWrites=true&w=majority +``` + +### Database Migration & Seeding + +#### 1. Seed Scripts +```typescript +// src/seeds/seed.ts +import { NestFactory } from '@nestjs/core'; +import { AppModule } from '../app.module'; +import { UsersService } from '../users/users.service'; +import { CategoriesService } from '../categories/categories.service'; + +async function bootstrap() { + const app = await NestFactory.createApplicationContext(AppModule); + + const usersService = app.get(UsersService); + const categoriesService = app.get(CategoriesService); + + // Seed categories + const categories = [ + 'Cleaning Services', + 'Home Maintenance', + 'Garden & Landscaping', + 'Pet Services', + 'Tutoring & Education' + ]; + + for (const categoryName of categories) { + await categoriesService.create(categoryName); + } + + // Seed admin user + await usersService.createAdmin({ + first_name: 'Admin', + last_name: 'User', + email: 'admin@servicespherem.com', + password: 'AdminPassword123!' + }); + + console.log('Database seeded successfully'); + await app.close(); +} + +bootstrap(); +``` + +```bash +# Run seed script +npm run seed +``` + +## 📊 Monitoring & Logging + +### Application Monitoring + +#### 1. Health Check Endpoint +```typescript +// src/app.controller.ts +@Get('health') +async healthCheck() { + return { + status: 'ok', + timestamp: new Date().toISOString(), + uptime: process.uptime(), + environment: process.env.NODE_ENV, + version: process.env.npm_package_version + }; +} +``` + +#### 2. PM2 Monitoring +```bash +# Real-time monitoring +pm2 monit + +# CPU and memory usage +pm2 list + +# Restart application +pm2 restart service-sphere-api + +# View logs +pm2 logs service-sphere-api + +# Reload application (zero-downtime) +pm2 reload service-sphere-api +``` + +#### 3. Nginx Monitoring +```bash +# Check Nginx status +sudo systemctl status nginx + +# View access logs +sudo tail -f /var/log/nginx/access.log + +# View error logs +sudo tail -f /var/log/nginx/error.log +``` + +### Logging Configuration + +#### 1. Winston Logger Setup +```typescript +// src/config/logger.config.ts +import { WinstonModule } from 'nest-winston'; +import * as winston from 'winston'; + +export const loggerConfig = WinstonModule.createLogger({ + transports: [ + new winston.transports.Console({ + format: winston.format.combine( + winston.format.timestamp(), + winston.format.colorize(), + winston.format.simple() + ), + }), + new winston.transports.File({ + filename: 'logs/error.log', + level: 'error', + format: winston.format.combine( + winston.format.timestamp(), + winston.format.json() + ), + }), + new winston.transports.File({ + filename: 'logs/combined.log', + format: winston.format.combine( + winston.format.timestamp(), + winston.format.json() + ), + }), + ], +}); +``` + +#### 2. Error Tracking with Sentry +```typescript +// src/main.ts +import * as Sentry from '@sentry/node'; + +if (process.env.NODE_ENV === 'production') { + Sentry.init({ + dsn: process.env.SENTRY_DSN, + environment: process.env.NODE_ENV, + }); +} +``` + +## 🔒 Security Considerations + +### Production Security Checklist + +#### 1. Environment Security +```bash +# Set proper file permissions +chmod 600 .env.production.local + +# Use environment variables, not files in production +export JWT_SECRET="your-secret-here" +``` + +#### 2. Database Security +```javascript +// MongoDB security +db.createUser({ + user: "service_sphere_user", + pwd: "strong_random_password", + roles: [{ role: "readWrite", db: "service-sphere" }] +}) + +// Enable authentication +# In /etc/mongod.conf +security: + authorization: enabled +``` + +#### 3. Nginx Security Headers +```nginx +# Security headers +add_header X-Frame-Options "SAMEORIGIN" always; +add_header X-XSS-Protection "1; mode=block" always; +add_header X-Content-Type-Options "nosniff" always; +add_header Referrer-Policy "no-referrer-when-downgrade" always; +add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always; + +# Hide Nginx version +server_tokens off; +``` + +#### 4. Firewall Configuration +```bash +# UFW firewall setup +sudo ufw enable +sudo ufw allow ssh +sudo ufw allow 'Nginx Full' +sudo ufw allow 27017 # MongoDB (restrict to app server IP in production) +``` + +## 🐛 Troubleshooting + +### Common Issues + +#### 1. Application Won't Start +```bash +# Check logs +pm2 logs service-sphere-api + +# Check environment variables +pm2 env 0 + +# Restart application +pm2 restart service-sphere-api + +# Check port availability +sudo netstat -tlnp | grep :3000 +``` + +#### 2. Database Connection Issues +```bash +# Test MongoDB connection +mongosh "mongodb://localhost:27017/service-sphere" + +# Check MongoDB status +sudo systemctl status mongod + +# Restart MongoDB +sudo systemctl restart mongod + +# Check MongoDB logs +sudo tail -f /var/log/mongodb/mongod.log +``` + +#### 3. Memory Issues +```bash +# Check memory usage +free -h + +# Check application memory usage +pm2 monit + +# Restart application if memory leak +pm2 restart service-sphere-api +``` + +#### 4. SSL Certificate Issues +```bash +# Check certificate status +sudo certbot certificates + +# Renew certificate manually +sudo certbot renew + +# Test certificate +openssl s_client -connect your-domain.com:443 +``` + +### Performance Optimization + +#### 1. Database Optimization +```javascript +// Add compound indexes +db.bookings.createIndex({ customer: 1, status: 1 }) +db.services.createIndex({ service_provider: 1, status: 1 }) + +// Monitor slow queries +db.setProfilingLevel(2, { slowms: 100 }) +db.system.profile.find().sort({ ts: -1 }).limit(5) +``` + +#### 2. Application Optimization +```typescript +// Enable compression +app.use(compression()); + +// Connection pooling +MongooseModule.forRootAsync({ + useFactory: () => ({ + uri: process.env.DATABASE_URI, + maxPoolSize: 10, + serverSelectionTimeoutMS: 5000, + socketTimeoutMS: 45000, + }), +}); +``` + +#### 3. Nginx Optimization +```nginx +# Enable gzip compression +gzip on; +gzip_vary on; +gzip_min_length 1024; +gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json; + +# Enable caching +location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { + expires 1y; + add_header Cache-Control "public, immutable"; +} +``` + +--- + +This deployment guide demonstrates: + +- **Multiple Deployment Strategies**: From development to production +- **Container Orchestration**: Docker and Kubernetes ready +- **Cloud Platform Support**: AWS, GCP, Azure deployment options +- **Production Best Practices**: Security, monitoring, optimization +- **Troubleshooting Skills**: Problem-solving and debugging +- **DevOps Knowledge**: Infrastructure as code and automation diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..ab6cd40 --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,452 @@ +# 🚀 Service Sphere - Feature Documentation + +## 📋 Table of Contents +- [Feature Overview](#feature-overview) +- [Authentication & Security](#authentication--security) +- [User Management System](#user-management-system) +- [Service Marketplace](#service-marketplace) +- [Booking Management](#booking-management) +- [Real-time Communication](#real-time-communication) +- [Feedback & Rating System](#feedback--rating-system) +- [Notification System](#notification-system) +- [Administrative Features](#administrative-features) +- [Integration Features](#integration-features) + +## 🌟 Feature Overview + +Service Sphere is a comprehensive service marketplace platform that connects customers with service providers through a sophisticated booking and communication system. The platform supports multiple user roles and provides real-time features for seamless interaction. + +### Core Value Propositions +- **For Customers**: Easy discovery and booking of local services +- **For Service Providers**: Professional platform to showcase services and manage bookings +- **For Administrators**: Complete platform oversight and management capabilities + +## 🔐 Authentication & Security + +### Multi-Factor Authentication System +```typescript +// Email verification with OTP +POST /api/v1/auth/register/customer +{ + "first_name": "John", + "last_name": "Doe", + "email": "john@example.com", + "password": "SecurePass123!", + "phone_number": "+1234567890" +} + +// Response includes OTP sent to email +{ + "status": "success", + "data": { + "user": { /* user data */ }, + "message": "Verification email sent", + "emailSent": true + } +} +``` + +### Advanced Security Features + +#### 1. JWT Token Management +- **Access Tokens**: Short-lived (15 minutes) for API requests +- **Refresh Tokens**: Long-lived (7 days) for token renewal +- **Token Rotation**: Automatic refresh token rotation for security +- **Token Revocation**: Immediate logout and token invalidation + +#### 2. Role-Based Access Control (RBAC) +```typescript +// Three distinct user roles with specific permissions +enum UserRole { + CUSTOMER = 'customer', // Book services, leave reviews + SERVICE_PROVIDER = 'service_provider', // Manage services, handle bookings + ADMIN = 'admin' // Platform administration +} + +// Endpoint protection example +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('service_provider', 'admin') +async createService() { /* Only providers and admins can create services */ } +``` + +#### 3. Password Security +- **bcrypt Hashing**: Industry-standard password encryption +- **Password Strength Validation**: Minimum 8 characters with complexity requirements +- **Secure Reset Process**: Token-based password reset with expiration + +#### 4. Email Verification System +- **OTP Generation**: 6-digit codes with 10-minute expiration +- **Resend Capability**: Users can request new verification codes +- **Account Activation**: Users must verify email before platform access + +## 👥 User Management System + +### Customer Management + +#### Profile Features +- **Personal Information**: Name, email, phone, profile picture +- **Booking History**: Complete history of service bookings +- **Favorite Services**: Save preferred services for quick access +- **Reviews & Ratings**: Manage feedback given to service providers + +```typescript +// Customer profile update +PATCH /api/v1/users/customers/:id +{ + "first_name": "Updated Name", + "profile_image": "base64_or_url" +} +``` + +### Service Provider Management + +#### Business Profile Features +- **Business Information**: Business name, address, tax ID +- **Verification System**: Multi-step verification process +- **Service Portfolio**: Manage multiple service offerings +- **Performance Analytics**: Booking statistics and ratings + +```typescript +// Service provider registration with business details +POST /api/v1/auth/register/service-provider +{ + "first_name": "Jane", + "last_name": "Smith", + "email": "jane@business.com", + "business_name": "Jane's Cleaning Services", + "business_address": "123 Business St, City", + "tax_id": "TAX123456789", + "password": "SecurePass123!" +} +``` + +#### Verification Process +1. **Initial Registration**: Basic business information collection +2. **Document Upload**: Tax ID and business license verification +3. **Admin Review**: Manual verification by platform administrators +4. **Status Updates**: Real-time verification status updates + +### Admin Management Features +- **User Oversight**: Manage all customers and service providers +- **Platform Analytics**: Comprehensive platform usage statistics +- **Content Moderation**: Review and moderate user-generated content +- **System Configuration**: Manage platform settings and categories + +## 🛍️ Service Marketplace + +### Service Creation & Management + +#### Advanced Service Features +```typescript +// Service creation with rich metadata +POST /api/v1/services +{ + "service_name": "Premium House Cleaning", + "description": "Professional deep cleaning service", + "base_price": 150.00, + "categories": ["cleaning", "home-services"], + "service_attributes": { + "duration": "3-4 hours", + "equipment_included": true, + "eco_friendly": true, + "insurance_covered": true + }, + "images": ["image1.jpg", "image2.jpg"] +} +``` + +#### Service Discovery Features +- **Category-based Browsing**: Organized service categories +- **Search Functionality**: Advanced search with filters +- **Provider Filtering**: Find services by specific providers +- **Geographic Search**: Location-based service discovery +- **Price Range Filtering**: Budget-based service selection + +### Image Management System +```typescript +// Cloudinary integration for professional image handling +const uploadResults = await Promise.all( + files.map(file => + this.cloudinary.uploadFile(file, { + folder: 'ServiceSphere', + transformation: [ + { width: 800, height: 600, crop: 'fill' }, + { quality: 'auto' }, + { format: 'webp' } + ] + }) + ) +); +``` + +### Category Management +- **Dynamic Categories**: Admin-managed service categories +- **Hierarchical Structure**: Support for subcategories +- **Category Analytics**: Popular categories and trends + +## 📅 Booking Management + +### Comprehensive Booking System + +#### Booking Lifecycle +```mermaid +graph LR + A[Customer Books] --> B[Pending Status] + B --> C[Provider Confirms] + C --> D[Service Delivery] + D --> E[Completion] + E --> F[Feedback Collection] +``` + +#### Booking Features +```typescript +// Create booking with automatic notifications +POST /api/v1/bookings/:serviceId +{ + "preferred_date": "2024-07-15T10:00:00Z", + "special_instructions": "Please bring eco-friendly supplies" +} + +// Automatic response with booking details +{ + "status": "success", + "data": { + "booking_id": "booking_123", + "status": "pending", + "service": { /* service details */ }, + "provider": { /* provider info */ }, + "estimated_completion": "2024-07-15T14:00:00Z" + } +} +``` + +### Status Management System +- **Pending**: Initial booking state awaiting provider confirmation +- **Confirmed**: Provider has accepted the booking +- **In Progress**: Service is currently being delivered +- **Completed**: Service has been finished +- **Cancelled**: Booking was cancelled by either party + +### Provider Booking Management +```typescript +// Providers can view and manage their bookings +GET /api/v1/bookings/provider +// Returns all bookings for the authenticated provider + +PATCH /api/v1/bookings/:id/status +{ + "status": "confirmed", + "estimated_start_time": "2024-07-15T10:00:00Z" +} +``` + +## 💬 Real-time Communication + +### WebSocket-Based Chat System + +#### Secure Chat Access +```typescript +// Chat access tied to active bookings +@SubscribeMessage('joinBookingRoom') +async handleJoinRoom(client: Socket, payload: JoinRoomDto) { + // Validate user has access to this booking + const { booking, providerId } = await this.chatService.validateUserAccess( + payload.userId, + payload.bookingId + ); + + // Only allow chat for active bookings + if (['completed', 'cancelled'].includes(booking.status)) { + throw new ForbiddenException('Chat is closed for this booking'); + } + + client.join(`booking-${payload.bookingId}`); +} +``` + +#### Real-time Features +- **Instant Messaging**: Real-time message delivery +- **Message Persistence**: All messages stored for history +- **Online Status**: Real-time user presence indicators +- **Typing Indicators**: Enhanced user experience +- **Message Read Receipts**: Delivery confirmation + +### Chat Security & Privacy +- **Booking-Specific**: Chats are isolated to individual bookings +- **Access Control**: Only booking participants can access chat +- **Message Encryption**: Secure message transmission +- **Chat History**: Complete conversation history for reference + +## ⭐ Feedback & Rating System + +### AI-Powered Sentiment Analysis + +#### Advanced Feedback Processing +```typescript +// Automatic sentiment analysis on feedback submission +async create(createFeedbackDto: CreateFeedbackDto, userId: string) { + // Analyze sentiment of the review text + const sentimentResult = await this.sentimentAnalysisService.analyzeSentiment( + createFeedbackDto.review_text + ); + + const feedback = new this.feedbackModel({ + ...createFeedbackDto, + user: userId, + sentiment_score: sentimentResult.score, + sentiment_magnitude: sentimentResult.magnitude, + created_at: new Date() + }); + + return feedback.save(); +} +``` + +#### Rating System Features +- **5-Star Rating**: Numerical rating system +- **Detailed Reviews**: Text-based feedback +- **Sentiment Analysis**: AI-powered sentiment scoring +- **Provider Ratings**: Aggregate rating calculations +- **Review Moderation**: Admin oversight for inappropriate content + +### Review Management +```typescript +// Comprehensive feedback endpoints +GET /api/v1/feedback/service/:id // All reviews for a service +GET /api/v1/feedback/provider/:id // All reviews for a provider +POST /api/v1/feedback // Submit new feedback +DELETE /api/v1/feedback/:id // Delete own feedback (or admin) +``` + +## 📧 Notification System + +### Multi-Channel Notifications + +#### Email Notifications +```typescript +// Professional email templates with Handlebars +await this.mailService.sendBookingConfirmation( + customer.email, + customer.first_name, + { + bookingId: booking._id, + serviceName: service.service_name, + providerName: provider.business_name, + scheduledDate: booking.scheduled_date, + totalAmount: booking.total_amount + } +); +``` + +#### Notification Types +- **Welcome Emails**: New user onboarding +- **Booking Confirmations**: Booking status updates +- **Payment Notifications**: Transaction confirmations +- **Verification Emails**: Account verification +- **Password Reset**: Secure password recovery +- **Provider Alerts**: New booking notifications + +### Email Template System +- **Handlebars Templates**: Dynamic content rendering +- **Brand Consistency**: Professional email design +- **Responsive Design**: Mobile-optimized emails +- **Personalization**: User-specific content + +## 🔧 Administrative Features + +### Comprehensive Admin Panel + +#### User Management +```typescript +// Admin-only endpoints for user management +GET /api/v1/users/customers // List all customers +GET /api/v1/users/service-providers // List all providers +PATCH /api/v1/users/:id // Update any user +DELETE /api/v1/users/:id // Remove users +``` + +#### Platform Analytics +- **User Statistics**: Registration and activity metrics +- **Booking Analytics**: Platform usage and revenue data +- **Service Performance**: Popular services and categories +- **Provider Verification**: Manage verification queue + +#### Content Moderation +- **Review Moderation**: Flag inappropriate reviews +- **Service Approval**: Review new service listings +- **User Verification**: Manual user verification process +- **Category Management**: Add/edit service categories + +### Admin Security Features +- **API Key Protection**: Secure admin registration +- **Audit Logging**: Track administrative actions +- **Role Separation**: Clear admin vs. user boundaries + +## 🔗 Integration Features + +### Third-Party Service Integration + +#### Cloudinary Integration +```typescript +// Professional image management +const uploadResult = await this.cloudinary.uploadFile(file, { + folder: 'ServiceSphere', + transformation: [ + { width: 800, height: 600, crop: 'fill' }, + { quality: 'auto:best' }, + { format: 'webp' } + ] +}); +``` + +#### Email Service Integration +- **SMTP Configuration**: Professional email delivery +- **Template Engine**: Dynamic email content +- **Delivery Tracking**: Email delivery confirmation +- **Bounce Handling**: Failed delivery management + +### Database Integration +- **MongoDB**: Scalable NoSQL database +- **Mongoose ODM**: Object document mapping +- **Index Optimization**: Performance-optimized queries +- **Data Validation**: Schema-level validation + +## 📊 Analytics & Reporting + +### Business Intelligence Features +- **Booking Trends**: Track booking patterns and seasonality +- **Revenue Analytics**: Platform revenue and commission tracking +- **User Engagement**: User activity and retention metrics +- **Service Performance**: Popular services and provider rankings + +### Performance Monitoring +- **Response Time Tracking**: API performance monitoring +- **Error Rate Monitoring**: System health tracking +- **User Behavior Analytics**: Platform usage patterns +- **Conversion Tracking**: Booking success rates + +## 🚀 Technical Excellence + +### Code Quality Features +- **TypeScript**: Type-safe development +- **Clean Architecture**: SOLID principles implementation +- **Comprehensive Testing**: Unit and integration tests +- **Documentation**: Extensive code documentation +- **Error Handling**: Graceful error management + +### Performance Optimization +- **Database Indexing**: Optimized query performance +- **Caching Strategy**: Redis-based caching +- **Image Optimization**: Automated image processing +- **Load Balancing**: Horizontal scaling support + +--- + +This feature documentation demonstrates: + +- **Full-Stack Capability**: Complete backend system development +- **Real-World Application**: Production-ready features +- **Technical Depth**: Advanced implementation details +- **Business Value**: Clear value propositions for users +- **Scalability**: Enterprise-grade architecture +- **Security**: Comprehensive security implementation diff --git a/README.md b/README.md index 72136e3..c1fb44b 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,333 @@ -## Running the Application with Docker Compose +# 🌟 Service Sphere - Professional Service Marketplace Platform -Follow these steps to build and run the application using Docker Compose. +[![NestJS](https://img.shields.io/badge/NestJS-E0234E?style=flat&logo=nestjs&logoColor=white)](https://nestjs.com/) +[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?style=flat&logo=typescript&logoColor=white)](https://www.typescriptlang.org/) +[![MongoDB](https://img.shields.io/badge/MongoDB-4EA94B?style=flat&logo=mongodb&logoColor=white)](https://www.mongodb.com/) +[![Docker](https://img.shields.io/badge/Docker-2496ED?style=flat&logo=docker&logoColor=white)](https://www.docker.com/) +[![JWT](https://img.shields.io/badge/JWT-000000?style=flat&logo=jsonwebtokens&logoColor=white)](https://jwt.io/) -### Clone the Repository +> **A comprehensive full-stack service marketplace platform connecting customers with service providers through real-time communication, booking management, and intelligent feedback systems.** -First, clone the repository to your local machine: +## 🎯 Project Overview +Service Sphere is a sophisticated service marketplace backend built with **NestJS** and **TypeScript**, designed to connect customers with service providers seamlessly. The platform features role-based authentication, real-time chat, booking management, and AI-powered sentiment analysis for feedback. + +### 🏆 Key Achievements +- **Clean Architecture**: Modular design with separation of concerns +- **Real-time Communication**: WebSocket implementation for instant messaging +- **Security-First**: JWT authentication with refresh tokens and role-based access control +- **Scalable Design**: Microservices-ready architecture with Docker containerization +- **Test Coverage**: Comprehensive testing with Jest (coverage reports available) + +## ✨ Core Features + +### 🔐 Authentication & Authorization +- **Multi-role system**: Customers, Service Providers, and Admins +- **JWT-based authentication** with refresh token rotation +- **Email verification** with OTP system +- **Password reset** functionality with secure token generation +- **Role-based access control** (RBAC) for endpoints + +### 👥 User Management +- **Customer profiles** with image upload capabilities +- **Service provider verification** system with business validation +- **Admin panel** for user management and platform oversight +- **Profile image management** with Cloudinary integration + +### 🛍️ Service Management +- **Service creation and management** by providers +- **Category-based organization** with dynamic categorization +- **Image upload and management** for service listings +- **Service search and filtering** capabilities +- **Provider rating and review** system + +### 📅 Booking System +- **Real-time booking management** with status tracking +- **Automated notifications** for booking updates +- **Provider-customer communication** through platform +- **Booking history and analytics** + +### 💬 Real-time Communication +- **WebSocket-based chat system** for booking-specific conversations +- **Real-time message delivery** with Socket.IO +- **Secure chat access** tied to active bookings +- **Message history and persistence** + +### 📊 Feedback & Analytics +- **AI-powered sentiment analysis** for customer feedback +- **Rating and review system** with detailed feedback +- **Service provider performance metrics** +- **Automated feedback categorization** + +### 📧 Email Services +- **Transactional email system** with Nodemailer +- **Custom email templates** with Handlebars +- **Welcome emails, verification, and password reset** +- **Booking confirmation and status updates** + +### 🏗️ Technical Architecture +- **Clean Architecture** with dependency injection +- **MongoDB** with Mongoose ODM for data persistence +- **Cloudinary** integration for media management +- **Docker containerization** for deployment +- **Global exception handling** with standardized responses +- **Input validation** with class-validator +- **Logging and monitoring** with Morgan + +## 🚀 Technology Stack + +### Backend Framework +- **NestJS** - Progressive Node.js framework +- **TypeScript** - Type-safe JavaScript development +- **Express** - Web application framework + +### Database & Storage +- **MongoDB** - NoSQL database with Mongoose ODM +- **Cloudinary** - Cloud-based image and video management + +### Authentication & Security +- **JWT** - JSON Web Tokens for stateless authentication +- **bcrypt** - Password hashing +- **Passport** - Authentication middleware + +### Real-time Communication +- **Socket.IO** - Real-time bidirectional event-based communication +- **WebSocket Gateway** - NestJS WebSocket implementation + +### Email & Notifications +- **Nodemailer** - Email sending capabilities +- **Handlebars** - Email template engine + +### Development & Deployment +- **Docker** - Containerization platform +- **Jest** - Testing framework +- **ESLint & Prettier** - Code quality and formatting + +## 🏃‍♂️ Quick Start + +### Prerequisites +- Node.js (v16+ recommended) +- Docker & Docker Compose +- MongoDB (or use Docker setup) + +### Installation & Setup + +1. **Clone the Repository** ```bash git clone git@github.com:Service-Sphere-GP/backend.git cd backend ``` -### Set Up Environment Variables - -Ensure that the `.env.test.local` file is present in the project root and correctly configured. +2. **Environment Configuration** +```bash +# Copy environment template +cp .env.example .env.development.local +# Configure your environment variables +``` -### Build and Run the Application +3. **Docker Deployment (Recommended)** +```bash +# Build and start all services +docker-compose up --build -Use Docker Compose to build and run the application: +# Run in background +docker-compose up -d +``` +4. **Local Development** ```bash -docker-compose up --build +# Install dependencies +npm install + +# Start development server +npm run start:dev + +# Run tests +npm run test +npm run test:cov ``` -This command will: +### 🌐 API Access +- **Base URL**: `http://localhost:3000/api/v1` +- **Documentation**: Available through Swagger/OpenAPI (if configured) + +## 📁 Project Structure -- Build the Docker images for the application and MongoDB. -- Start the services defined in `docker-compose.yml`. -- Set up the necessary environment variables inside the containers. +``` +src/ +├── auth/ # Authentication & authorization +├── users/ # User management (customers, providers, admins) +├── services/ # Service listings and management +├── service-bookings/ # Booking system and workflow +├── chat/ # Real-time messaging system +├── feedback/ # Review and rating system +├── notifications/ # Push notification system +├── mail/ # Email service and templates +├── categories/ # Service categorization +├── advice/ # Advisory system +├── config/ # Application configuration +├── common/ # Shared utilities and decorators +└── main.ts # Application entry point +``` -### Access the Application +## 🧪 Testing & Quality -Once the containers are up and running, you can access the application at: +```bash +# Run unit tests +npm run test -- **URL**: `http://localhost:3000` +# Run tests with coverage +npm run test:cov ---- +# Run e2e tests +npm run test:e2e -## Stopping the Application +# Lint code +npm run lint -To stop the application and remove the containers, run: +# Format code +npm run format +``` + +## 🚢 Deployment +### Docker Production Setup ```bash -docker-compose down +# Production build +docker-compose -f docker-compose.prod.yml up -d + +# Scale services +docker-compose up --scale app=3 +``` + +### Environment Variables +```env +# Database +DATABASE_URI=mongodb://localhost:27017/service-sphere + +# JWT Configuration +JWT_SECRET=your-super-secret-key +JWT_ACCESS_TOKEN_EXPIRATION_TIME=15m +JWT_REFRESH_TOKEN_EXPIRATION_TIME=7d + +# Email Configuration +SMTP_HOST=your-smtp-host +SMTP_PORT=587 +SMTP_USER=your-email@domain.com +SMTP_PASS=your-app-password + +# Cloudinary +CLOUDINARY_CLOUD_NAME=your-cloud-name +CLOUDINARY_API_KEY=your-api-key +CLOUDINARY_API_SECRET=your-api-secret + +# Application +APP_PORT=3000 +NODE_ENV=production ``` -This will stop and remove the containers, networks, and volumes defined in `docker-compose.yml`. +## 📈 Performance Features + +- **Connection pooling** for database optimization +- **Image optimization** with Cloudinary transformations +- **Caching strategies** for frequently accessed data +- **Rate limiting** for API protection +- **Request logging** for monitoring and debugging + +## 🔒 Security Implementation + +- **Input validation** and sanitization +- **SQL injection** prevention with parameterized queries +- **XSS protection** with helmet middleware +- **CORS configuration** for cross-origin requests +- **Rate limiting** to prevent abuse +- **Secure headers** implementation + +## 📚 API Documentation + +### Authentication Endpoints +``` +POST /api/v1/auth/register/customer +POST /api/v1/auth/register/service-provider +POST /api/v1/auth/login +POST /api/v1/auth/refresh +POST /api/v1/auth/logout +POST /api/v1/auth/forgot-password +PATCH /api/v1/auth/reset-password/:token +``` + +### Service Management +``` +GET /api/v1/services +POST /api/v1/services +GET /api/v1/services/:id +PATCH /api/v1/services/:id +DELETE /api/v1/services/:id +GET /api/v1/services/provider/:providerId +``` + +### Booking System +``` +POST /api/v1/bookings/:serviceId +GET /api/v1/bookings +GET /api/v1/bookings/provider +PATCH /api/v1/bookings/:id/status +GET /api/v1/bookings/:id +``` + +## 👨‍💻 Development Highlights + +### Design Patterns Implemented +- **Repository Pattern** for data access abstraction +- **Dependency Injection** for loose coupling +- **Observer Pattern** for event-driven notifications +- **Strategy Pattern** for multiple authentication methods +- **Factory Pattern** for service creation + +### Best Practices Applied +- **SOLID Principles** in class design +- **Clean Code** principles throughout +- **Error handling** with custom exception filters +- **Logging** for debugging and monitoring +- **Code documentation** and type safety + +## 🤝 Contributing + +This project demonstrates enterprise-level backend development practices and is suitable for: +- **Portfolio demonstration** +- **Technical interviews** +- **Learning NestJS and TypeScript** +- **Understanding microservices architecture** + +## 📄 License + +This project is developed as part of a graduation project and is available for educational and portfolio purposes. + +--- + +## 🎓 Academic Project Information + +**Project Type**: Graduation Project +**Framework**: NestJS with TypeScript +**Database**: MongoDB +**Architecture**: Microservices-ready monolith +**Development Period**: [Your timeline] +**Team Size**: [Team size if applicable] + +### Skills Demonstrated +- Advanced TypeScript and NestJS development +- RESTful API design and implementation +- Real-time communication with WebSockets +- Database design and optimization +- Authentication and authorization systems +- Cloud services integration +- Docker containerization +- Test-driven development --- +**⭐ Star this repository if you find it helpful for your learning journey!** + ## Running the Application in Development Mode (Without Docker) If you prefer to run the application without Docker for development purposes, follow these steps: diff --git a/package.json b/package.json index 7545e2d..55fabc4 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,29 @@ { - "name": "backend", - "version": "0.0.1", - "description": "", - "author": "", + "name": "service-sphere-backend", + "version": "1.0.0", + "description": "Professional service marketplace platform backend - A comprehensive NestJS application for connecting customers with service providers through real-time communication and intelligent booking management", + "author": "Hussein Hany ", "private": true, - "license": "UNLICENSED", + "license": "MIT", + "keywords": [ + "nestjs", + "typescript", + "service-marketplace", + "booking-system", + "real-time-chat", + "jwt-authentication", + "mongodb", + "websocket", + "graduation-project" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/Service-Sphere-GP/backend.git" + }, + "bugs": { + "url": "https://github.com/Service-Sphere-GP/backend/issues" + }, + "homepage": "https://github.com/Service-Sphere-GP/backend#readme", "scripts": { "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", From aa5b17e3f611587b7f37f564d055819b426f3a47 Mon Sep 17 00:00:00 2001 From: Hussein Saad Date: Wed, 9 Jul 2025 05:44:24 +0300 Subject: [PATCH 2/8] Update README.md --- README.md | 31 ++++--------------------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index c1fb44b..10bc233 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,6 @@ Service Sphere is a sophisticated service marketplace backend built with **NestJ - **Real-time Communication**: WebSocket implementation for instant messaging - **Security-First**: JWT authentication with refresh tokens and role-based access control - **Scalable Design**: Microservices-ready architecture with Docker containerization -- **Test Coverage**: Comprehensive testing with Jest (coverage reports available) ## ✨ Core Features @@ -63,7 +62,6 @@ Service Sphere is a sophisticated service marketplace backend built with **NestJ - **Transactional email system** with Nodemailer - **Custom email templates** with Handlebars - **Welcome emails, verification, and password reset** -- **Booking confirmation and status updates** ### 🏗️ Technical Architecture - **Clean Architecture** with dependency injection @@ -137,14 +135,14 @@ docker-compose up -d 4. **Local Development** ```bash # Install dependencies -npm install +yarn install # Start development server -npm run start:dev +yarn run start:dev # Run tests -npm run test -npm run test:cov +yarn run test +yarn run test:cov ``` ### 🌐 API Access @@ -170,25 +168,6 @@ src/ └── main.ts # Application entry point ``` -## 🧪 Testing & Quality - -```bash -# Run unit tests -npm run test - -# Run tests with coverage -npm run test:cov - -# Run e2e tests -npm run test:e2e - -# Lint code -npm run lint - -# Format code -npm run format -``` - ## 🚢 Deployment ### Docker Production Setup @@ -311,8 +290,6 @@ This project is developed as part of a graduation project and is available for e **Framework**: NestJS with TypeScript **Database**: MongoDB **Architecture**: Microservices-ready monolith -**Development Period**: [Your timeline] -**Team Size**: [Team size if applicable] ### Skills Demonstrated - Advanced TypeScript and NestJS development From 5f53697068c655b48de03aeb61fbad948892ad03 Mon Sep 17 00:00:00 2001 From: Hussein Saad Date: Mon, 14 Jul 2025 11:47:19 +0300 Subject: [PATCH 3/8] feat: remove admin user creation guide from documentation --- docs/admin-creation.md | 119 ----------------------------------------- 1 file changed, 119 deletions(-) delete mode 100644 docs/admin-creation.md diff --git a/docs/admin-creation.md b/docs/admin-creation.md deleted file mode 100644 index 8d10e4e..0000000 --- a/docs/admin-creation.md +++ /dev/null @@ -1,119 +0,0 @@ -# Admin User Creation Guide - -This document explains how to create admin users in your application. - -## Creating the First Admin User - -When your application is first deployed and there are no admin users in the system, you can create the first admin user using the following endpoint: - -``` -POST /auth/register/first-admin -``` - -Example request body: - -```json -{ - "first_name": "Admin", - "last_name": "User", - "email": "admin@example.com", - "password": "securePassword123", - "confirm_password": "securePassword123", - "permissions": ["manage_users", "manage_services", "manage_all"] -} -``` - -This endpoint will only work when there are no existing admin users in the system. Once the first admin is created, this endpoint will return a 403 error. - -## Creating Additional Admin Users - -After the first admin is created, there are two ways to create additional admin users: - -### 1. Using the API Key Authentication - -You can create additional admin users by using the following endpoint with an API key: - -``` -POST /auth/register/admin -``` - -This endpoint requires an API key to be provided in the `x-api-key` header. The API key should be set in the `ADMIN_API_KEY` environment variable. - -Example request: - -```bash -curl -X POST \ - http://your-api.com/auth/register/admin \ - -H 'Content-Type: application/json' \ - -H 'x-api-key: your-api-key-here' \ - -d '{ - "first_name": "Another", - "last_name": "Admin", - "email": "another.admin@example.com", - "password": "securePassword456", - "confirm_password": "securePassword456", - "permissions": ["manage_users", "manage_services"] - }' -``` - -### 2. Using Admin Authentication - -Existing admin users can create new admin users through the admin interface using the following endpoint: - -``` -POST /users/admins -``` - -This endpoint requires JWT authentication with an admin role. - -Example request: - -```bash -curl -X POST \ - http://your-api.com/users/admins \ - -H 'Content-Type: application/json' \ - -H 'Authorization: Bearer your-admin-jwt-token' \ - -d '{ - "first_name": "New", - "last_name": "Admin", - "email": "new.admin@example.com", - "password": "securePassword789", - "confirm_password": "securePassword789", - "permissions": ["manage_users"] - }' -``` - -## Security Considerations - -- Set a strong, unique value for the `ADMIN_API_KEY` environment variable -- Keep your API key secure and only share it with authorized personnel -- Use HTTPS for all API requests to prevent interception of sensitive data -- Regularly rotate your API key for enhanced security -- Consider implementing IP whitelisting for admin creation endpoints -- Monitor admin creation activities for any suspicious behavior - -## Environment Variables - -Make sure to set the following environment variables: - -- `ADMIN_API_KEY`: A secure random string used for API key authentication - -Example: - -```bash -# Linux/macOS -export ADMIN_API_KEY="your-secure-random-api-key" - -# Windows -set ADMIN_API_KEY=your-secure-random-api-key -``` - -You can generate a secure random API key using a command like: - -```bash -# Linux/macOS -openssl rand -hex 32 - -# Node.js -node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" -``` \ No newline at end of file From e207904795c09897f103ef282d4fa0349c9699c8 Mon Sep 17 00:00:00 2001 From: Hussein Saad Date: Mon, 14 Jul 2025 12:31:56 +0300 Subject: [PATCH 4/8] feat: Update README.md --- README.md | 381 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 296 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index 10bc233..62350f0 100644 --- a/README.md +++ b/README.md @@ -5,172 +5,314 @@ [![MongoDB](https://img.shields.io/badge/MongoDB-4EA94B?style=flat&logo=mongodb&logoColor=white)](https://www.mongodb.com/) [![Docker](https://img.shields.io/badge/Docker-2496ED?style=flat&logo=docker&logoColor=white)](https://www.docker.com/) [![JWT](https://img.shields.io/badge/JWT-000000?style=flat&logo=jsonwebtokens&logoColor=white)](https://jwt.io/) +[![Socket.IO](https://img.shields.io/badge/Socket.IO-010101?style=flat&logo=socketdotio&logoColor=white)](https://socket.io/) -> **A comprehensive full-stack service marketplace platform connecting customers with service providers through real-time communication, booking management, and intelligent feedback systems.** +> **A comprehensive service marketplace backend platform connecting customers with service providers through real-time communication, intelligent booking management, and sentiment-based feedback systems.** ## 🎯 Project Overview Service Sphere is a sophisticated service marketplace backend built with **NestJS** and **TypeScript**, designed to connect customers with service providers seamlessly. The platform features role-based authentication, real-time chat, booking management, and AI-powered sentiment analysis for feedback. ### 🏆 Key Achievements -- **Clean Architecture**: Modular design with separation of concerns -- **Real-time Communication**: WebSocket implementation for instant messaging -- **Security-First**: JWT authentication with refresh tokens and role-based access control + +- **Clean Architecture**: Modular design with separation of concerns and domain-driven design +- **Real-time Communication**: WebSocket implementation for instant messaging between users +- **Security-First**: JWT authentication with refresh tokens and comprehensive role-based access control - **Scalable Design**: Microservices-ready architecture with Docker containerization +- **AI Integration**: Sentiment analysis for customer feedback classification ## ✨ Core Features ### 🔐 Authentication & Authorization -- **Multi-role system**: Customers, Service Providers, and Admins -- **JWT-based authentication** with refresh token rotation -- **Email verification** with OTP system -- **Password reset** functionality with secure token generation -- **Role-based access control** (RBAC) for endpoints + +- **Multi-role system**: Customers, Service Providers, and Admins with discriminator-based schemas +- **JWT-based authentication** with refresh token rotation and secure token management +- **Email verification** with OTP system (6-digit codes, 15-minute expiration) +- **Password reset** functionality with secure token generation and deep linking support +- **Role-based access control** (RBAC) for all endpoints with guard protection ### 👥 User Management -- **Customer profiles** with image upload capabilities -- **Service provider verification** system with business validation -- **Admin panel** for user management and platform oversight -- **Profile image management** with Cloudinary integration + +- **Customer profiles** with loyalty points and activity tracking +- **Service provider verification** system with business validation and tax ID verification +- **Admin panel** for comprehensive user management and platform oversight +- **Profile image management** with Cloudinary integration and automatic optimization +- **User status management** (active, suspended) with proper lifecycle handling ### 🛍️ Service Management -- **Service creation and management** by providers -- **Category-based organization** with dynamic categorization -- **Image upload and management** for service listings -- **Service search and filtering** capabilities -- **Provider rating and review** system + +- **Service creation and management** by verified providers with rich metadata +- **Category-based organization** with dynamic categorization system +- **Image upload and management** for service listings with automatic optimization +- **Service search and filtering** capabilities across multiple criteria +- **Provider rating and review** system with sentiment analysis +- **Service attributes** for detailed service customization ### 📅 Booking System -- **Real-time booking management** with status tracking -- **Automated notifications** for booking updates -- **Provider-customer communication** through platform -- **Booking history and analytics** + +- **Real-time booking management** with comprehensive status tracking +- **Automated notifications** for booking updates through WebSocket and email +- **Provider-customer communication** through secure platform chat +- **Booking history and analytics** with detailed lifecycle management +- **Status workflow**: pending → confirmed → completed/cancelled ### 💬 Real-time Communication + - **WebSocket-based chat system** for booking-specific conversations -- **Real-time message delivery** with Socket.IO -- **Secure chat access** tied to active bookings -- **Message history and persistence** +- **Real-time message delivery** with Socket.IO and proper authentication +- **Secure chat access** tied to active bookings with user validation +- **Message history and persistence** with MongoDB storage +- **Real-time notifications** for instant user engagement ### 📊 Feedback & Analytics -- **AI-powered sentiment analysis** for customer feedback -- **Rating and review system** with detailed feedback -- **Service provider performance metrics** -- **Automated feedback categorization** -### 📧 Email Services -- **Transactional email system** with Nodemailer -- **Custom email templates** with Handlebars -- **Welcome emails, verification, and password reset** +- **AI-powered sentiment analysis** for automatic feedback classification +- **Rating and review system** with 1-5 star ratings and detailed comments +- **Service provider performance metrics** with aggregated statistics +- **Automated feedback categorization** (positive, negative, neutral) +- **Booking analytics** and provider performance tracking + +### 📧 Email & Notification Services + +- **Transactional email system** with Nodemailer and SMTP support +- **Custom email templates** with Handlebars template engine +- **Welcome emails, verification, and password reset** with deep linking +- **Real-time push notifications** through WebSocket connections +- **Notification management** with read/unread status tracking ### 🏗️ Technical Architecture -- **Clean Architecture** with dependency injection -- **MongoDB** with Mongoose ODM for data persistence -- **Cloudinary** integration for media management -- **Docker containerization** for deployment -- **Global exception handling** with standardized responses -- **Input validation** with class-validator -- **Logging and monitoring** with Morgan + +- **Clean Architecture** with dependency injection and modular design +- **MongoDB** with Mongoose ODM for robust data persistence +- **Cloudinary** integration for professional media management +- **Docker containerization** for consistent deployment environments +- **Global exception handling** with standardized JSend response format +- **Input validation** with class-validator and transformation pipes +- **Comprehensive logging** with Morgan middleware and custom loggers +- **Environment-based configuration** with Joi validation schemas ## 🚀 Technology Stack ### Backend Framework + - **NestJS** - Progressive Node.js framework - **TypeScript** - Type-safe JavaScript development - **Express** - Web application framework ### Database & Storage + - **MongoDB** - NoSQL database with Mongoose ODM - **Cloudinary** - Cloud-based image and video management ### Authentication & Security -- **JWT** - JSON Web Tokens for stateless authentication -- **bcrypt** - Password hashing -- **Passport** - Authentication middleware + +- **JWT** - JSON Web Tokens for stateless authentication with RS256 algorithm +- **bcrypt** - Password hashing with salt rounds (10) +- **Passport** - Authentication middleware with JWT strategy +- **OTP System** - 6-digit verification codes with 15-minute expiration +- **Role Guards** - Decorator-based role protection (@Roles) ### Real-time Communication + - **Socket.IO** - Real-time bidirectional event-based communication -- **WebSocket Gateway** - NestJS WebSocket implementation +- **WebSocket Gateway** - NestJS WebSocket implementation with authentication +- **Chat System** - Booking-specific messaging with message persistence +- **Real-time Notifications** - Instant push notifications for user actions ### Email & Notifications -- **Nodemailer** - Email sending capabilities -- **Handlebars** - Email template engine + +- **Nodemailer** - SMTP email sending capabilities with template support +- **Handlebars** - Email template engine for dynamic content +- **Notification System** - In-app notifications with read/unread status +- **Push Notifications** - Real-time user engagement through WebSocket ### Development & Deployment -- **Docker** - Containerization platform -- **Jest** - Testing framework -- **ESLint & Prettier** - Code quality and formatting -## 🏃‍♂️ Quick Start +- **Docker** - Multi-stage containerization with optimized production builds +- **Jest** - Comprehensive testing framework with coverage reports +- **ESLint & Prettier** - Code quality and consistent formatting +- **Yarn** - Fast and reliable package management +- **Morgan** - HTTP request logging middleware + +## 🚀 Quick Start ### Prerequisites -- Node.js (v16+ recommended) -- Docker & Docker Compose -- MongoDB (or use Docker setup) -### Installation & Setup +- **Node.js** v18+ +- **Yarn** package manager +- **MongoDB** 4.4+ +- **Docker** & Docker Compose (optional) + +### Environment Setup + +1. **Clone the repository** -1. **Clone the Repository** ```bash -git clone git@github.com:Service-Sphere-GP/backend.git +git clone https://github.com/Service-Sphere-GP/backend.git cd backend ``` -2. **Environment Configuration** +2. **Install dependencies** + ```bash -# Copy environment template +yarn install +``` + +3. **Configure environment variables** + +```bash +# Create environment file cp .env.example .env.development.local -# Configure your environment variables + +# Required environment variables: +MONGODB_URI=mongodb://localhost:27017/service-sphere-dev +JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters +JWT_ACCESS_TOKEN_EXPIRATION_TIME=15m +JWT_REFRESH_TOKEN_EXPIRATION_TIME=7d + +# Email configuration (SMTP) +MAIL_HOST=smtp.gmail.com +MAIL_PORT=587 +MAIL_USER=your-email@gmail.com +MAIL_PASSWORD=your-app-password +MAIL_FROM_NAME="Service Sphere" +MAIL_FROM_ADDRESS=noreply@servicesphere.com + +# Cloudinary configuration +CLOUDINARY_CLOUD_NAME=your-cloud-name +CLOUDINARY_API_KEY=your-api-key +CLOUDINARY_API_SECRET=your-api-secret + +# Optional configurations +PORT=3000 +CORS_ORIGIN=* +ADMIN_API_KEY=your-secure-admin-api-key ``` -3. **Docker Deployment (Recommended)** +4. **Start the application** + +**Development mode:** + ```bash -# Build and start all services -docker-compose up --build +yarn start:dev +``` -# Run in background -docker-compose up -d +**Production mode:** + +```bash +yarn build +yarn start:prod ``` -4. **Local Development** +**With Docker:** + ```bash -# Install dependencies -yarn install +docker-compose up --build +``` + +5. **Verify installation** -# Start development server -yarn run start:dev +```bash +# Check if server is running +curl http://localhost:3000/api/v1 + +# Create first admin user +curl -X POST http://localhost:3000/api/v1/auth/register/first-admin \ + -H "Content-Type: application/json" \ + -d '{ + "first_name": "Admin", + "last_name": "User", + "email": "admin@example.com", + "password": "AdminPassword123!", + "confirm_password": "AdminPassword123!" + }' +``` # Run tests + +```bash yarn run test yarn run test:cov ``` ### 🌐 API Access + - **Base URL**: `http://localhost:3000/api/v1` -- **Documentation**: Available through Swagger/OpenAPI (if configured) ## 📁 Project Structure ``` src/ -├── auth/ # Authentication & authorization -├── users/ # User management (customers, providers, admins) -├── services/ # Service listings and management -├── service-bookings/ # Booking system and workflow -├── chat/ # Real-time messaging system -├── feedback/ # Review and rating system -├── notifications/ # Push notification system -├── mail/ # Email service and templates -├── categories/ # Service categorization -├── advice/ # Advisory system -├── config/ # Application configuration -├── common/ # Shared utilities and decorators -└── main.ts # Application entry point +├── app.module.ts # Root application module +├── main.ts # Application entry point +├── auth/ # Authentication & authorization +│ ├── auth.controller.ts # Auth endpoints (register, login, etc.) +│ ├── auth.service.ts # Authentication business logic +│ ├── guards/ # JWT and role-based guards +│ ├── strategies/ # Passport JWT strategy +│ ├── dto/ # Data transfer objects +│ └── schemas/ # Token schemas (refresh, reset) +├── users/ # User management +│ ├── users.controller.ts # User CRUD operations +│ ├── users.service.ts # User business logic +│ ├── schemas/ # User schemas with discriminators +│ │ ├── user.schema.ts # Base user schema +│ │ ├── customer.schema.ts # Customer-specific fields +│ │ ├── service-provider.schema.ts # Provider fields +│ │ └── admin.schema.ts # Admin permissions +│ └── dto/ # User DTOs for validation +├── services/ # Service marketplace +│ ├── services.controller.ts # Service CRUD operations +│ ├── services.service.ts # Service business logic +│ ├── schemas/ # Service data models +│ └── interfaces/ # Service type definitions +├── service-bookings/ # Booking management +│ ├── service-bookings.controller.ts # Booking endpoints +│ ├── service-bookings.service.ts # Booking logic +│ └── schemas/ # Booking data models +├── chat/ # Real-time communication +│ ├── chat.gateway.ts # WebSocket gateway +│ ├── chat.service.ts # Chat business logic +│ ├── guards/ # WebSocket JWT authentication +│ └── schemas/ # Message schemas +├── feedback/ # Review & rating system +│ ├── feedback.controller.ts # Feedback endpoints +│ ├── feedback.service.ts # Review logic +│ ├── sentiment-analysis.service.ts # AI sentiment analysis +│ └── schemas/ # Feedback data models +├── notifications/ # Notification system +│ ├── notifications.controller.ts # Notification endpoints +│ ├── notifications.service.ts # Notification logic +│ └── schemas/ # Notification schemas +├── categories/ # Service categorization +│ ├── categories.controller.ts # Category management +│ ├── categories.service.ts # Category logic +│ └── schemas/ # Category schemas +├── mail/ # Email services +│ ├── mail.service.ts # Email sending logic +│ ├── mail.module.ts # Email configuration +│ └── templates/ # Handlebars email templates +├── advice/ # Advisory system +│ ├── advice.controller.ts # Advice endpoints +│ ├── advice.service.ts # Advisory logic +│ └── schemas/ # Advice schemas +├── config/ # Configuration management +│ ├── app.config.ts # Application settings +│ ├── database.config.ts # MongoDB configuration +│ ├── mail.config.ts # SMTP settings +│ └── validation.schema.ts # Joi validation schemas +└── common/ # Shared utilities + ├── decorators/ # Custom decorators (@Roles, @CurrentUser) + ├── filters/ # Exception filters (JSend format) + ├── guards/ # Custom guards + ├── interceptors/ # Response interceptors + └── middleware/ # Custom middleware ``` ## 🚢 Deployment ### Docker Production Setup + ```bash # Production build docker-compose -f docker-compose.prod.yml up -d @@ -180,6 +322,7 @@ docker-compose up --scale app=3 ``` ### Environment Variables + ```env # Database DATABASE_URI=mongodb://localhost:27017/service-sphere @@ -225,27 +368,53 @@ NODE_ENV=production ## 📚 API Documentation ### Authentication Endpoints + ``` POST /api/v1/auth/register/customer POST /api/v1/auth/register/service-provider +POST /api/v1/auth/register/first-admin +POST /api/v1/auth/register/admin POST /api/v1/auth/login POST /api/v1/auth/refresh POST /api/v1/auth/logout +POST /api/v1/auth/verify-email/:userId +POST /api/v1/auth/resend-verification POST /api/v1/auth/forgot-password PATCH /api/v1/auth/reset-password/:token +GET /api/v1/auth/verification-status/:email +``` + +### User Management + +``` +GET /api/v1/users/customers +GET /api/v1/users/customers/:id +PATCH /api/v1/users/customers/:id +DELETE /api/v1/users/customers/:id +GET /api/v1/users/service-providers +GET /api/v1/users/service-providers/:id +PATCH /api/v1/users/service-providers/:id +DELETE /api/v1/users/service-providers/:id +GET /api/v1/users/admins +POST /api/v1/users/admins +GET /api/v1/users/:id ``` ### Service Management + ``` GET /api/v1/services POST /api/v1/services GET /api/v1/services/:id PATCH /api/v1/services/:id DELETE /api/v1/services/:id +GET /api/v1/services/my-services GET /api/v1/services/provider/:providerId +GET /api/v1/services/categories ``` ### Booking System + ``` POST /api/v1/bookings/:serviceId GET /api/v1/bookings @@ -254,9 +423,49 @@ PATCH /api/v1/bookings/:id/status GET /api/v1/bookings/:id ``` +### Real-time Chat (WebSocket) + +``` +WebSocket Events: +- joinRoom +- sendMessage +- subscribeToNotifications +- newMessage (incoming) +- messageDelivered (status) +``` + +### Feedback System + +``` +GET /api/v1/feedback/service/:serviceId +GET /api/v1/feedback/provider/:providerId +POST /api/v1/feedback +DELETE /api/v1/feedback/:id +``` + +### Notifications + +``` +GET /api/v1/notifications +GET /api/v1/notifications/unread +POST /api/v1/notifications/:id/read +POST /api/v1/notifications/read-all +DELETE /api/v1/notifications/:id +``` + +### Categories + +``` +GET /api/v1/categories +POST /api/v1/categories (Admin only) +PATCH /api/v1/categories/:id (Admin only) +DELETE /api/v1/categories/:id (Admin only) +``` + ## 👨‍💻 Development Highlights ### Design Patterns Implemented + - **Repository Pattern** for data access abstraction - **Dependency Injection** for loose coupling - **Observer Pattern** for event-driven notifications @@ -264,6 +473,7 @@ GET /api/v1/bookings/:id - **Factory Pattern** for service creation ### Best Practices Applied + - **SOLID Principles** in class design - **Clean Code** principles throughout - **Error handling** with custom exception filters @@ -273,6 +483,7 @@ GET /api/v1/bookings/:id ## 🤝 Contributing This project demonstrates enterprise-level backend development practices and is suitable for: + - **Portfolio demonstration** - **Technical interviews** - **Learning NestJS and TypeScript** @@ -289,9 +500,10 @@ This project is developed as part of a graduation project and is available for e **Project Type**: Graduation Project **Framework**: NestJS with TypeScript **Database**: MongoDB -**Architecture**: Microservices-ready monolith +**Architecture**: Microservices-ready monolith ### Skills Demonstrated + - Advanced TypeScript and NestJS development - RESTful API design and implementation - Real-time communication with WebSockets @@ -299,7 +511,6 @@ This project is developed as part of a graduation project and is available for e - Authentication and authorization systems - Cloud services integration - Docker containerization -- Test-driven development --- From 67366e9fae240431c021bcbcdcf846002c70330f Mon Sep 17 00:00:00 2001 From: Hussein Saad Date: Mon, 14 Jul 2025 12:36:19 +0300 Subject: [PATCH 5/8] feat: remove deployment guide --- DEPLOYMENT.md | 984 -------------------------------------------------- 1 file changed, 984 deletions(-) delete mode 100644 DEPLOYMENT.md diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md deleted file mode 100644 index dcc7225..0000000 --- a/DEPLOYMENT.md +++ /dev/null @@ -1,984 +0,0 @@ -# 🚀 Service Sphere - Deployment Guide - -## 📋 Table of Contents -- [Deployment Overview](#deployment-overview) -- [Development Environment](#development-environment) -- [Docker Deployment](#docker-deployment) -- [Production Deployment](#production-deployment) -- [Cloud Deployment](#cloud-deployment) -- [Environment Configuration](#environment-configuration) -- [Database Setup](#database-setup) -- [Monitoring & Logging](#monitoring--logging) -- [Security Considerations](#security-considerations) -- [Troubleshooting](#troubleshooting) - -## 🌐 Deployment Overview - -Service Sphere supports multiple deployment strategies, from local development to production-ready cloud deployments. This guide covers all deployment scenarios with step-by-step instructions. - -### Deployment Options -- **Development**: Local development with hot reload -- **Docker**: Containerized deployment for consistency -- **Production**: Optimized production deployment -- **Cloud**: AWS, Google Cloud, or Azure deployment -- **Kubernetes**: Container orchestration for scalability - -## 💻 Development Environment - -### Prerequisites -```bash -# Node.js (v18+ recommended) -node --version # Should be v18.0.0 or higher -npm --version # Should be v8.0.0 or higher - -# MongoDB (optional if using Docker) -mongod --version - -# Git -git --version -``` - -### Local Development Setup - -#### 1. Clone Repository -```bash -git clone git@github.com:Service-Sphere-GP/backend.git -cd backend -``` - -#### 2. Install Dependencies -```bash -# Install all dependencies -npm install - -# Install development dependencies -npm install --include=dev -``` - -#### 3. Environment Configuration -```bash -# Copy environment template -cp .env.example .env.development.local - -# Edit environment variables -nano .env.development.local -``` - -**Required Environment Variables:** -```env -# Database Configuration -DATABASE_URI=mongodb://localhost:27017/service-sphere-dev - -# JWT Configuration -JWT_SECRET=your-super-secret-development-key-here -JWT_ACCESS_TOKEN_EXPIRATION_TIME=15m -JWT_REFRESH_TOKEN_EXPIRATION_TIME=7d - -# Email Configuration (for development) -SMTP_HOST=smtp.gmail.com -SMTP_PORT=587 -SMTP_USER=your-dev-email@gmail.com -SMTP_PASS=your-app-password - -# Cloudinary Configuration -CLOUDINARY_CLOUD_NAME=your-cloudinary-name -CLOUDINARY_API_KEY=your-api-key -CLOUDINARY_API_SECRET=your-api-secret - -# Application Configuration -APP_PORT=3000 -NODE_ENV=development -CORS_ORIGIN=http://localhost:3001 -``` - -#### 4. Start Development Server -```bash -# Start with hot reload -npm run start:dev - -# Start with debug mode -npm run start:debug - -# Run tests during development -npm run test:watch -``` - -#### 5. Database Seeding (Optional) -```bash -# Seed with sample data -npm run seed - -# Seed with minimal data -npm run seed:minimal -``` - -### Development Tools -```bash -# Code formatting -npm run format - -# Linting -npm run lint - -# Type checking -npx tsc --noEmit - -# Test coverage -npm run test:cov -``` - -## 🐳 Docker Deployment - -### Docker Compose (Recommended for Development) - -#### 1. Basic Docker Setup -```yaml -# docker-compose.yml -version: '3.8' - -services: - app: - build: . - ports: - - "3000:3000" - environment: - - NODE_ENV=development - env_file: - - .env.development.local - depends_on: - - mongodb - volumes: - - .:/app - - /app/node_modules - command: npm run start:dev - - mongodb: - image: mongo:7 - ports: - - "27017:27017" - volumes: - - mongo_data:/data/db - environment: - - MONGO_INITDB_DATABASE=service-sphere - -volumes: - mongo_data: -``` - -#### 2. Start Docker Environment -```bash -# Build and start all services -docker-compose up --build - -# Run in background -docker-compose up -d - -# View logs -docker-compose logs -f app - -# Stop services -docker-compose down - -# Remove volumes (clean database) -docker-compose down -v -``` - -#### 3. Docker Development Commands -```bash -# Execute commands in running container -docker-compose exec app npm run test -docker-compose exec app npm run seed - -# Access MongoDB shell -docker-compose exec mongodb mongosh service-sphere - -# Rebuild specific service -docker-compose build app -``` - -### Production Docker Setup - -#### 1. Multi-stage Dockerfile -```dockerfile -# Multi-stage build for production -FROM node:18-alpine AS builder - -WORKDIR /app -COPY package*.json ./ -RUN npm ci --only=production && npm cache clean --force - -FROM node:18-alpine AS development -WORKDIR /app -COPY package*.json ./ -RUN npm ci -COPY . . -CMD ["npm", "run", "start:dev"] - -FROM node:18-alpine AS build -WORKDIR /app -COPY package*.json ./ -RUN npm ci -COPY . . -RUN npm run build - -FROM node:18-alpine AS production -WORKDIR /app -COPY package*.json ./ -RUN npm ci --only=production && npm cache clean --force -COPY --from=build /app/dist ./dist -EXPOSE 3000 -USER node -CMD ["node", "dist/main.js"] -``` - -#### 2. Production Docker Compose -```yaml -# docker-compose.prod.yml -version: '3.8' - -services: - app: - build: - context: . - target: production - ports: - - "3000:3000" - environment: - - NODE_ENV=production - env_file: - - .env.production.local - depends_on: - - mongodb - - redis - restart: unless-stopped - - mongodb: - image: mongo:7 - ports: - - "27017:27017" - volumes: - - mongo_data:/data/db - - ./mongo-init:/docker-entrypoint-initdb.d - environment: - - MONGO_INITDB_ROOT_USERNAME=admin - - MONGO_INITDB_ROOT_PASSWORD=secure_password - restart: unless-stopped - - redis: - image: redis:7-alpine - ports: - - "6379:6379" - volumes: - - redis_data:/data - restart: unless-stopped - - nginx: - image: nginx:alpine - ports: - - "80:80" - - "443:443" - volumes: - - ./nginx.conf:/etc/nginx/nginx.conf - - ./ssl:/etc/nginx/ssl - depends_on: - - app - restart: unless-stopped - -volumes: - mongo_data: - redis_data: -``` - -#### 3. Production Deployment -```bash -# Build production images -docker-compose -f docker-compose.prod.yml build - -# Start production environment -docker-compose -f docker-compose.prod.yml up -d - -# Scale application -docker-compose -f docker-compose.prod.yml up -d --scale app=3 - -# Health check -docker-compose -f docker-compose.prod.yml ps -``` - -## 🏭 Production Deployment - -### Server Requirements -- **CPU**: 2+ cores recommended -- **RAM**: 4GB minimum, 8GB recommended -- **Storage**: 20GB minimum SSD -- **Network**: Stable internet connection -- **OS**: Ubuntu 20.04+ or CentOS 8+ - -### Manual Production Setup - -#### 1. Server Preparation -```bash -# Update system -sudo apt update && sudo apt upgrade -y - -# Install Node.js 18 -curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - -sudo apt-get install -y nodejs - -# Install MongoDB -wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add - -echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list -sudo apt-get update -sudo apt-get install -y mongodb-org - -# Install PM2 for process management -sudo npm install -g pm2 - -# Install Nginx for reverse proxy -sudo apt install nginx -y -``` - -#### 2. Application Deployment -```bash -# Clone repository -git clone git@github.com:Service-Sphere-GP/backend.git -cd backend - -# Install dependencies -npm ci --only=production - -# Build application -npm run build - -# Set up environment -cp .env.example .env.production.local -# Edit .env.production.local with production values -``` - -#### 3. PM2 Process Management -```javascript -// ecosystem.config.js -module.exports = { - apps: [{ - name: 'service-sphere-api', - script: 'dist/main.js', - instances: 'max', - exec_mode: 'cluster', - env: { - NODE_ENV: 'production', - PORT: 3000 - }, - error_file: './logs/err.log', - out_file: './logs/out.log', - log_file: './logs/combined.log', - time: true - }] -}; -``` - -```bash -# Start application with PM2 -pm2 start ecosystem.config.js - -# Save PM2 configuration -pm2 save - -# Set up PM2 startup -pm2 startup - -# Monitor application -pm2 monit -``` - -#### 4. Nginx Configuration -```nginx -# /etc/nginx/sites-available/service-sphere -server { - listen 80; - server_name your-domain.com; - - location / { - proxy_pass http://localhost:3000; - proxy_http_version 1.1; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection 'upgrade'; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_cache_bypass $http_upgrade; - } -} -``` - -```bash -# Enable site -sudo ln -s /etc/nginx/sites-available/service-sphere /etc/nginx/sites-enabled/ - -# Test configuration -sudo nginx -t - -# Restart Nginx -sudo systemctl restart nginx -``` - -#### 5. SSL Configuration with Let's Encrypt -```bash -# Install Certbot -sudo apt install certbot python3-certbot-nginx -y - -# Obtain SSL certificate -sudo certbot --nginx -d your-domain.com - -# Auto-renewal -sudo crontab -e -# Add: 0 12 * * * /usr/bin/certbot renew --quiet -``` - -## ☁️ Cloud Deployment - -### AWS Deployment - -#### 1. EC2 Instance Setup -```bash -# Launch EC2 instance (t3.medium recommended) -# Security groups: HTTP (80), HTTPS (443), SSH (22), Custom (3000) - -# Connect to instance -ssh -i your-key.pem ubuntu@your-ec2-ip - -# Follow manual production setup above -``` - -#### 2. Amazon ECS Deployment -```json -{ - "family": "service-sphere-task", - "networkMode": "awsvpc", - "requiresCompatibilities": ["FARGATE"], - "cpu": "512", - "memory": "1024", - "executionRoleArn": "arn:aws:iam::account:role/ecsTaskExecutionRole", - "containerDefinitions": [ - { - "name": "service-sphere-api", - "image": "your-account.dkr.ecr.region.amazonaws.com/service-sphere:latest", - "portMappings": [ - { - "containerPort": 3000, - "protocol": "tcp" - } - ], - "environment": [ - { - "name": "NODE_ENV", - "value": "production" - } - ], - "logConfiguration": { - "logDriver": "awslogs", - "options": { - "awslogs-group": "/ecs/service-sphere", - "awslogs-region": "us-east-1", - "awslogs-stream-prefix": "ecs" - } - } - } - ] -} -``` - -#### 3. MongoDB Atlas Integration -```env -# Use MongoDB Atlas for managed database -DATABASE_URI=mongodb+srv://username:password@cluster.mongodb.net/service-sphere?retryWrites=true&w=majority -``` - -### Google Cloud Platform Deployment - -#### 1. Cloud Run Deployment -```yaml -# cloudbuild.yaml -steps: - - name: 'gcr.io/cloud-builders/docker' - args: ['build', '-t', 'gcr.io/$PROJECT_ID/service-sphere', '.'] - - name: 'gcr.io/cloud-builders/docker' - args: ['push', 'gcr.io/$PROJECT_ID/service-sphere'] - - name: 'gcr.io/cloud-builders/gcloud' - args: - - 'run' - - 'deploy' - - 'service-sphere-api' - - '--image' - - 'gcr.io/$PROJECT_ID/service-sphere' - - '--region' - - 'us-central1' - - '--platform' - - 'managed' - - '--allow-unauthenticated' -``` - -```bash -# Deploy to Cloud Run -gcloud builds submit --config cloudbuild.yaml -``` - -### Azure Deployment - -#### 1. Azure Container Instances -```bash -# Create resource group -az group create --name service-sphere-rg --location eastus - -# Deploy container -az container create \ - --resource-group service-sphere-rg \ - --name service-sphere-api \ - --image your-registry/service-sphere:latest \ - --dns-name-label service-sphere \ - --ports 3000 -``` - -## 🔧 Environment Configuration - -### Environment Files Structure -``` -.env.development.local # Development environment -.env.test.local # Testing environment -.env.staging.local # Staging environment -.env.production.local # Production environment -``` - -### Complete Environment Template -```env -# Application Configuration -NODE_ENV=production -APP_PORT=3000 -CORS_ORIGIN=https://your-frontend-domain.com - -# Database Configuration -DATABASE_URI=mongodb://localhost:27017/service-sphere -DATABASE_NAME=service-sphere - -# JWT Configuration -JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters -JWT_ACCESS_TOKEN_EXPIRATION_TIME=15m -JWT_REFRESH_TOKEN_EXPIRATION_TIME=7d - -# Email Configuration -SMTP_HOST=smtp.gmail.com -SMTP_PORT=587 -SMTP_SECURE=false -SMTP_USER=your-email@gmail.com -SMTP_PASS=your-app-specific-password - -# Cloudinary Configuration -CLOUDINARY_CLOUD_NAME=your-cloud-name -CLOUDINARY_API_KEY=your-api-key -CLOUDINARY_API_SECRET=your-api-secret - -# Admin Configuration -ADMIN_API_KEY=your-admin-api-key-for-creating-admin-users - -# Redis Configuration (Optional) -REDIS_URL=redis://localhost:6379 - -# Monitoring & Logging -LOG_LEVEL=info -SENTRY_DSN=your-sentry-dsn-for-error-tracking - -# Rate Limiting -RATE_LIMIT_WINDOW_MS=900000 -RATE_LIMIT_MAX_REQUESTS=100 - -# File Upload Limits -MAX_FILE_SIZE=5242880 # 5MB in bytes -ALLOWED_FILE_TYPES=jpg,jpeg,png,gif,webp -``` - -### Environment Validation -```typescript -// src/config/validation.schema.ts -import * as Joi from 'joi'; - -export const configValidationSchema = Joi.object({ - NODE_ENV: Joi.string() - .valid('development', 'production', 'test', 'staging') - .default('development'), - APP_PORT: Joi.number().default(3000), - DATABASE_URI: Joi.string().required(), - JWT_SECRET: Joi.string().min(32).required(), - JWT_ACCESS_TOKEN_EXPIRATION_TIME: Joi.string().default('15m'), - JWT_REFRESH_TOKEN_EXPIRATION_TIME: Joi.string().default('7d'), - SMTP_HOST: Joi.string().required(), - SMTP_PORT: Joi.number().default(587), - SMTP_USER: Joi.string().required(), - SMTP_PASS: Joi.string().required(), - CLOUDINARY_CLOUD_NAME: Joi.string().required(), - CLOUDINARY_API_KEY: Joi.string().required(), - CLOUDINARY_API_SECRET: Joi.string().required(), -}); -``` - -## 🗄️ Database Setup - -### MongoDB Configuration - -#### 1. Local MongoDB Setup -```bash -# Install MongoDB -sudo apt-get install -y mongodb-org - -# Start MongoDB service -sudo systemctl start mongod -sudo systemctl enable mongod - -# Create database user -mongosh -``` - -```javascript -// MongoDB shell commands -use service-sphere - -// Create application user -db.createUser({ - user: "service_sphere_user", - pwd: "secure_password", - roles: [ - { role: "readWrite", db: "service-sphere" } - ] -}) - -// Create indexes for performance -db.users.createIndex({ email: 1 }, { unique: true }) -db.users.createIndex({ role: 1 }) -db.services.createIndex({ service_provider: 1 }) -db.services.createIndex({ categories: 1 }) -db.bookings.createIndex({ customer: 1 }) -db.bookings.createIndex({ service: 1 }) -db.feedback.createIndex({ service: 1 }) -``` - -#### 2. MongoDB Atlas (Cloud) Setup -```bash -# 1. Create MongoDB Atlas account -# 2. Create cluster -# 3. Configure network access (whitelist your IP) -# 4. Create database user -# 5. Get connection string -``` - -```env -# Atlas connection string -DATABASE_URI=mongodb+srv://username:password@cluster.mongodb.net/service-sphere?retryWrites=true&w=majority -``` - -### Database Migration & Seeding - -#### 1. Seed Scripts -```typescript -// src/seeds/seed.ts -import { NestFactory } from '@nestjs/core'; -import { AppModule } from '../app.module'; -import { UsersService } from '../users/users.service'; -import { CategoriesService } from '../categories/categories.service'; - -async function bootstrap() { - const app = await NestFactory.createApplicationContext(AppModule); - - const usersService = app.get(UsersService); - const categoriesService = app.get(CategoriesService); - - // Seed categories - const categories = [ - 'Cleaning Services', - 'Home Maintenance', - 'Garden & Landscaping', - 'Pet Services', - 'Tutoring & Education' - ]; - - for (const categoryName of categories) { - await categoriesService.create(categoryName); - } - - // Seed admin user - await usersService.createAdmin({ - first_name: 'Admin', - last_name: 'User', - email: 'admin@servicespherem.com', - password: 'AdminPassword123!' - }); - - console.log('Database seeded successfully'); - await app.close(); -} - -bootstrap(); -``` - -```bash -# Run seed script -npm run seed -``` - -## 📊 Monitoring & Logging - -### Application Monitoring - -#### 1. Health Check Endpoint -```typescript -// src/app.controller.ts -@Get('health') -async healthCheck() { - return { - status: 'ok', - timestamp: new Date().toISOString(), - uptime: process.uptime(), - environment: process.env.NODE_ENV, - version: process.env.npm_package_version - }; -} -``` - -#### 2. PM2 Monitoring -```bash -# Real-time monitoring -pm2 monit - -# CPU and memory usage -pm2 list - -# Restart application -pm2 restart service-sphere-api - -# View logs -pm2 logs service-sphere-api - -# Reload application (zero-downtime) -pm2 reload service-sphere-api -``` - -#### 3. Nginx Monitoring -```bash -# Check Nginx status -sudo systemctl status nginx - -# View access logs -sudo tail -f /var/log/nginx/access.log - -# View error logs -sudo tail -f /var/log/nginx/error.log -``` - -### Logging Configuration - -#### 1. Winston Logger Setup -```typescript -// src/config/logger.config.ts -import { WinstonModule } from 'nest-winston'; -import * as winston from 'winston'; - -export const loggerConfig = WinstonModule.createLogger({ - transports: [ - new winston.transports.Console({ - format: winston.format.combine( - winston.format.timestamp(), - winston.format.colorize(), - winston.format.simple() - ), - }), - new winston.transports.File({ - filename: 'logs/error.log', - level: 'error', - format: winston.format.combine( - winston.format.timestamp(), - winston.format.json() - ), - }), - new winston.transports.File({ - filename: 'logs/combined.log', - format: winston.format.combine( - winston.format.timestamp(), - winston.format.json() - ), - }), - ], -}); -``` - -#### 2. Error Tracking with Sentry -```typescript -// src/main.ts -import * as Sentry from '@sentry/node'; - -if (process.env.NODE_ENV === 'production') { - Sentry.init({ - dsn: process.env.SENTRY_DSN, - environment: process.env.NODE_ENV, - }); -} -``` - -## 🔒 Security Considerations - -### Production Security Checklist - -#### 1. Environment Security -```bash -# Set proper file permissions -chmod 600 .env.production.local - -# Use environment variables, not files in production -export JWT_SECRET="your-secret-here" -``` - -#### 2. Database Security -```javascript -// MongoDB security -db.createUser({ - user: "service_sphere_user", - pwd: "strong_random_password", - roles: [{ role: "readWrite", db: "service-sphere" }] -}) - -// Enable authentication -# In /etc/mongod.conf -security: - authorization: enabled -``` - -#### 3. Nginx Security Headers -```nginx -# Security headers -add_header X-Frame-Options "SAMEORIGIN" always; -add_header X-XSS-Protection "1; mode=block" always; -add_header X-Content-Type-Options "nosniff" always; -add_header Referrer-Policy "no-referrer-when-downgrade" always; -add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always; - -# Hide Nginx version -server_tokens off; -``` - -#### 4. Firewall Configuration -```bash -# UFW firewall setup -sudo ufw enable -sudo ufw allow ssh -sudo ufw allow 'Nginx Full' -sudo ufw allow 27017 # MongoDB (restrict to app server IP in production) -``` - -## 🐛 Troubleshooting - -### Common Issues - -#### 1. Application Won't Start -```bash -# Check logs -pm2 logs service-sphere-api - -# Check environment variables -pm2 env 0 - -# Restart application -pm2 restart service-sphere-api - -# Check port availability -sudo netstat -tlnp | grep :3000 -``` - -#### 2. Database Connection Issues -```bash -# Test MongoDB connection -mongosh "mongodb://localhost:27017/service-sphere" - -# Check MongoDB status -sudo systemctl status mongod - -# Restart MongoDB -sudo systemctl restart mongod - -# Check MongoDB logs -sudo tail -f /var/log/mongodb/mongod.log -``` - -#### 3. Memory Issues -```bash -# Check memory usage -free -h - -# Check application memory usage -pm2 monit - -# Restart application if memory leak -pm2 restart service-sphere-api -``` - -#### 4. SSL Certificate Issues -```bash -# Check certificate status -sudo certbot certificates - -# Renew certificate manually -sudo certbot renew - -# Test certificate -openssl s_client -connect your-domain.com:443 -``` - -### Performance Optimization - -#### 1. Database Optimization -```javascript -// Add compound indexes -db.bookings.createIndex({ customer: 1, status: 1 }) -db.services.createIndex({ service_provider: 1, status: 1 }) - -// Monitor slow queries -db.setProfilingLevel(2, { slowms: 100 }) -db.system.profile.find().sort({ ts: -1 }).limit(5) -``` - -#### 2. Application Optimization -```typescript -// Enable compression -app.use(compression()); - -// Connection pooling -MongooseModule.forRootAsync({ - useFactory: () => ({ - uri: process.env.DATABASE_URI, - maxPoolSize: 10, - serverSelectionTimeoutMS: 5000, - socketTimeoutMS: 45000, - }), -}); -``` - -#### 3. Nginx Optimization -```nginx -# Enable gzip compression -gzip on; -gzip_vary on; -gzip_min_length 1024; -gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json; - -# Enable caching -location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { - expires 1y; - add_header Cache-Control "public, immutable"; -} -``` - ---- - -This deployment guide demonstrates: - -- **Multiple Deployment Strategies**: From development to production -- **Container Orchestration**: Docker and Kubernetes ready -- **Cloud Platform Support**: AWS, GCP, Azure deployment options -- **Production Best Practices**: Security, monitoring, optimization -- **Troubleshooting Skills**: Problem-solving and debugging -- **DevOps Knowledge**: Infrastructure as code and automation From 2c31329696d06c672e35f9433aa30d14a66d6afb Mon Sep 17 00:00:00 2001 From: Hussein Saad Date: Mon, 14 Jul 2025 12:42:08 +0300 Subject: [PATCH 6/8] feat: update architecture documentation --- ARCHITECTURE.md | 176 +++++++++++++++++++----------------------------- 1 file changed, 69 insertions(+), 107 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d76b326..412d5ce 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,6 +1,7 @@ # 🏗️ Service Sphere - System Architecture ## 📋 Table of Contents + - [System Overview](#system-overview) - [Architecture Patterns](#architecture-patterns) - [Module Structure](#module-structure) @@ -8,7 +9,6 @@ - [Security Architecture](#security-architecture) - [Real-time Communication](#real-time-communication) - [Database Design](#database-design) -- [Deployment Architecture](#deployment-architecture) ## 🌐 System Overview @@ -23,7 +23,7 @@ graph TB C[Web App] --> B D[Admin Panel] --> B end - + subgraph "Application Layer" B --> E[Authentication Service] B --> F[User Management] @@ -32,7 +32,7 @@ graph TB B --> I[Chat Service] B --> J[Notification Service] end - + subgraph "Infrastructure Layer" E --> K[(MongoDB)] F --> K @@ -48,17 +48,20 @@ graph TB ## 🔧 Architecture Patterns ### 1. Modular Monolith + - **Bounded Contexts**: Each module represents a distinct business domain - **Loose Coupling**: Modules interact through well-defined interfaces - **Independent Development**: Teams can work on different modules simultaneously - **Migration Ready**: Easy transition to microservices architecture ### 2. Dependency Injection Pattern + ```typescript @Injectable() export class BookingsService { constructor( - @InjectModel(ServiceBookings.name) private bookingModel: Model, + @InjectModel(ServiceBookings.name) + private bookingModel: Model, private readonly servicesService: ServicesService, private readonly usersService: UsersService, private readonly notificationService: NotificationService, @@ -67,17 +70,19 @@ export class BookingsService { ``` ### 3. Repository Pattern + - Abstract data access layer - Centralized query logic - Easy testing with mock repositories - Database-agnostic business logic ### 4. Observer Pattern (Event-Driven) + ```typescript // Booking status changes trigger notifications async updateBookingStatus(bookingId: string, status: string) { const updatedBooking = await booking.save(); - + // Emit event for notification service await this.notificationService.sendBookingStatusUpdate(/* ... */); } @@ -88,6 +93,7 @@ async updateBookingStatus(bookingId: string, status: string) { ### Core Modules #### 1. Authentication Module (`auth/`) + ``` auth/ ├── auth.controller.ts # Auth endpoints @@ -101,6 +107,7 @@ auth/ ``` **Responsibilities:** + - User registration and login - JWT token management - Email verification @@ -108,6 +115,7 @@ auth/ - Role-based access control #### 2. User Management Module (`users/`) + ``` users/ ├── users.controller.ts # User CRUD operations @@ -121,12 +129,14 @@ users/ ``` **Responsibilities:** + - User profile management - Service provider verification - Admin user management - Profile image handling #### 3. Service Management Module (`services/`) + ``` services/ ├── services.controller.ts # Service endpoints @@ -138,12 +148,14 @@ services/ ``` **Responsibilities:** + - Service listing creation - Service categorization - Image upload and management - Service search and filtering #### 4. Booking System Module (`service-bookings/`) + ``` service-bookings/ ├── service-bookings.controller.ts @@ -154,12 +166,14 @@ service-bookings/ ``` **Responsibilities:** + - Booking creation and management - Status tracking - Provider-customer booking coordination - Booking analytics #### 5. Real-time Chat Module (`chat/`) + ``` chat/ ├── chat.gateway.ts # WebSocket gateway @@ -171,12 +185,14 @@ chat/ ``` **Responsibilities:** + - Real-time messaging - Message persistence - Chat access control - Online status management #### 6. Feedback System Module (`feedback/`) + ``` feedback/ ├── feedback.controller.ts @@ -188,6 +204,7 @@ feedback/ ``` **Responsibilities:** + - Review and rating management - Sentiment analysis - Feedback categorization @@ -196,6 +213,7 @@ feedback/ ## 🔄 Data Flow ### 1. Authentication Flow + ```mermaid sequenceDiagram participant Client @@ -214,6 +232,7 @@ sequenceDiagram ``` ### 2. Service Booking Flow + ```mermaid sequenceDiagram participant Customer @@ -232,6 +251,7 @@ sequenceDiagram ``` ### 3. Real-time Chat Flow + ```mermaid sequenceDiagram participant User @@ -266,11 +286,13 @@ graph TD ### Security Features Implemented 1. **JWT Authentication** + - Access tokens (15 minutes) - Refresh tokens (7 days) - Token rotation on refresh 2. **Role-Based Access Control (RBAC)** + ```typescript @UseGuards(JwtAuthGuard, RolesGuard) @Roles('admin', 'service_provider') @@ -278,13 +300,13 @@ graph TD ``` 3. **Input Validation** + ```typescript @IsEmail() @IsNotEmpty() email: string; - + @MinLength(8) - @Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/) password: string; ``` @@ -311,7 +333,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect { payload.userId, payload.bookingId, ); - + // Join room for real-time updates client.join(`booking-${payload.bookingId}`); } @@ -319,6 +341,7 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect { ``` ### Real-time Features + - **Chat messaging** between customers and providers - **Booking status updates** in real-time - **Online status** indicators @@ -329,44 +352,64 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect { ### MongoDB Schema Design #### User Collection + ```typescript { _id: ObjectId, email: String (unique), - password: String (hashed), + password: String (hashed with bcrypt), first_name: String, last_name: String, + full_name: String (computed), role: Enum['customer', 'service_provider', 'admin'], - profile_image: String, + status: Enum['active', 'suspended'], + phone_number: String, email_verified: Boolean, + email_verification_otp: String, + email_verification_expires: Date, + otp_attempts: Number, + emailSent: Boolean, created_at: Date, - - // Service Provider specific fields + updated_at: Date, + + // Customer specific fields (discriminator) + loyalty_points?: Number, + last_active_time?: Date, + is_active?: Boolean, + + // Service Provider specific fields (discriminator) business_name?: String, business_address?: String, tax_id?: String, - verification_status?: Enum['pending', 'approved', 'rejected'], - rating_average?: Number + verification_status?: Enum['pending', 'approved', 'suspended', 'rejected'], + verification_date?: Date, + rating_average?: Number, + + // Admin specific fields (discriminator) + permissions?: [String] } ``` #### Service Collection + ```typescript { _id: ObjectId, service_name: String, description: String, base_price: Number, - status: Enum['active', 'inactive'], + status: String, service_provider: ObjectId (ref: User), categories: [ObjectId] (ref: Category), images: [String], - service_attributes: Object, - creation_time: Date + service_attributes: Object (flexible key-value pairs), + creation_time: Date, + rating_average: Number } ``` #### Booking Collection + ```typescript { _id: ObjectId, @@ -381,106 +424,25 @@ export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect { ``` ### Indexing Strategy + ```javascript // User indices -db.users.createIndex({ email: 1 }, { unique: true }) -db.users.createIndex({ role: 1 }) +db.users.createIndex({ email: 1 }, { unique: true }); +db.users.createIndex({ role: 1 }); // Service indices -db.services.createIndex({ service_provider: 1 }) -db.services.createIndex({ categories: 1 }) -db.services.createIndex({ status: 1 }) +db.services.createIndex({ service_provider: 1 }); +db.services.createIndex({ categories: 1 }); +db.services.createIndex({ status: 1 }); // Booking indices -db.bookings.createIndex({ customer: 1 }) -db.bookings.createIndex({ service: 1 }) -db.bookings.createIndex({ status: 1 }) +db.bookings.createIndex({ customer: 1 }); +db.bookings.createIndex({ service: 1 }); +db.bookings.createIndex({ status: 1 }); ``` -## 🚀 Deployment Architecture - -### Container Architecture -```dockerfile -# Multi-stage build for production optimization -FROM node:18-alpine AS builder -WORKDIR /app -COPY package*.json ./ -RUN npm ci --only=production - -FROM node:18-alpine AS production -WORKDIR /app -COPY --from=builder /app/node_modules ./node_modules -COPY dist ./dist -EXPOSE 3000 -CMD ["node", "dist/main.js"] -``` - -### Docker Compose Setup -```yaml -version: '3.8' -services: - app: - build: . - ports: - - "3000:3000" - environment: - - NODE_ENV=production - depends_on: - - mongodb - - redis - - mongodb: - image: mongo:7 - volumes: - - mongo_data:/data/db - - redis: - image: redis:7-alpine - volumes: - - redis_data:/data -``` - -### Production Considerations - -1. **Horizontal Scaling** - - Load balancer configuration - - Session management with Redis - - Database connection pooling - -2. **Monitoring & Logging** - - Application performance monitoring - - Error tracking and alerting - - Request/response logging - -3. **Security Hardening** - - Environment variable management - - SSL/TLS configuration - - Network security groups - -4. **Backup & Recovery** - - Automated database backups - - Disaster recovery procedures - - Data retention policies - -## 📊 Performance Optimization - -### Caching Strategy -- **Redis** for session storage and temporary data -- **MongoDB** query optimization with proper indexing -- **Cloudinary** for image optimization and CDN delivery - -### Database Optimization -- Connection pooling for database connections -- Aggregation pipelines for complex queries -- Proper indexing strategy for frequently accessed data -### API Optimization -- Response compression with gzip -- Request/response caching where appropriate -- Pagination for large datasets -- Rate limiting to prevent abuse ---- This architecture documentation demonstrates enterprise-level system design and implementation skills, showcasing: From 27071d40b209e3b3c37b162f074630a44dd3a423 Mon Sep 17 00:00:00 2001 From: Hussein Saad Date: Mon, 14 Jul 2025 12:51:53 +0300 Subject: [PATCH 7/8] feat: remove API documentation file --- API_DOCUMENTATION.md | 834 ------------------------------------------- 1 file changed, 834 deletions(-) delete mode 100644 API_DOCUMENTATION.md diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md deleted file mode 100644 index 37ec66a..0000000 --- a/API_DOCUMENTATION.md +++ /dev/null @@ -1,834 +0,0 @@ -# 📚 Service Sphere - API Documentation - -## 📋 Table of Contents -- [API Overview](#api-overview) -- [Authentication Endpoints](#authentication-endpoints) -- [User Management](#user-management) -- [Service Management](#service-management) -- [Booking System](#booking-system) -- [Real-time Chat](#real-time-chat) -- [Feedback System](#feedback-system) -- [Category Management](#category-management) -- [Administrative APIs](#administrative-apis) -- [Error Handling](#error-handling) - -## 🌐 API Overview - -### Base Configuration -- **Base URL**: `http://localhost:3000/api/v1` -- **Content-Type**: `application/json` -- **Authentication**: Bearer Token (JWT) -- **API Version**: v1 - -### Response Format (JSend Standard) -```json -{ - "status": "success|fail|error", - "data": { /* response data */ }, - "message": "Optional message" -} -``` - -### Common Headers -```http -Authorization: Bearer -Content-Type: application/json -Accept: application/json -``` - -## 🔐 Authentication Endpoints - -### Customer Registration -```http -POST /api/v1/auth/register/customer -``` - -**Request Body:** -```json -{ - "first_name": "John", - "last_name": "Doe", - "email": "john.doe@example.com", - "password": "SecurePassword123!", - "phone_number": "+1234567890" -} -``` - -**Response (201 Created):** -```json -{ - "status": "success", - "data": { - "user": { - "_id": "user_id_here", - "first_name": "John", - "last_name": "Doe", - "email": "john.doe@example.com", - "role": "customer", - "email_verified": false, - "profile_image": "default_image_url" - }, - "emailSent": true - }, - "message": "Customer registered successfully. Please verify your email." -} -``` - -### Service Provider Registration -```http -POST /api/v1/auth/register/service-provider -``` - -**Request Body:** -```json -{ - "first_name": "Jane", - "last_name": "Smith", - "email": "jane@business.com", - "password": "SecurePassword123!", - "phone_number": "+1234567890", - "business_name": "Jane's Professional Services", - "business_address": "123 Business Street, City, State 12345", - "tax_id": "TAX123456789" -} -``` - -**Response (201 Created):** -```json -{ - "status": "success", - "data": { - "user": { - "_id": "provider_id_here", - "first_name": "Jane", - "last_name": "Smith", - "email": "jane@business.com", - "role": "service_provider", - "business_name": "Jane's Professional Services", - "verification_status": "pending", - "rating_average": 0 - }, - "emailSent": true - } -} -``` - -### User Login -```http -POST /api/v1/auth/login -``` - -**Request Body:** -```json -{ - "email": "user@example.com", - "password": "UserPassword123!" -} -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": { - "user": { - "_id": "user_id", - "email": "user@example.com", - "role": "customer", - "email_verified": true - }, - "tokens": { - "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", - "refresh_token": "refresh_token_here", - "expires_in": 900 - } - } -} -``` - -### Email Verification -```http -POST /api/v1/auth/verify-email -``` - -**Request Body:** -```json -{ - "userId": "user_id_here", - "otp": "123456" -} -``` - -### Refresh Token -```http -POST /api/v1/auth/refresh -``` - -**Request Body:** -```json -{ - "refreshToken": "refresh_token_here" -} -``` - -### Password Reset Request -```http -POST /api/v1/auth/forgot-password -``` - -**Request Body:** -```json -{ - "email": "user@example.com" -} -``` - -### Password Reset Confirmation -```http -PATCH /api/v1/auth/reset-password/:token -``` - -**Request Body:** -```json -{ - "newPassword": "NewSecurePassword123!" -} -``` - -### Logout -```http -POST /api/v1/auth/logout -``` - -**Request Body:** -```json -{ - "refreshToken": "refresh_token_here" -} -``` - -## 👥 User Management - -### Get All Customers (Admin Only) -```http -GET /api/v1/users/customers -Authorization: Bearer -``` - -### Get Customer by ID -```http -GET /api/v1/users/customers/:id -Authorization: Bearer -``` - -### Update Customer Profile -```http -PATCH /api/v1/users/customers/:id -Content-Type: multipart/form-data -Authorization: Bearer -``` - -**Form Data:** -``` -first_name: Updated Name -phone_number: +1987654321 -profile_image: -``` - -### Get All Service Providers -```http -GET /api/v1/users/service-providers -Authorization: Bearer -``` - -### Get Service Provider by ID -```http -GET /api/v1/users/service-providers/:id -Authorization: Bearer -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": { - "_id": "provider_id", - "first_name": "Jane", - "last_name": "Smith", - "business_name": "Jane's Services", - "verification_status": "approved", - "rating_average": 4.8, - "profile_image": "profile_image_url" - } -} -``` - -## 🛍️ Service Management - -### Get All Services -```http -GET /api/v1/services -Authorization: Bearer -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": [ - { - "_id": "service_id", - "service_name": "Premium House Cleaning", - "description": "Professional deep cleaning service", - "base_price": 150.00, - "status": "active", - "service_provider": { - "_id": "provider_id", - "business_name": "Clean Pro Services", - "rating_average": 4.9 - }, - "categories": [ - { - "_id": "category_id", - "name": "Cleaning" - } - ], - "images": ["image1_url", "image2_url"], - "service_attributes": { - "duration": "3-4 hours", - "equipment_included": true - } - } - ] -} -``` - -### Get Service by ID -```http -GET /api/v1/services/:id -Authorization: Bearer -``` - -### Create New Service (Service Provider Only) -```http -POST /api/v1/services -Content-Type: multipart/form-data -Authorization: Bearer -``` - -**Form Data:** -``` -service_name: Premium House Cleaning -description: Professional deep cleaning service with eco-friendly products -base_price: 150.00 -categories: ["cleaning_category_id", "home_services_category_id"] -service_attributes: {"duration": "3-4 hours", "equipment_included": true} -images: , -``` - -**Response (201 Created):** -```json -{ - "status": "success", - "data": { - "_id": "new_service_id", - "service_name": "Premium House Cleaning", - "description": "Professional deep cleaning service", - "base_price": 150.00, - "status": "active", - "service_provider": "provider_id", - "categories": ["category_id_1", "category_id_2"], - "images": ["uploaded_image_url_1", "uploaded_image_url_2"], - "creation_time": "2024-07-08T10:00:00.000Z" - } -} -``` - -### Update Service -```http -PATCH /api/v1/services/:id -Content-Type: multipart/form-data -Authorization: Bearer -``` - -### Delete Service -```http -DELETE /api/v1/services/:id -Authorization: Bearer -``` - -### Get My Services (Provider Only) -```http -GET /api/v1/services/my-services -Authorization: Bearer -``` - -### Get Services by Provider ID -```http -GET /api/v1/services/provider/:providerId -Authorization: Bearer -``` - -## 📅 Booking System - -### Create Booking -```http -POST /api/v1/bookings/:serviceId -Authorization: Bearer -``` - -**Request Body:** -```json -{ - "preferred_date": "2024-07-15T10:00:00Z", - "special_instructions": "Please use eco-friendly cleaning supplies" -} -``` - -**Response (201 Created):** -```json -{ - "status": "success", - "data": { - "_id": "booking_id", - "customer": "customer_id", - "service": { - "_id": "service_id", - "service_name": "Premium House Cleaning", - "service_provider": { - "_id": "provider_id", - "business_name": "Clean Pro Services" - } - }, - "status": "pending", - "booking_date": "2024-07-15T10:00:00Z", - "total_amount": 150.00, - "created_at": "2024-07-08T12:00:00Z" - } -} -``` - -### Get Customer Bookings -```http -GET /api/v1/bookings -Authorization: Bearer -``` - -### Get Provider Bookings -```http -GET /api/v1/bookings/provider -Authorization: Bearer -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": [ - { - "_id": "booking_id", - "customer": { - "_id": "customer_id", - "full_name": "John Doe", - "email": "john@example.com", - "profile_image": "customer_image_url" - }, - "service": { - "_id": "service_id", - "service_name": "Premium House Cleaning" - }, - "status": "confirmed", - "booking_date": "2024-07-15T10:00:00Z", - "total_amount": 150.00 - } - ] -} -``` - -### Update Booking Status -```http -PATCH /api/v1/bookings/:id/status -Authorization: Bearer -``` - -**Request Body:** -```json -{ - "status": "confirmed" -} -``` - -**Status Options:** -- `pending` - Initial booking state -- `confirmed` - Provider accepted booking -- `completed` - Service was delivered -- `cancelled` - Booking was cancelled - -### Get Booking by ID -```http -GET /api/v1/bookings/:id -Authorization: Bearer -``` - -## 💬 Real-time Chat - -### WebSocket Connection -```javascript -// Connect to WebSocket -const socket = io('http://localhost:3000', { - auth: { - token: 'your_jwt_token' - } -}); - -// Join booking-specific chat room -socket.emit('joinBookingRoom', { - userId: 'user_id', - bookingId: 'booking_id' -}); - -// Listen for new messages -socket.on('newMessage', (message) => { - console.log('New message received:', message); -}); - -// Send message -socket.emit('sendMessage', { - bookingId: 'booking_id', - content: 'Hello, when can you start the service?' -}); -``` - -### Get Chat History -```http -GET /api/v1/chat/history/:bookingId -Authorization: Bearer -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": { - "booking": { - "_id": "booking_id", - "service": { - "service_name": "House Cleaning" - } - }, - "messages": [ - { - "_id": "message_id", - "sender": { - "_id": "user_id", - "first_name": "John", - "profile_image": "image_url" - }, - "content": "Hello, when can you start?", - "timestamp": "2024-07-08T12:30:00Z" - } - ] - } -} -``` - -## ⭐ Feedback System - -### Submit Feedback -```http -POST /api/v1/feedback -Authorization: Bearer -``` - -**Request Body:** -```json -{ - "service": "service_id", - "booking": "booking_id", - "rating": 5, - "review_text": "Excellent service! Very professional and thorough cleaning." -} -``` - -**Response (201 Created):** -```json -{ - "status": "success", - "data": { - "_id": "feedback_id", - "user": "customer_id", - "service": "service_id", - "booking": "booking_id", - "rating": 5, - "review_text": "Excellent service! Very professional and thorough cleaning.", - "sentiment_score": 0.9, - "sentiment_magnitude": 0.8, - "created_at": "2024-07-08T15:00:00Z" - } -} -``` - -### Get Service Feedback -```http -GET /api/v1/feedback/service/:serviceId -Authorization: Bearer -``` - -### Get Provider Feedback -```http -GET /api/v1/feedback/provider/:providerId -Authorization: Bearer -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": [ - { - "_id": "feedback_id", - "user": { - "_id": "customer_id", - "first_name": "John", - "last_name": "Doe", - "profile_image": "customer_image" - }, - "service": { - "_id": "service_id", - "service_name": "Premium House Cleaning" - }, - "rating": 5, - "review_text": "Outstanding service quality!", - "created_at": "2024-07-08T15:00:00Z" - } - ] -} -``` - -### Delete Feedback -```http -DELETE /api/v1/feedback/:id -Authorization: Bearer -``` - -## 🏷️ Category Management - -### Get All Categories -```http -GET /api/v1/categories -Authorization: Bearer -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": [ - { - "_id": "category_id_1", - "name": "Cleaning Services" - }, - { - "_id": "category_id_2", - "name": "Home Maintenance" - }, - { - "_id": "category_id_3", - "name": "Garden & Landscaping" - } - ] -} -``` - -### Create Category (Admin Only) -```http -POST /api/v1/categories -Authorization: Bearer -``` - -**Request Body:** -```json -{ - "name": "Pet Services" -} -``` - -### Update Category (Admin Only) -```http -PATCH /api/v1/categories/:id -Authorization: Bearer -``` - -### Delete Category (Admin Only) -```http -DELETE /api/v1/categories/:id -Authorization: Bearer -``` - -## 🔧 Administrative APIs - -### Get Platform Statistics (Admin Only) -```http -GET /api/v1/admin/statistics -Authorization: Bearer -``` - -**Response (200 OK):** -```json -{ - "status": "success", - "data": { - "users": { - "total_customers": 1250, - "total_providers": 180, - "verified_providers": 165, - "new_registrations_this_month": 45 - }, - "bookings": { - "total_bookings": 3420, - "completed_bookings": 3100, - "pending_bookings": 85, - "bookings_this_month": 340 - }, - "services": { - "total_services": 450, - "active_services": 420, - "most_popular_category": "Cleaning Services" - }, - "revenue": { - "total_platform_revenue": 125000.00, - "revenue_this_month": 12500.00, - "average_booking_value": 165.50 - } - } -} -``` - -### Approve Service Provider (Admin Only) -```http -PATCH /api/v1/admin/providers/:id/verify -Authorization: Bearer -``` - -**Request Body:** -```json -{ - "verification_status": "approved", - "admin_notes": "All documents verified and approved" -} -``` - -## ❌ Error Handling - -### Error Response Format -```json -{ - "status": "error", - "message": "Detailed error message", - "error": { - "code": "ERROR_CODE", - "details": "Additional error details", - "timestamp": "2024-07-08T12:00:00Z" - } -} -``` - -### Common HTTP Status Codes - -#### Authentication Errors -- **401 Unauthorized**: Invalid or missing token -- **403 Forbidden**: Insufficient permissions -- **422 Unprocessable Entity**: Email not verified - -#### Client Errors -- **400 Bad Request**: Invalid request data -- **404 Not Found**: Resource not found -- **409 Conflict**: Duplicate resource (email exists) - -#### Server Errors -- **500 Internal Server Error**: Unexpected server error -- **503 Service Unavailable**: External service unavailable - -### Example Error Responses - -#### Validation Error (400) -```json -{ - "status": "fail", - "data": { - "validation_errors": [ - { - "field": "email", - "message": "Email must be a valid email address" - }, - { - "field": "password", - "message": "Password must be at least 8 characters long" - } - ] - } -} -``` - -#### Authentication Error (401) -```json -{ - "status": "error", - "message": "Invalid or expired token", - "error": { - "code": "INVALID_TOKEN", - "details": "Please login again to get a new token" - } -} -``` - -#### Permission Error (403) -```json -{ - "status": "error", - "message": "Insufficient permissions to access this resource", - "error": { - "code": "INSUFFICIENT_PERMISSIONS", - "required_role": "service_provider", - "user_role": "customer" - } -} -``` - -#### Resource Not Found (404) -```json -{ - "status": "fail", - "data": { - "resource": "service", - "id": "invalid_service_id", - "message": "Service with ID 'invalid_service_id' not found" - } -} -``` - -## 📊 Rate Limiting - -### API Rate Limits -- **Authentication endpoints**: 5 requests per minute per IP -- **General API endpoints**: 100 requests per minute per user -- **File upload endpoints**: 10 requests per minute per user -- **WebSocket connections**: 1 connection per user per booking - -### Rate Limit Headers -```http -X-RateLimit-Limit: 100 -X-RateLimit-Remaining: 95 -X-RateLimit-Reset: 1625097600 -``` - ---- - -This API documentation demonstrates: - -- **RESTful Design**: Clean and intuitive API endpoints -- **Comprehensive Coverage**: All major platform features -- **Security Implementation**: Authentication and authorization -- **Real-world Complexity**: Production-ready API design -- **Error Handling**: Professional error management -- **Documentation Quality**: Enterprise-level documentation standards From 14370c18d0a3e005a8a0eb88bcdf42a391204b6d Mon Sep 17 00:00:00 2001 From: Hussein Saad Date: Mon, 14 Jul 2025 12:56:37 +0300 Subject: [PATCH 8/8] feat: update feature documentation file --- FEATURES.md | 387 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 264 insertions(+), 123 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index ab6cd40..c45258a 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1,6 +1,7 @@ # 🚀 Service Sphere - Feature Documentation ## 📋 Table of Contents + - [Feature Overview](#feature-overview) - [Authentication & Security](#authentication--security) - [User Management System](#user-management-system) @@ -8,6 +9,7 @@ - [Booking Management](#booking-management) - [Real-time Communication](#real-time-communication) - [Feedback & Rating System](#feedback--rating-system) +- [AI-Powered Service Recommendations](#ai-powered-service-recommendations) - [Notification System](#notification-system) - [Administrative Features](#administrative-features) - [Integration Features](#integration-features) @@ -17,6 +19,7 @@ Service Sphere is a comprehensive service marketplace platform that connects customers with service providers through a sophisticated booking and communication system. The platform supports multiple user roles and provides real-time features for seamless interaction. ### Core Value Propositions + - **For Customers**: Easy discovery and booking of local services - **For Service Providers**: Professional platform to showcase services and manage bookings - **For Administrators**: Complete platform oversight and management capabilities @@ -24,43 +27,49 @@ Service Sphere is a comprehensive service marketplace platform that connects cus ## 🔐 Authentication & Security ### Multi-Factor Authentication System + ```typescript // Email verification with OTP -POST /api/v1/auth/register/customer +POST /auth/register/customer { "first_name": "John", "last_name": "Doe", "email": "john@example.com", "password": "SecurePass123!", - "phone_number": "+1234567890" + "confirm_password": "SecurePass123!" } // Response includes OTP sent to email { - "status": "success", - "data": { - "user": { /* user data */ }, - "message": "Verification email sent", - "emailSent": true - } + "user": { + "_id": "user_id", + "first_name": "John", + "last_name": "Doe", + "email": "john@example.com", + "role": "customer", + "email_verified": false + }, + "emailSent": true } ``` ### Advanced Security Features #### 1. JWT Token Management + - **Access Tokens**: Short-lived (15 minutes) for API requests - **Refresh Tokens**: Long-lived (7 days) for token renewal - **Token Rotation**: Automatic refresh token rotation for security - **Token Revocation**: Immediate logout and token invalidation #### 2. Role-Based Access Control (RBAC) + ```typescript -// Three distinct user roles with specific permissions +// Two main user roles with specific permissions enum UserRole { - CUSTOMER = 'customer', // Book services, leave reviews - SERVICE_PROVIDER = 'service_provider', // Manage services, handle bookings - ADMIN = 'admin' // Platform administration + CUSTOMER = 'customer', // Book services, leave reviews + SERVICE_PROVIDER = 'service_provider', // Manage services, handle bookings + ADMIN = 'admin' // Platform administration } // Endpoint protection example @@ -70,20 +79,24 @@ async createService() { /* Only providers and admins can create services */ } ``` #### 3. Password Security + - **bcrypt Hashing**: Industry-standard password encryption -- **Password Strength Validation**: Minimum 8 characters with complexity requirements +- **Password Strength Validation**: Minimum 8 characters - **Secure Reset Process**: Token-based password reset with expiration #### 4. Email Verification System -- **OTP Generation**: 6-digit codes with 10-minute expiration -- **Resend Capability**: Users can request new verification codes + +- **OTP Generation**: 6-digit codes with 15-minute expiration +- **Resend Capability**: Users can request new verification codes with cooldown - **Account Activation**: Users must verify email before platform access +- **Rate Limiting**: Maximum 5 OTP attempts with 1-minute cooldown between requests ## 👥 User Management System ### Customer Management #### Profile Features + - **Personal Information**: Name, email, phone, profile picture - **Booking History**: Complete history of service bookings - **Favorite Services**: Save preferred services for quick access @@ -91,16 +104,18 @@ async createService() { /* Only providers and admins can create services */ } ```typescript // Customer profile update -PATCH /api/v1/users/customers/:id +PATCH /users/customers/:id +Content-Type: multipart/form-data { "first_name": "Updated Name", - "profile_image": "base64_or_url" + "profile_image": } ``` ### Service Provider Management #### Business Profile Features + - **Business Information**: Business name, address, tax ID - **Verification System**: Multi-step verification process - **Service Portfolio**: Manage multiple service offerings @@ -108,25 +123,28 @@ PATCH /api/v1/users/customers/:id ```typescript // Service provider registration with business details -POST /api/v1/auth/register/service-provider +POST /auth/register/service-provider { "first_name": "Jane", "last_name": "Smith", "email": "jane@business.com", + "password": "SecurePass123!", + "confirm_password": "SecurePass123!", "business_name": "Jane's Cleaning Services", "business_address": "123 Business St, City", - "tax_id": "TAX123456789", - "password": "SecurePass123!" + "tax_id": "TAX123456789" } ``` #### Verification Process + 1. **Initial Registration**: Basic business information collection 2. **Document Upload**: Tax ID and business license verification 3. **Admin Review**: Manual verification by platform administrators 4. **Status Updates**: Real-time verification status updates ### Admin Management Features + - **User Oversight**: Manage all customers and service providers - **Platform Analytics**: Comprehensive platform usage statistics - **Content Moderation**: Review and moderate user-generated content @@ -137,25 +155,29 @@ POST /api/v1/auth/register/service-provider ### Service Creation & Management #### Advanced Service Features + ```typescript // Service creation with rich metadata -POST /api/v1/services +POST /services +Content-Type: multipart/form-data { "service_name": "Premium House Cleaning", "description": "Professional deep cleaning service", "base_price": 150.00, - "categories": ["cleaning", "home-services"], + "status": "active", + "categories": ["category_id_1", "category_id_2"], "service_attributes": { "duration": "3-4 hours", "equipment_included": true, "eco_friendly": true, "insurance_covered": true }, - "images": ["image1.jpg", "image2.jpg"] + "images": [, ] } ``` #### Service Discovery Features + - **Category-based Browsing**: Organized service categories - **Search Functionality**: Advanced search with filters - **Provider Filtering**: Find services by specific providers @@ -163,23 +185,25 @@ POST /api/v1/services - **Price Range Filtering**: Budget-based service selection ### Image Management System + ```typescript // Cloudinary integration for professional image handling const uploadResults = await Promise.all( - files.map(file => + files.map((file) => this.cloudinary.uploadFile(file, { folder: 'ServiceSphere', transformation: [ { width: 800, height: 600, crop: 'fill' }, { quality: 'auto' }, - { format: 'webp' } - ] - }) - ) + { format: 'webp' }, + ], + }), + ), ); ``` ### Category Management + - **Dynamic Categories**: Admin-managed service categories - **Hierarchical Structure**: Support for subcategories - **Category Analytics**: Popular categories and trends @@ -189,6 +213,7 @@ const uploadResults = await Promise.all( ### Comprehensive Booking System #### Booking Lifecycle + ```mermaid graph LR A[Customer Books] --> B[Pending Status] @@ -199,44 +224,47 @@ graph LR ``` #### Booking Features + ```typescript // Create booking with automatic notifications -POST /api/v1/bookings/:serviceId -{ - "preferred_date": "2024-07-15T10:00:00Z", - "special_instructions": "Please bring eco-friendly supplies" -} +POST /bookings/:serviceId +// No request body required - booking created with pending status // Automatic response with booking details { - "status": "success", - "data": { - "booking_id": "booking_123", - "status": "pending", - "service": { /* service details */ }, - "provider": { /* provider info */ }, - "estimated_completion": "2024-07-15T14:00:00Z" - } + "_id": "booking_123", + "customer": "customer_id", + "service": { + "_id": "service_id", + "service_name": "Premium House Cleaning", + "service_provider": { + "_id": "provider_id", + "business_name": "Clean Pro Services" + } + }, + "status": "pending", + "created_at": "2024-07-15T10:00:00Z", + "updated_at": "2024-07-15T10:00:00Z" } ``` ### Status Management System + - **Pending**: Initial booking state awaiting provider confirmation - **Confirmed**: Provider has accepted the booking -- **In Progress**: Service is currently being delivered - **Completed**: Service has been finished - **Cancelled**: Booking was cancelled by either party ### Provider Booking Management + ```typescript // Providers can view and manage their bookings -GET /api/v1/bookings/provider +GET /bookings/provider // Returns all bookings for the authenticated provider -PATCH /api/v1/bookings/:id/status +PATCH /bookings/:id/status { - "status": "confirmed", - "estimated_start_time": "2024-07-15T10:00:00Z" + "status": "confirmed" } ``` @@ -245,26 +273,28 @@ PATCH /api/v1/bookings/:id/status ### WebSocket-Based Chat System #### Secure Chat Access + ```typescript // Chat access tied to active bookings -@SubscribeMessage('joinBookingRoom') +@SubscribeMessage('joinRoom') async handleJoinRoom(client: Socket, payload: JoinRoomDto) { // Validate user has access to this booking - const { booking, providerId } = await this.chatService.validateUserAccess( + const { booking } = await this.chatService.validateUserAccess( payload.userId, payload.bookingId ); - + // Only allow chat for active bookings if (['completed', 'cancelled'].includes(booking.status)) { throw new ForbiddenException('Chat is closed for this booking'); } - - client.join(`booking-${payload.bookingId}`); + + client.join(`booking_${payload.bookingId}`); } ``` #### Real-time Features + - **Instant Messaging**: Real-time message delivery - **Message Persistence**: All messages stored for history - **Online Status**: Real-time user presence indicators @@ -272,6 +302,7 @@ async handleJoinRoom(client: Socket, payload: JoinRoomDto) { - **Message Read Receipts**: Delivery confirmation ### Chat Security & Privacy + - **Booking-Specific**: Chats are isolated to individual bookings - **Access Control**: Only booking participants can access chat - **Message Encryption**: Secure message transmission @@ -282,47 +313,124 @@ async handleJoinRoom(client: Socket, payload: JoinRoomDto) { ### AI-Powered Sentiment Analysis #### Advanced Feedback Processing + ```typescript // Automatic sentiment analysis on feedback submission async create(createFeedbackDto: CreateFeedbackDto, userId: string) { + // Validate booking and user access + const booking = await this.bookingModel.findById(createFeedbackDto.booking); + + if (booking.status !== 'completed') { + throw new BadRequestException('You can only leave feedback for completed bookings'); + } + // Analyze sentiment of the review text const sentimentResult = await this.sentimentAnalysisService.analyzeSentiment( - createFeedbackDto.review_text + createFeedbackDto.message ); - + const feedback = new this.feedbackModel({ ...createFeedbackDto, user: userId, - sentiment_score: sentimentResult.score, - sentiment_magnitude: sentimentResult.magnitude, - created_at: new Date() + sentiment: sentimentResult.sentiment, + sentimentScore: sentimentResult.score, }); - + + // Update service and provider ratings + await this.updateServiceRating(feedback.service.toString()); + return feedback.save(); } ``` #### Rating System Features -- **5-Star Rating**: Numerical rating system -- **Detailed Reviews**: Text-based feedback -- **Sentiment Analysis**: AI-powered sentiment scoring -- **Provider Ratings**: Aggregate rating calculations -- **Review Moderation**: Admin oversight for inappropriate content + +- **5-Star Rating**: Numerical rating system (1-5 stars) +- **Detailed Reviews**: Text-based feedback with sentiment analysis +- **Multi-language Support**: Arabic and English sentiment analysis +- **Provider Ratings**: Aggregate rating calculations for service providers +- **Service Ratings**: Individual service rating calculations +- **Review Validation**: Only customers who completed bookings can review +- **Duplicate Prevention**: One review per customer per booking ### Review Management + ```typescript // Comprehensive feedback endpoints -GET /api/v1/feedback/service/:id // All reviews for a service -GET /api/v1/feedback/provider/:id // All reviews for a provider -POST /api/v1/feedback // Submit new feedback -DELETE /api/v1/feedback/:id // Delete own feedback (or admin) +GET /feedback/service/:id // All reviews for a service +GET /feedback/provider/:id // All reviews for a provider +GET /feedback/customer // Current user's feedback +GET /feedback/customer/:id // Specific customer's feedback +POST /feedback // Submit new feedback +DELETE /feedback/:id // Delete own feedback (or admin) ``` +## 🤖 AI-Powered Service Recommendations + +### Intelligent Advice System + +Service Sphere features an advanced AI-powered advice system that provides personalized recommendations to service providers based on customer feedback analysis. + +#### Smart Feedback Analysis + +```typescript +// Get AI-powered advice for service providers +GET /advice/me +Authorization: Bearer + +// AI analyzes all feedback and provides actionable insights +{ + "advice": "Based on your recent feedback analysis..." +} +``` + +#### Key Features + +- **Multi-language Analysis**: Supports both Arabic and English feedback +- **Automatic Language Detection**: Identifies dominant language in feedback +- **Sentiment Categorization**: Groups feedback into positive, neutral, and negative +- **Actionable Insights**: Provides specific recommendations for improvement +- **Hugging Face Integration**: Uses advanced NLP models for advice generation + +#### Technical Implementation + +```typescript +async getAdviceForServiceProvider(providerId: string): Promise { + // Collect all feedback for provider's services + const services = await this.servicesService.getAllServicesByProviderId(providerId); + const feedback = []; + + for (const service of services) { + const serviceFeedback = await this.feedbackService.getAllFeedbackByServiceId( + service._id.toString() + ); + feedback.push(...serviceFeedback); + } + + // Detect dominant language (Arabic/English) + const dominantLanguage = this.detectDominantLanguage(feedback); + + // Format feedback for AI analysis + const feedbackText = this.formatFeedbackForAdvice(feedback, dominantLanguage); + + // Get AI-powered advice + return await this.callHuggingFaceModel(feedbackText, dominantLanguage); +} +``` + +#### Language Support + +- **Arabic Feedback**: Native Arabic language processing and response +- **English Feedback**: English language analysis and recommendations +- **Language Detection**: Automatic detection based on character analysis +- **Bilingual Responses**: AI responds in the detected dominant language + ## 📧 Notification System ### Multi-Channel Notifications #### Email Notifications + ```typescript // Professional email templates with Handlebars await this.mailService.sendBookingConfirmation( @@ -331,22 +439,22 @@ await this.mailService.sendBookingConfirmation( { bookingId: booking._id, serviceName: service.service_name, - providerName: provider.business_name, - scheduledDate: booking.scheduled_date, - totalAmount: booking.total_amount - } + providerName: provider.business_name || provider.full_name, + }, ); ``` #### Notification Types -- **Welcome Emails**: New user onboarding -- **Booking Confirmations**: Booking status updates -- **Payment Notifications**: Transaction confirmations -- **Verification Emails**: Account verification -- **Password Reset**: Secure password recovery -- **Provider Alerts**: New booking notifications + +- **Welcome Emails**: New user onboarding with OTP verification +- **Booking Notifications**: New booking alerts for providers +- **Status Updates**: Booking status change notifications +- **Email Verification**: Account verification with OTP codes +- **Password Reset**: Secure password recovery with tokens +- **Real-time Notifications**: In-app notifications through WebSocket ### Email Template System + - **Handlebars Templates**: Dynamic content rendering - **Brand Consistency**: Professional email design - **Responsive Design**: Mobile-optimized emails @@ -357,96 +465,129 @@ await this.mailService.sendBookingConfirmation( ### Comprehensive Admin Panel #### User Management + ```typescript // Admin-only endpoints for user management -GET /api/v1/users/customers // List all customers -GET /api/v1/users/service-providers // List all providers -PATCH /api/v1/users/:id // Update any user -DELETE /api/v1/users/:id // Remove users +GET /users/customers // List all customers +GET /users/service-providers // List all providers +GET /users/admins // List all admins (admin only) +PATCH /users/customers/:id // Update customer +PATCH /users/service-providers/:id // Update provider +DELETE /users/customers/:id // Remove customer +DELETE /users/service-providers/:id // Remove provider ``` #### Platform Analytics + - **User Statistics**: Registration and activity metrics -- **Booking Analytics**: Platform usage and revenue data +- **Booking Analytics**: Platform usage and booking trends - **Service Performance**: Popular services and categories -- **Provider Verification**: Manage verification queue +- **Provider Verification**: Manage verification status +- **Real-time Monitoring**: Live platform statistics #### Content Moderation -- **Review Moderation**: Flag inappropriate reviews -- **Service Approval**: Review new service listings -- **User Verification**: Manual user verification process -- **Category Management**: Add/edit service categories + +- **Review Management**: Monitor and manage user feedback +- **Service Oversight**: Review and manage service listings +- **User Verification**: Manual verification processes +- **Category Management**: Add/edit service categories via dedicated endpoints ### Admin Security Features -- **API Key Protection**: Secure admin registration -- **Audit Logging**: Track administrative actions -- **Role Separation**: Clear admin vs. user boundaries + +- **API Key Protection**: Secure admin registration with API keys +- **Role-based Access**: Strict admin-only endpoints +- **First Admin Setup**: Special endpoint for initial admin creation +- **Permission Management**: Granular admin permissions system ## 🔗 Integration Features ### Third-Party Service Integration #### Cloudinary Integration + ```typescript -// Professional image management +// Professional image management with automatic optimization const uploadResult = await this.cloudinary.uploadFile(file, { folder: 'ServiceSphere', transformation: [ { width: 800, height: 600, crop: 'fill' }, - { quality: 'auto:best' }, - { format: 'webp' } - ] + { quality: 'auto' }, + { format: 'webp' }, + ], }); ``` +#### AI/ML Service Integration + +- **Hugging Face Models**: Advanced NLP for sentiment analysis and advice generation +- **Multi-language Processing**: Arabic and English language support +- **Sentiment Analysis**: Real-time feedback sentiment classification +- **Recommendation Engine**: AI-powered service improvement suggestions + #### Email Service Integration -- **SMTP Configuration**: Professional email delivery -- **Template Engine**: Dynamic email content -- **Delivery Tracking**: Email delivery confirmation -- **Bounce Handling**: Failed delivery management + +- **SMTP Configuration**: Professional email delivery with Nodemailer +- **Template Engine**: Dynamic email content with Handlebars +- **Delivery Tracking**: Email delivery status monitoring +- **Multi-template Support**: Welcome, verification, password reset templates ### Database Integration -- **MongoDB**: Scalable NoSQL database -- **Mongoose ODM**: Object document mapping -- **Index Optimization**: Performance-optimized queries -- **Data Validation**: Schema-level validation + +- **MongoDB**: Scalable NoSQL database with Mongoose ODM +- **Discriminator Pattern**: Role-based user schemas (Customer, ServiceProvider, Admin) +- **Index Optimization**: Performance-optimized queries for users, services, bookings +- **Schema Validation**: Robust data validation with class-validator +- **Relationship Management**: Proper document relationships and population ## 📊 Analytics & Reporting ### Business Intelligence Features -- **Booking Trends**: Track booking patterns and seasonality -- **Revenue Analytics**: Platform revenue and commission tracking -- **User Engagement**: User activity and retention metrics + +- **Booking Trends**: Track booking patterns and status distribution +- **User Engagement**: User registration and activity metrics - **Service Performance**: Popular services and provider rankings +- **Rating Analytics**: Average ratings and sentiment analysis results ### Performance Monitoring -- **Response Time Tracking**: API performance monitoring -- **Error Rate Monitoring**: System health tracking -- **User Behavior Analytics**: Platform usage patterns -- **Conversion Tracking**: Booking success rates + +- **Real-time Notifications**: WebSocket-based notification delivery +- **Response Optimization**: Efficient database queries with proper indexing +- **Error Handling**: Comprehensive error tracking and logging +- **API Performance**: Monitoring endpoint response times and usage ## 🚀 Technical Excellence ### Code Quality Features -- **TypeScript**: Type-safe development -- **Clean Architecture**: SOLID principles implementation -- **Comprehensive Testing**: Unit and integration tests -- **Documentation**: Extensive code documentation -- **Error Handling**: Graceful error management + +- **TypeScript**: Type-safe development with strict typing +- **Clean Architecture**: SOLID principles and modular design +- **Dependency Injection**: NestJS dependency injection container +- **Comprehensive Validation**: DTOs with class-validator decorators +- **Error Handling**: Global exception filters with standardized responses ### Performance Optimization -- **Database Indexing**: Optimized query performance -- **Caching Strategy**: Redis-based caching -- **Image Optimization**: Automated image processing -- **Load Balancing**: Horizontal scaling support + +- **Database Indexing**: Optimized MongoDB indexes for key queries +- **Image Optimization**: Cloudinary automatic image processing +- **Connection Pooling**: Efficient database connection management +- **Caching Strategy**: Strategic data caching for performance +- **Load Balancing**: Horizontal scaling support with Docker + +### Security Implementation + +- **JWT Authentication**: Secure token-based authentication +- **Password Hashing**: bcrypt with salt rounds +- **Role-based Guards**: Decorator-based access control +- **Input Sanitization**: XSS and injection protection +- **Rate Limiting**: API rate limiting and abuse prevention --- This feature documentation demonstrates: -- **Full-Stack Capability**: Complete backend system development -- **Real-World Application**: Production-ready features -- **Technical Depth**: Advanced implementation details -- **Business Value**: Clear value propositions for users -- **Scalability**: Enterprise-grade architecture -- **Security**: Comprehensive security implementation +- **Full-Stack Capability**: Complete backend system with real-world features +- **AI Integration**: Advanced machine learning and NLP capabilities +- **Production Ready**: Comprehensive security, validation, and error handling +- **Scalable Architecture**: Clean, modular design ready for growth +- **Multi-language Support**: Arabic and English language processing +- **Real-time Features**: WebSocket implementation for live interactions