Skip to content

Marketplace backend built using Node.js + MySQL with JWT authentication, product/order modules, delivery routing, and Swagger-powered documentation.

Notifications You must be signed in to change notification settings

Vkchowdary05/node-mysql-marketplace-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Marketplace Backend System

πŸš€ Overview

A comprehensive multi-role marketplace backend system built with Node.js, Express.js, MySQL, and Sequelize ORM. This production-ready application features JWT-based authentication, Swagger documentation, and AI-powered features for seller recommendations, route optimization, and complaint categorization.

πŸ“‹ Table of Contents

✨ Features

Core Functionality

  • Multi-role authentication (Seller, Customer, Salesman, Delivery Person)
  • JWT-based authorization with role-based access control
  • Complete CRUD operations for all entities
  • Transaction management for data consistency
  • Real-time order tracking
  • Comprehensive Swagger documentation
  • Production-ready error handling

Seller Module

  • Dashboard with order management
  • Accept/reject orders with partial acceptance
  • Product catalog management
  • Order status updates
  • Delivery person assignment
  • Analytics and summaries

Delivery Person Module

  • View assigned orders
  • Update delivery status
  • Upload proof of delivery
  • Optimized route planning
  • Daily performance tracking

Salesman Module

  • Route and beat management
  • Attendance marking
  • Store visit logging
  • Secondary sales order creation
  • Performance metrics

Customer Module

  • Search sellers by location
  • Place multi-product orders
  • Real-time order tracking
  • Raise complaints
  • View order history

AI-Powered Features

  • Seller Recommendation System: Location-based recommendations with rating and availability scoring
  • Delivery Route Optimization: Nearest-neighbor algorithm for efficient delivery sequencing
  • Complaint Categorization: Keyword-based AI classification of complaints

πŸ›  Tech Stack

  • Runtime: Node.js (v14+)
  • Framework: Express.js
  • Database: MySQL (v8+)
  • ORM: Sequelize
  • Authentication: JWT (jsonwebtoken)
  • Documentation: Swagger (swagger-jsdoc, swagger-ui-express)
  • Validation: express-validator
  • Security: bcryptjs, helmet, cors
  • Dev Tools: nodemon, sequelize-cli

πŸ“ Project Structure

marketplace-backend/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”œβ”€β”€ database.js          # Database configuration
β”‚   β”‚   β”œβ”€β”€ swagger.js            # Swagger/OpenAPI configuration
β”‚   β”‚   └── constants.js          # Application constants
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ index.js              # Model initialization and relationships
β”‚   β”‚   β”œβ”€β”€ User.js               # User model (base authentication)
β”‚   β”‚   β”œβ”€β”€ Seller.js             # Seller profile model
β”‚   β”‚   β”œβ”€β”€ Customer.js           # Customer profile model
β”‚   β”‚   β”œβ”€β”€ Salesman.js           # Salesman profile model
β”‚   β”‚   β”œβ”€β”€ DeliveryPerson.js     # Delivery person profile model
β”‚   β”‚   β”œβ”€β”€ Product.js            # Product catalog model
β”‚   β”‚   β”œβ”€β”€ Order.js              # Order model
β”‚   β”‚   β”œβ”€β”€ OrderItem.js          # Order line items model
β”‚   β”‚   β”œβ”€β”€ Route.js              # Sales route model
β”‚   β”‚   β”œβ”€β”€ Store.js              # Retail store model
β”‚   β”‚   β”œβ”€β”€ Attendance.js         # Salesman attendance model
β”‚   β”‚   β”œβ”€β”€ SalesOrder.js         # Secondary sales order model
β”‚   β”‚   β”œβ”€β”€ Complaint.js          # Customer complaint model
β”‚   β”‚   └── ProofOfDelivery.js    # Delivery proof model
β”‚   β”œβ”€β”€ middlewares/
β”‚   β”‚   β”œβ”€β”€ auth.js               # JWT authentication & authorization
β”‚   β”‚   β”œβ”€β”€ errorHandler.js       # Centralized error handling
β”‚   β”‚   └── validator.js          # Request validation middleware
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ authController.js     # Authentication endpoints
β”‚   β”‚   β”œβ”€β”€ sellerController.js   # Seller business logic handlers
β”‚   β”‚   β”œβ”€β”€ deliveryController.js # Delivery person handlers
β”‚   β”‚   β”œβ”€β”€ salesmanController.js # Salesman handlers
β”‚   β”‚   └── customerController.js # Customer handlers
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ authService.js        # Authentication business logic
β”‚   β”‚   β”œβ”€β”€ sellerService.js      # Seller business operations
β”‚   β”‚   β”œβ”€β”€ deliveryService.js    # Delivery operations
β”‚   β”‚   β”œβ”€β”€ salesmanService.js    # Salesman operations
β”‚   β”‚   └── customerService.js    # Customer operations
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ index.js              # Route aggregation
β”‚   β”‚   β”œβ”€β”€ authRoutes.js         # Authentication routes
β”‚   β”‚   β”œβ”€β”€ sellerRoutes.js       # Seller API routes
β”‚   β”‚   β”œβ”€β”€ deliveryRoutes.js     # Delivery person routes
β”‚   β”‚   β”œβ”€β”€ salesmanRoutes.js     # Salesman routes
β”‚   β”‚   └── customerRoutes.js     # Customer routes
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ jwt.js                # JWT token utilities
β”‚   β”‚   β”œβ”€β”€ response.js           # Response formatting utilities
β”‚   β”‚   └── aiHelper.js           # AI feature implementations
β”‚   └── app.js                    # Express app configuration
β”œβ”€β”€ migrations/                    # Sequelize migrations
β”œβ”€β”€ seeders/                       # Database seed files
β”œβ”€β”€ .env.example                   # Environment variables template
β”œβ”€β”€ .gitignore                     # Git ignore rules
β”œβ”€β”€ .sequelizerc                   # Sequelize CLI configuration
β”œβ”€β”€ package.json                   # Dependencies and scripts
β”œβ”€β”€ server.js                      # Application entry point
└── README.md                      # This file

