Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ElectroMart — Production-Style Electronics E-Commerce Website

"Powering Your Digital Life."
A full-stack, production-grade electronics e-commerce platform built with Node.js, Express.js, EJS Server-Side Rendering (SSR), Bootstrap 5 / Modern CSS, and MongoDB Atlas (Mongoose).


🌟 Key Highlights & Features

1. 🚪 3 Dedicated, Role-Enforced Login Portals

  • Customer Portal (/login & /customer/login):
    • Consumer-focused blue/cyan storefront styling.
    • Role-restricted to shoppers (customer).
    • Integrated with Brevo Email OTP Verification and direct account registration links.
    • 1-Click Auto-Fill for quick evaluation (customer@electromart.demo).
  • Admin Control Center (/admin/login):
    • High-security dark slate & crimson enterprise theme with security badges.
    • Strict role validation—only authorized administrators can authenticate.
    • IP logging notice and compliance safeguards.
  • Delivery Partner Hub (/delivery/login):
    • Mobile-first, logistics & route dispatch styling with emerald accents.
    • Restricted to delivery agents and supervising admins.
  • Interactive Portal Switcher: Every login screen features a top pill banner ([ 🛍️ Customer ] [ 🚚 Delivery ] [ 🛡️ Admin ]) for 1-click cross-portal switching.
  • Smart Redirection & Session Isolation: Unauthenticated attempts to access /admin/* automatically redirect to /admin/login, /delivery/* to /delivery/login, and customer routes to /login. Sign-out intelligently returns users to their respective role login page.

2. 🔥 Hot Deals & Discounts System

  • Dedicated Endpoints: Direct access via /hot-deals and /deals.
  • Automatic Discovery: Automatically filters items with isDeal: true or active discount percentage (discount > 0), sorted by highest discount first.
  • Shop Integration: Interactive "Hot Deals Only" checkbox in the shop sidebar filter with active visual indicators and custom page headings.
  • Storewide Access: Directly linked in the top announcement bar, category navigation strip, homepage hero section, and footer.

3. 📝 Expanded & Modern Customer Registration

  • Generous Responsive Layout: Expanded container width up to 860px (col-12 col-sm-11 col-md-10 col-lg-9 col-xl-8) with comfortable padding (p-4 p-sm-5).
  • Membership Perks Banner: Highlights 10% Welcome Coupon (WELCOME10), Free Express Delivery, and 1-Year Official Warranty.
  • Clean 2-Column Grid: Full Name & Mobile Phone, Full Email, and Password with Confirmation & eye visibility toggles.
  • Email Verification: Built-in 6-digit OTP verification via Brevo API with expiration and resend handling.

4. 🛒 Complete E-Commerce Lifecycle

  • Zero Client-Side Calculation Trust: All cart subtotals, GST (18%), delivery fees, coupon logic, and stock availability are strictly calculated on the server.
  • Multi-Step Checkout: Indian address book management, review breakdown, and payment mode selection (Cash on Delivery & Mock Payment Gateway).
  • Real-Time Visual Order Tracking: Timeline state transitions (Order Placed $\rightarrow$ Confirmed $\rightarrow$ Packed $\rightarrow$ Assigned $\rightarrow$ Picked Up $\rightarrow$ Out for Delivery $\rightarrow$ Delivered).
  • Inventory State Machine: Atomically decrements stock with $inc: { stock: -quantity } and restores inventory if orders are cancelled.
  • Verified Buyer Reviews: Only verified customers who received the product can leave ratings & reviews, dynamically updating product average ratings.

🛠️ Technology Stack

Layer Technology Description
Backend Runtime Node.js (v18+) Non-blocking asynchronous I/O
Web Framework Express.js 4.x RESTful routing, middleware pipeline
Templating / SSR EJS 3.x Componentized modular views & partials
Styling & UI Vanilla CSS3 + Bootstrap 5.3 + FontAwesome 6 Custom responsive design system with dark & logistics modes
Database & ODM MongoDB / Mongoose 8.x Schema validation, atomic operations & indexing
Session Management express-session + connect-mongo Persistent MongoDB session store with TTL
Security & Headers helmet, bcryptjs, express-rate-limit Password hashing, CSP, and auth rate limiting
Email Service Brevo Transactional API 6-digit email OTP verification delivery
File Uploads multer Disk storage for product images

📁 Project Architecture & Directory Structure

electromart/
│
├── app.js                     # Express application setup, security & middleware pipeline
├── server.js                  # Server entry point (starts HTTP server & DB connection)
├── package.json               # NPM dependencies & lifecycle scripts
├── render.yaml                # Render Web Service deployment configuration
├── .env                       # Environment variables
├── .env.example               # Template environment configuration
├── README.md                  # Comprehensive project documentation
│
├── config/
│   ├── db.js                  # MongoDB Mongoose connection handler
│   └── session.js             # MongoStore session configuration
│
├── models/
│   ├── User.js                # Users with roles ('customer', 'admin', 'delivery') & addresses
│   ├── Category.js            # Product categories with icons & display orders
│   ├── Product.js             # Electronics items, specs array, discount & text search
│   ├── Cart.js                # Persistent customer cart with applied coupon
│   ├── Order.js               # Orders with items, payment, and tracking history
│   ├── Delivery.js            # Dispatch records linking orders to delivery agents
│   ├── Coupon.js              # Discount rules (WELCOME10, ELECTRO500, MEGA2026)
│   └── Review.js              # Verified buyer reviews & auto rating aggregation
│
├── middleware/
│   ├── authMiddleware.js      # requireAuth, redirectIfAuth, portal redirects, res.locals
│   ├── roleMiddleware.js      # RBAC middleware (requireAdmin, requireDelivery)
│   ├── errorMiddleware.js     # Centralized 404, 403, and 500 error handlers
│   └── uploadMiddleware.js    # Multer disk upload handler for product images
│
├── controllers/
│   ├── authController.js      # Customer, Admin & Delivery logins, Register, Brevo OTP, Logout
│   ├── customerController.js  # Homepage, Account profile, Address book, Wishlist
│   ├── productController.js   # Shop catalog, /hot-deals, /deals, product details
│   ├── cartController.js      # Cart management, item updates, coupon apply/remove
│   ├── orderController.js     # Checkout, order creation, order tracking, cancellation
│   ├── reviewController.js    # Verified review submission & deletion
│   ├── couponController.js    # Admin coupon creation, toggles & deletion
│   ├── adminController.js     # Real-time analytics, product CRUD, category & user management
│   └── deliveryController.js  # Agent dispatch console, assigned orders, status updates
│
├── routes/
│   ├── authRoutes.js          # /login, /admin/login, /delivery/login, /register, /logout
│   ├── customerRoutes.js      # /, /account, /wishlist
│   ├── productRoutes.js       # /shop, /hot-deals, /deals, /products/:slug
│   ├── cartRoutes.js          # /cart, /cart/add, /cart/update, /cart/remove, /cart/coupon
│   ├── orderRoutes.js         # /checkout, /orders, /orders/:id
│   ├── reviewRoutes.js        # /reviews/add, /reviews/delete
│   ├── couponRoutes.js        # /admin/coupons/*
│   ├── adminRoutes.js         # /admin/* (Dashboard, Products, Categories, Orders, Users)
│   └── deliveryRoutes.js      # /delivery/* (Dashboard, Orders, Status updates)
│
├── services/
│   ├── orderService.js        # Server-side pricing, inventory decrements & state machine
│   ├── deliveryService.js     # Agent assignment & tracking timeline synchronizer
│   ├── paymentService.js      # Mock gateway simulation & payment verification
│   └── emailService.js        # Brevo API email dispatcher for OTP verification
│
├── utils/
│   ├── generateOrderId.js     # Unique order identifier generator (e.g. EM-108241)
│   ├── validation.js          # Email, phone, and pincode validators
│   └── helpers.js             # Currency (₹ INR), date, and badge formatting helpers
│
├── views/
│   ├── partials/
│   │   ├── header.ejs         # Meta tags, Bootstrap 5 & FontAwesome CDN
│   │   ├── navbar.ejs         # Search bar, cart/wishlist counters, portal split dropdown
│   │   ├── footer.ejs         # Store directory, customer care, staff portal links
│   │   ├── flash.ejs          # Dismissible Bootstrap alert banners
│   │   ├── product-card.ejs   # Reusable product card with discount badges
│   │   ├── pagination.ejs     # Query-preserving pagination component
│   │   ├── admin-sidebar.ejs  # Admin dashboard sidebar with sign-out
│   │   └── delivery-sidebar.ejs # Delivery console mobile header & tabs
│   ├── auth/
│   │   ├── login.ejs          # Dedicated Customer sign-in with role switcher & autofill
│   │   ├── admin-login.ejs    # Dedicated Admin Control Center portal with autofill
│   │   ├── delivery-login.ejs # Dedicated Delivery Partner Hub portal with autofill
│   │   ├── register.ejs       # Wide 860px customer registration form
│   │   └── verify-otp.ejs     # 6-digit Brevo OTP verification form
│   ├── customer/
│   │   ├── home.ejs           # Hero banner, category grid, hot deals, best sellers
│   │   ├── account.ejs        # Customer profile editor & address management
│   │   └── wishlist.ejs       # Wishlist grid with move-to-cart
│   ├── products/
│   │   ├── shop.ejs           # Multi-filter sidebar, hot deals toggle, catalog grid
│   │   └── detail.ejs         # Product gallery, specs table, verified buyer reviews
│   ├── cart/
│   │   ├── index.ejs          # Cart breakdown, quantity controls, promo coupon input
│   │   └── checkout.ejs       # 3-Step checkout (Address, Order Review, Payment Mode)
│   ├── orders/
│   │   ├── index.ejs          # Order history listing
│   │   └── detail.ejs         # Detailed order summary & visual tracking timeline
│   ├── admin/
│   │   ├── dashboard.ejs      # Chart.js analytics graphs & KPI metric cards
│   │   ├── products/          # Product list (index.ejs) & Add/Edit form (form.ejs)
│   │   ├── categories/        # Category management (index.ejs)
│   │   ├── orders/            # Order list & agent assigner (index.ejs, detail.ejs)
│   │   ├── users/             # User directory with role & status toggles (index.ejs)
│   │   ├── coupons/           # Coupon management (index.ejs)
│   │   └── reviews/           # Product reviews moderation (index.ejs)
│   ├── delivery/
│   │   ├── dashboard.ejs      # Delivery agent KPI metrics & active queue
│   │   ├── orders.ejs         # Assigned orders list
│   │   └── detail.ejs         # Customer contact, COD indicator & status progression
│   └── errors/
│       ├── 404.ejs            # Page not found
│       ├── 403.ejs            # Access forbidden
│       └── 500.ejs            # Internal server error
│
├── public/
│   ├── css/
│   │   ├── style.css          # Core design system, glassmorphism & responsive utilities
│   │   ├── admin.css          # Admin dashboard sidebar, tables & analytics styling
│   │   └── delivery.css       # Mobile-first delivery console stylesheet
│   ├── js/
│   │   ├── main.js            # AJAX cart/wishlist, toasts, password eye toggles
│   │   ├── checkout.js        # Checkout address validation & gateway simulator
│   │   └── admin.js           # Chart.js renderers & dynamic specs repeater
│   └── images/                # Default avatars & placeholders
│
└── seed/
    └── seedDatabase.js        # Comprehensive seeder (40+ products, 14 categories, demo users)

🔑 Pre-Configured Login Credentials

For testing and evaluation, the customer portal features a 1-click Auto-Fill button, while administrative and delivery portals require manual credential entry for security:

Role Dedicated Login Portal Email Password Destination Dashboard
System Admin /admin/login vik7065ash@gmail.com vikash123 /admin/dashboard
Delivery Agent /delivery/login vik7065ash@gmail.com vikash123 /delivery/dashboard
Customer /login customer@electromart.demo Customer@12345 / and /account

💡 Note: You can also use the secondary admin credential admin@electromart.demo / Admin@12345 or secondary delivery credential delivery@electromart.demo / Delivery@12345.


🎟️ Active Demo Promo Coupons

Apply any of these valid promotional coupons during checkout on the /cart page:

  • WELCOME10: 10% OFF (Max discount ₹1,500 on orders $\ge$ ₹999)
  • ELECTRO500: Flat ₹500 OFF (On tech orders $\ge$ ₹4,999)
  • MEGA2026: 15% OFF (Max discount ₹3,000 on orders $\ge$ ₹14,999)

🚀 Quick Start & Local Setup

1. Prerequisites

  • Node.js (v18.0.0 or higher)
  • MongoDB (Local instance running on mongodb://127.0.0.1:27017 or MongoDB Atlas URI)

2. Install Dependencies

npm install

3. Environment Configuration

Create or verify your .env file in the project root:

NODE_ENV=development
PORT=3000
BASE_URL=http://localhost:3000
MONGODB_URI=mongodb://127.0.0.1:27017/electromart
SESSION_SECRET=electromart_super_secret_session_key_2026_prod
RAZORPAY_KEY_ID=rzp_test_electromart_mock_key
RAZORPAY_KEY_SECRET=electromart_mock_secret
BREVO_API_KEY=xkeysib-your-api-key
BREVO_SENDER_EMAIL=your-email@example.com
BREVO_SENDER_NAME=ElectroMart

4. Seed the Database

Initialize the 14 categories, 40+ products, demo accounts, active coupons, and sample orders:

npm run seed

5. Start the Development Server

# Development mode (with live reload via nodemon)
npm run dev

# Production mode
npm start

Open your browser and navigate to: http://localhost:3000


🔄 Core Business Workflows

1. Customer Shopping & Checkout Flow

  1. Catalog Exploration: Filter by Category, Brand, Price Range, In-Stock, Customer Rating, or Hot Deals Only.
  2. Cart Management: Add items with requested quantities; inventory is checked in real time. Apply valid coupons (WELCOME10, ELECTRO500, MEGA2026).
  3. Checkout: 3-step checkout selects/adds delivery addresses, computes 18% GST and free shipping thresholds (free over ₹999), and selects Cash on Delivery or Instant Online Sandbox Gateway.
  4. Order Confirmation: Unique order ID (e.g. EM-108241) is generated, inventory is deducted atomically, and tracking timeline is initialized.

2. Admin Assignment Flow

  1. Admin views live metrics, recent orders, and inventory alerts on /admin/dashboard.
  2. Admin opens /admin/orders, inspects order details, and selects an active delivery agent from the dropdown.
  3. System transitions order status to Assigned and creates a dispatch record.

3. Delivery Handover & COD Collection

  1. Agent signs into /delivery/login to see assigned runs.
  2. Agent advances state: Assigned $\rightarrow$ Processing $\rightarrow$ Picked Up $\rightarrow$ Out for Delivery $\rightarrow$ Delivered.
  3. For COD orders, agent collects the payment and marks delivery complete.
  4. Customer's tracking timeline updates live, unlocking verified review privileges.

4. Order Cancellation & Auto Inventory Restock

  • Orders can be cancelled while in eligible states (Pending, Confirmed, Processing, Packed, Assigned).
  • Server restores product stock automatically via restoreStock(order.items) and logs the cancellation timestamp and reason.

☁️ MongoDB Atlas Cloud Setup

To connect to MongoDB Atlas in the cloud:

  1. Create a cluster on MongoDB Atlas.
  2. In Database Access, create a user with read/write privileges.
  3. In Network Access, whitelist 0.0.0.0/0 (Allow from Anywhere for cloud hosting).
  4. In Connect $\rightarrow$ Drivers, copy the connection string:
    mongodb+srv://<username>:<password>@cluster0.mongodb.net/electromart?retryWrites=true&w=majority
    
  5. Update MONGODB_URI in .env.
  6. Run npm run seed to populate cloud catalog data.

🚀 Deployment on Render

This application is ready for 1-click deployment on Render:

  1. Connect your GitHub repository to Render.
  2. Create a new Web Service with:
    • Environment: Node
    • Build Command: npm install
    • Start Command: npm start
  3. Add Environment Variables:
    • NODE_ENV: production
    • PORT: 10000
    • MONGODB_URI: <Your MongoDB Atlas URI>
    • SESSION_SECRET: <Secure random secret>
    • BASE_URL: <Your Render Web Service URL>
    • BREVO_API_KEY: <Your Brevo API Key>
    • BREVO_SENDER_EMAIL: <Your Verified Brevo Email>
    • BREVO_SENDER_NAME: ElectroMart
  4. Deploy and run node seed/seedDatabase.js via the Render Shell to seed the production database.

🛡️ Security & Quality Checklist

  • Strict RBAC: Dedicated login portals and middleware preventing cross-role privilege escalation.
  • Atomic Inventory: Mongo $inc prevents race conditions on stock decrements.
  • Rate Limiting: express-rate-limit prevents brute force on all authentication portals.
  • Security Headers: helmet configured with Content Security Policy allowing required CDNs.
  • Session Persistence: MongoDB session store with automatic TTL cleanup.
  • Server-Side Computation: Zero client calculation trust for taxes, discounts, and totals.
  • Mobile-First Responsiveness: Tailored interfaces for Desktop, Tablet, and Mobile Delivery Agents.

📄 License

This project is open-source and available under the ISC License.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages