diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..412d5ce --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,454 @@ +# 🏗️ 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) + +## 🌐 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) + 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 with bcrypt), + first_name: String, + last_name: String, + full_name: String (computed), + role: Enum['customer', 'service_provider', 'admin'], + 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, + 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', '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: String, + service_provider: ObjectId (ref: User), + categories: [ObjectId] (ref: Category), + images: [String], + service_attributes: Object (flexible key-value pairs), + creation_time: Date, + rating_average: Number +} +``` + +#### 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 }); +``` + + + + +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/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..c45258a --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,593 @@ +# 🚀 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) +- [AI-Powered Service Recommendations](#ai-powered-service-recommendations) +- [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 /auth/register/customer +{ + "first_name": "John", + "last_name": "Doe", + "email": "john@example.com", + "password": "SecurePass123!", + "confirm_password": "SecurePass123!" +} + +// Response includes OTP sent to email +{ + "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 +// 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 +} + +// 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 +- **Secure Reset Process**: Token-based password reset with expiration + +#### 4. Email Verification System + +- **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 +- **Reviews & Ratings**: Manage feedback given to service providers + +```typescript +// Customer profile update +PATCH /users/customers/:id +Content-Type: multipart/form-data +{ + "first_name": "Updated Name", + "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 +- **Performance Analytics**: Booking statistics and ratings + +```typescript +// Service provider registration with business details +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" +} +``` + +#### 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 /services +Content-Type: multipart/form-data +{ + "service_name": "Premium House Cleaning", + "description": "Professional deep cleaning service", + "base_price": 150.00, + "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": [, ] +} +``` + +#### 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 /bookings/:serviceId +// No request body required - booking created with pending status + +// Automatic response with booking details +{ + "_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 +- **Completed**: Service has been finished +- **Cancelled**: Booking was cancelled by either party + +### Provider Booking Management + +```typescript +// Providers can view and manage their bookings +GET /bookings/provider +// Returns all bookings for the authenticated provider + +PATCH /bookings/:id/status +{ + "status": "confirmed" +} +``` + +## 💬 Real-time Communication + +### WebSocket-Based Chat System + +#### Secure Chat Access + +```typescript +// Chat access tied to active bookings +@SubscribeMessage('joinRoom') +async handleJoinRoom(client: Socket, payload: JoinRoomDto) { + // Validate user has access to this booking + 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}`); +} +``` + +#### 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) { + // 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.message + ); + + const feedback = new this.feedbackModel({ + ...createFeedbackDto, + user: userId, + 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 (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 /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( + customer.email, + customer.first_name, + { + bookingId: booking._id, + serviceName: service.service_name, + providerName: provider.business_name || provider.full_name, + }, +); +``` + +#### Notification Types + +- **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 +- **Personalization**: User-specific content + +## 🔧 Administrative Features + +### Comprehensive Admin Panel + +#### User Management + +```typescript +// Admin-only endpoints for user management +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 booking trends +- **Service Performance**: Popular services and categories +- **Provider Verification**: Manage verification status +- **Real-time Monitoring**: Live platform statistics + +#### Content Moderation + +- **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 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 with automatic optimization +const uploadResult = await this.cloudinary.uploadFile(file, { + folder: 'ServiceSphere', + transformation: [ + { width: 800, height: 600, crop: 'fill' }, + { 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 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 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 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 + +- **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 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 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 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 diff --git a/README.md b/README.md index 72136e3..62350f0 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,521 @@ -## 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/) +[![Socket.IO](https://img.shields.io/badge/Socket.IO-010101?style=flat&logo=socketdotio&logoColor=white)](https://socket.io/) -### Clone the Repository +> **A comprehensive service marketplace backend platform connecting customers with service providers through real-time communication, intelligent booking management, and sentiment-based 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 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 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 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 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 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 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 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 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 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 with authentication +- **Chat System** - Booking-specific messaging with message persistence +- **Real-time Notifications** - Instant push notifications for user actions + +### Email & Notifications + +- **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** - 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** v18+ +- **Yarn** package manager +- **MongoDB** 4.4+ +- **Docker** & Docker Compose (optional) + +### Environment Setup + +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 ``` -### Set Up Environment Variables +2. **Install dependencies** + +```bash +yarn install +``` + +3. **Configure environment variables** + +```bash +# Create environment file +cp .env.example .env.development.local + +# 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 +``` + +4. **Start the application** + +**Development mode:** + +```bash +yarn start:dev +``` -Ensure that the `.env.test.local` file is present in the project root and correctly configured. +**Production mode:** -### Build and Run the Application +```bash +yarn build +yarn start:prod +``` -Use Docker Compose to build and run the application: +**With Docker:** ```bash docker-compose up --build ``` -This command will: +5. **Verify installation** -- 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. +```bash +# Check if server is running +curl http://localhost:3000/api/v1 -### Access the Application +# 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!" + }' +``` -Once the containers are up and running, you can access the application at: +# Run tests -- **URL**: `http://localhost:3000` +```bash +yarn run test +yarn run test:cov +``` ---- +### 🌐 API Access -## Stopping the Application +- **Base URL**: `http://localhost:3000/api/v1` -To stop the application and remove the containers, run: +## 📁 Project Structure + +``` +src/ +├── 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 -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 +``` + +## 📈 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/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 +GET /api/v1/bookings/provider +PATCH /api/v1/bookings/:id/status +GET /api/v1/bookings/:id ``` -This will stop and remove the containers, networks, and volumes defined in `docker-compose.yml`. +### 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 +- **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 + +### 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 --- +**⭐ 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/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 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\"",