πŸ“¦ Installation

Prerequisites

Ensure you have the following installed:

  • Node.js (v14 or higher)
  • MySQL (v8 or higher)
  • npm or yarn

Steps

  1. Clone the repository
git clone <repository-url>
cd marketplace-backend
  1. Install dependencies
npm install
  1. Configure environment variables
cp .env.example .env

Edit .env with your configuration:

NODE_ENV=development
PORT=3000

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_NAME=marketplace_db
DB_USER=root
DB_PASSWORD=your_password

# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRE=7d

# AI Features
ENABLE_AI_FEATURES=true

πŸ—„ Database Setup

Create Database

# Using Sequelize CLI
npx sequelize-cli db:create

Or manually in MySQL:

CREATE DATABASE marketplace_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Run Migrations

npx sequelize-cli db:migrate

This will create all required tables with proper relationships and indexes.

Seed Database

npx sequelize-cli db:seed:all

This creates demo data with the following users:

Role Email Password
Seller 1 seller1@marketplace.com password123
Seller 2 seller2@marketplace.com password123
Customer 1 customer1@marketplace.com password123
Customer 2 customer2@marketplace.com password123
Salesman salesman1@marketplace.com password123
Delivery Person delivery1@marketplace.com password123

πŸš€ Running the Application

Development Mode

npm run dev

Production Mode

npm start

The server will start on http://localhost:3000

Health Check

curl http://localhost:3000/health

πŸ“š API Documentation

Swagger UI

Access interactive API documentation at:

http://localhost:3000/api-docs

Authentication

All protected endpoints require a JWT token in the Authorization header:

Authorization: Bearer <your-jwt-token>

Base URL

http://localhost:3000/api

Endpoints Overview

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - Login user

Seller APIs

  • GET /api/seller/profile - Get seller profile
  • GET /api/seller/dashboard - Get dashboard with orders
  • PUT /api/seller/orders/:orderId/accept - Accept order
  • PUT /api/seller/orders/:orderId/reject - Reject order
  • PUT /api/seller/orders/:orderId/status - Update order status
  • POST /api/seller/orders/:orderId/assign-delivery - Assign delivery person
  • GET /api/seller/products - List products
  • POST /api/seller/products - Create product
  • PUT /api/seller/products/:productId - Update product
  • DELETE /api/seller/products/:productId - Delete product
  • PATCH /api/seller/products/:productId/toggle-status - Toggle product status

