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.
- Features
- Tech Stack
- Project Structure
- Installation
- Configuration
- Database Setup
- Running the Application
- API Documentation
- Modules Overview
- AI Features
- Testing
- Deployment
- 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
- Dashboard with order management
- Accept/reject orders with partial acceptance
- Product catalog management
- Order status updates
- Delivery person assignment
- Analytics and summaries
- View assigned orders
- Update delivery status
- Upload proof of delivery
- Optimized route planning
- Daily performance tracking
- Route and beat management
- Attendance marking
- Store visit logging
- Secondary sales order creation
- Performance metrics
- Search sellers by location
- Place multi-product orders
- Real-time order tracking
- Raise complaints
- View order history
- 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
- 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
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
Ensure you have the following installed:
- Node.js (v14 or higher)
- MySQL (v8 or higher)
- npm or yarn
- Clone the repository
git clone <repository-url>
cd marketplace-backend- Install dependencies
npm install- Configure environment variables
cp .env.example .envEdit .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# Using Sequelize CLI
npx sequelize-cli db:createOr manually in MySQL:
CREATE DATABASE marketplace_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;npx sequelize-cli db:migrateThis will create all required tables with proper relationships and indexes.
npx sequelize-cli db:seed:allThis creates demo data with the following users:
| Role | 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 |
npm run devnpm startThe server will start on http://localhost:3000
curl http://localhost:3000/healthAccess interactive API documentation at:
http://localhost:3000/api-docs
All protected endpoints require a JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>
http://localhost:3000/api
POST /api/auth/register- Register new userPOST /api/auth/login- Login user
GET /api/seller/profile- Get seller profileGET /api/seller/dashboard- Get dashboard with ordersPUT /api/seller/orders/:orderId/accept- Accept orderPUT /api/seller/orders/:orderId/reject- Reject orderPUT /api/seller/orders/:orderId/status- Update order statusPOST /api/seller/orders/:orderId/assign-delivery- Assign delivery personGET /api/seller/products- List productsPOST /api/seller/products- Create productPUT /api/seller/products/:productId- Update productDELETE /api/seller/products/:productId- Delete productPATCH /api/seller/products/:productId/toggle-status- Toggle product status
GET /api/delivery/profile- Get profileGET /api/delivery/orders- Get assigned ordersPUT /api/delivery/orders/:orderId/status- Update delivery statusPOST /api/delivery/orders/:orderId/proof- Upload proof of deliveryGET /api/delivery/route- Get optimized routeGET /api/delivery/performance- Get daily performance
GET /api/salesman/profile- Get profileGET /api/salesman/routes- Get assigned routesGET /api/salesman/routes/:routeId/stores- Get stores in routePOST /api/salesman/attendance- Mark attendancePUT /api/salesman/attendance/checkout- Check outPOST /api/salesman/visits- Log store visitPOST /api/salesman/sales-orders- Create sales orderGET /api/salesman/sales-orders- Get sales ordersGET /api/salesman/performance- Get performance summary
GET /api/customer/profile- Get profileGET /api/customer/sellers- Search sellers by locationPOST /api/customer/orders- Place new orderGET /api/customer/orders/:orderId- Track orderGET /api/customer/orders- Get order historyPOST /api/customer/complaints- Raise complaintGET /api/customer/complaints- Get complaint history
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
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
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
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
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
Algorithm: Nearest Neighbor (Greedy Algorithm)
Process:
- Start from delivery person's current location
- Find nearest unvisited delivery location
- Move to that location
- Repeat until all deliveries are sequenced
- 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
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:
- Scan complaint description for category-specific keywords
- Count matches for each category
- Calculate confidence score
- Return category with highest score
-
Import the Postman collection (create from Swagger)
-
Set up environment variables:
baseUrl:http://localhost:3000/apitoken: JWT token from login response
-
Test workflow:
- Register/Login as different roles
- Use token in subsequent requests
- Test complete order lifecycle
- Verify transactions and relationships
- 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- Customer Workflow:
# Search sellers
GET /api/customer/sellers?city=Mumbai&pincode=400053
# Place order
POST /api/customer/orders
{
"sellerId": "...",
"items": [{"productId": "...", "quantity": 2}]
}- JWT Authentication: Secure token-based authentication
- Password Hashing: bcrypt with salt rounds
- Role-Based Access Control: Middleware validates user roles
- Input Validation: express-validator for request validation
- SQL Injection Prevention: Sequelize parameterized queries
- CORS: Configured for allowed origins
- Helmet: Security headers
- Error Handling: No sensitive data in error responses
- Database Indexing: Indexes on frequently queried fields
- Connection Pooling: Configured in database settings
- Eager Loading: Optimized queries with includes
- Transaction Management: ACID compliance for critical operations
- Pagination Ready: Structure supports pagination for large datasets
- Set
NODE_ENV=production - Use strong JWT secret
- Configure database with production credentials
- Set up database backups
- Implement rate limiting
- Use HTTPS
- Set up monitoring and logging
# Production migration
NODE_ENV=production npx sequelize-cli db:migratenpm install -g pm2
pm2 start server.js --name marketplace-backend
pm2 save
pm2 startup-
Database Connection Error
- Verify MySQL is running
- Check database credentials in
.env - Ensure database exists
-
Migration Errors
- Drop and recreate database
- Run migrations again
- Check migration order
-
JWT Token Errors
- Verify token is included in Authorization header
- Check token format:
Bearer <token> - Ensure token hasn't expired
-
Port Already in Use
- Change PORT in
.env - Kill existing process:
lsof -ti:3000 | xargs kill
- Change PORT in
- 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
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
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