Delivery Person APIs

  • GET /api/delivery/profile - Get profile
  • GET /api/delivery/orders - Get assigned orders
  • PUT /api/delivery/orders/:orderId/status - Update delivery status
  • POST /api/delivery/orders/:orderId/proof - Upload proof of delivery
  • GET /api/delivery/route - Get optimized route
  • GET /api/delivery/performance - Get daily performance

Salesman APIs

  • GET /api/salesman/profile - Get profile
  • GET /api/salesman/routes - Get assigned routes
  • GET /api/salesman/routes/:routeId/stores - Get stores in route
  • POST /api/salesman/attendance - Mark attendance
  • PUT /api/salesman/attendance/checkout - Check out
  • POST /api/salesman/visits - Log store visit
  • POST /api/salesman/sales-orders - Create sales order
  • GET /api/salesman/sales-orders - Get sales orders
  • GET /api/salesman/performance - Get performance summary

Customer APIs

  • GET /api/customer/profile - Get profile
  • GET /api/customer/sellers - Search sellers by location
  • POST /api/customer/orders - Place new order
  • GET /api/customer/orders/:orderId - Track order
  • GET /api/customer/orders - Get order history
  • POST /api/customer/complaints - Raise complaint
  • GET /api/customer/complaints - Get complaint history

πŸ”§ Modules Overview

1. Seller Module (20 points)

Key Features:

  • Complete order management dashboard
  • Accept/reject orders with partial acceptance capability
  • Update order lifecycle status (accepted β†’ packed β†’ dispatched)
  • Assign delivery personnel to orders
  • Full product catalog CRUD operations
  • Product activation/deactivation
  • Transaction-based updates for data consistency

Business Logic:

  • Sellers can partially accept orders by accepting/rejecting individual items
  • Order status transitions are validated
  • Stock is automatically reduced when orders are placed
  • Products can be soft-deleted (deactivated) instead of permanent deletion

2. Delivery Person Module (20 points)

Key Features:

  • View all assigned orders with full details
  • Progressive status updates (dispatched β†’ out_for_delivery β†’ delivered/returned)
  • Upload proof of delivery (image or signature)
  • AI-powered route optimization
  • Daily performance tracking

Business Logic:

  • Status transitions are validated (can't skip stages)
  • Proof can only be uploaded after delivery
  • Route optimization uses nearest-neighbor algorithm
  • Performance metrics include delivered, returned, and pending counts

3. Salesman Module (20 points)

Key Features:

  • View assigned routes and stores
  • Daily attendance check-in/check-out
  • Log store visits with timestamps
  • Create secondary sales orders for retailers
  • View comprehensive performance metrics

Business Logic:

  • Can only check in once per day
  • Must check in before checking out
  • Sales orders are tracked per store
  • Performance metrics include total orders, sales, attendance days, and stores covered

4. Customer Module

Key Features:

  • Search sellers by city, area, and pincode
  • AI-powered seller recommendations
  • Place orders for multiple products
  • Real-time order tracking
  • Raise complaints with image upload
  • AI-based complaint categorization

Business Logic:

  • Stock validation before order placement
  • Complaints can only be raised for delivered orders
  • Order history with filtering options

πŸ€– AI Features

1. Seller Recommendation System

Algorithm: Weighted scoring based on multiple factors

Factors:

  • Proximity (40%): Distance calculated from pincode difference
  • Availability (30%): Verification status and stock availability
  • Rating (30%): Seller rating out of 5

Formula:

Total Score = (Proximity Score Γ— 0.4) + (Availability Score Γ— 0.3) + (Rating Score Γ— 0.3)

Implementation: src/utils/aiHelper.js -> recommendSellers()

Usage: Enabled when ENABLE_AI_FEATURES=true and customer provides pincode

2. Delivery Route Optimization

Algorithm: Nearest Neighbor (Greedy Algorithm)

Process:

  1. Start from delivery person's current location
  2. Find nearest unvisited delivery location
  3. Move to that location
  4. Repeat until all deliveries are sequenced
  5. Calculate estimated time for each stop (base 30min + 15min per stop)

Implementation: src/utils/aiHelper.js -> optimizeDeliveryRoute()

Benefits:

  • Minimizes total travel distance
  • Reduces delivery time
  • Improves fuel efficiency
  • Better time estimates for customers

3. Complaint Categorization

Algorithm: Keyword-based classification with confidence scoring

Categories:

  • Damaged: Keywords like "broken", "damaged", "crack", "torn", "defective"
  • Late: Keywords like "late", "delay", "slow", "waiting", "overdue"
  • Wrong Item: Keywords like "wrong", "different", "incorrect", "mistake"
  • Others: Default when no keywords match

Implementation: src/utils/aiHelper.js -> categorizeComplaint()

Process:

  1. Scan complaint description for category-specific keywords
  2. Count matches for each category
  3. Calculate confidence score
  4. Return category with highest score

πŸ§ͺ Testing

Using Postman

  1. Import the Postman collection (create from Swagger)

  2. Set up environment variables:

    • baseUrl: http://localhost:3000/api
    • token: JWT token from login response
  3. Test workflow:

    • Register/Login as different roles
    • Use token in subsequent requests
    • Test complete order lifecycle
    • Verify transactions and relationships

Manual Testing

  1. Seller Workflow:
# Login
POST /api/auth/login
{
  "email": "seller1@marketplace.com",
  "password": "password123"
}

# View dashboard
GET /api/seller/dashboard

# Accept order
PUT /api/seller/orders/{orderId}/accept
  1. Customer Workflow:
# Search sellers
GET /api/customer/sellers?city=Mumbai&pincode=400053

# Place order
POST /api/customer/orders
{
  "sellerId": "...",
  "items": [{"productId": "...", "quantity": 2}]
}

πŸ”’ Security Features

  1. JWT Authentication: Secure token-based authentication
  2. Password Hashing: bcrypt with salt rounds
  3. Role-Based Access Control: Middleware validates user roles
  4. Input Validation: express-validator for request validation
  5. SQL Injection Prevention: Sequelize parameterized queries
  6. CORS: Configured for allowed origins
  7. Helmet: Security headers
  8. Error Handling: No sensitive data in error responses

πŸ“ˆ Performance Optimizations

  1. Database Indexing: Indexes on frequently queried fields
  2. Connection Pooling: Configured in database settings
  3. Eager Loading: Optimized queries with includes
  4. Transaction Management: ACID compliance for critical operations
  5. Pagination Ready: Structure supports pagination for large datasets

πŸš€ Deployment

Environment Setup

  1. Set NODE_ENV=production
  2. Use strong JWT secret
  3. Configure database with production credentials
  4. Set up database backups
  5. Implement rate limiting
  6. Use HTTPS
  7. Set up monitoring and logging

Database Migration

# Production migration
NODE_ENV=production npx sequelize-cli db:migrate

PM2 Process Manager

npm install -g pm2
pm2 start server.js --name marketplace-backend
pm2 save
pm2 startup

πŸ› Troubleshooting

Common Issues

  1. Database Connection Error

    • Verify MySQL is running
    • Check database credentials in .env
    • Ensure database exists
  2. Migration Errors

    • Drop and recreate database
    • Run migrations again
    • Check migration order
  3. JWT Token Errors

    • Verify token is included in Authorization header
    • Check token format: Bearer <token>
    • Ensure token hasn't expired
  4. Port Already in Use

    • Change PORT in .env
    • Kill existing process: lsof -ti:3000 | xargs kill

πŸ“ Code Quality

  • Naming Convention: camelCase for all variables, functions, and APIs
  • Modular Structure: Clean separation of concerns
  • Error Handling: Comprehensive try-catch blocks
  • Comments: Inline documentation for complex logic
  • Consistent Formatting: ESLint ready
  • Production-Ready: Environment-based configuration

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

πŸ“§ Support

For issues or questions:

  • Check the Swagger documentation at /api-docs
  • Review the Postman collection
  • Examine seed data for examples
  • Check application logs

Built with using Node.js, Express, MySQL, and Sequelize

About

Marketplace backend built using Node.js + MySQL with JWT authentication, product/order modules, delivery routing, and Swagger-powered documentation.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published