Files
Guitar-Ecommerce/PROJECT_DOCUMENTATION.md
2026-09-16 17:36:46 +05:30

15 KiB

🎸 MERN Stack Modern Guitar Ecommerce Application

Complete Architecture, Workflow & Technical Documentation

This document provides a comprehensive technical guide on how the Modern Guitar Ecommerce Application works under the hood, detailing the MERN stack architecture, backend controllers, MongoDB database models, frontend state management, customer and admin workflows, and API endpoints.


📑 Table of Contents

  1. Architecture Overview
  2. Database Schema & Models (MongoDB)
  3. Backend API Architecture (Node & Express)
  4. Frontend Architecture (React, Vite & Redux Toolkit)
  5. End-to-End Application Workflows
  6. API Endpoints Reference
  7. Installation & Execution Guide

1. Architecture Overview

The application follows a Decoupled Architecture built on the MERN Stack:

 ┌─────────────────────────────────────────────────────────┐
 │               React 18 Customer & Admin Frontend        │
 │     (Vite + Tailwind CSS + Framer Motion + Redux)       │
 └────────────────────────────┬────────────────────────────┘
                              │ REST API Calls (Axios / JWT)
                              ▼
 ┌─────────────────────────────────────────────────────────┐
 │                Node.js & Express.js Backend             │
 │   Routes  ──►  Controllers  ──►  Services  ──►  Models  │
 └────────────────────────────┬────────────────────────────┘
                              │ Mongoose ODM
                              ▼
 ┌─────────────────────────────────────────────────────────┐
 │                    MongoDB Database                     │
 │          (16 Collections with Structured Schemas)       │
 └────────────────────────────┴────────────────────────────┘

Key Technologies Used:

  • Database: MongoDB (Mongoose ODM with indexed text search & references)
  • Backend: Node.js, Express.js, JWT (jsonwebtoken), Password Hashing (bcryptjs), Multer (Media upload), Nodemailer (Email engine), Helmet (Security), CORS, Rate Limiter.
  • Frontend: React 18, Vite, Tailwind CSS, Framer Motion (Animations), Redux Toolkit (Global Store), TanStack Query (Data Fetching), Lucide Icons, React Hook Form.

2. Database Schema & Models (MongoDB)

The backend features 16 MongoDB collections located in server/models/:

Collection / Model Description Key Fields
User Stores customer and admin accounts name, email, password (hashed), role (Customer, Admin), phone, addresses[]
Product Core guitar catalog items with rich specs name, slug, sku, brand, category, price, salePrice, stock, specs (body, neck, pickups, frets, bridge), variants[], images[], rating
Category Hierarchy for guitar types name, slug, description, image, displayOrder
Brand Guitar manufacturers name, slug, logo, description, website
Cart Shopping carts for users & guests user, sessionId, items[] (product, quantity, variantColor, price), couponCode
Wishlist User saved instruments user, products[]
Order Customer purchase orders orderNumber, user, orderItems[], shippingAddress, paymentMethod, orderStatus, statusHistory[], trackingNumber
InventoryHistory Audit trail for stock changes product, sku, changeType (Order Placed, Restock, Manual), quantityChanged, previousStock, newStock, reason
Review Customer product reviews user, product, rating, title, comment, isApproved
Coupon Promo discount codes code, discountType, discountValue, minPurchaseAmount, endDate
Banner Homepage hero sliders title, subtitle, desktopImage, mobileImage, buttonText, buttonLink
WebsiteSettings Global store branding siteName, tagline, contactEmail, phone, address, currencySymbol, logos
SocialMedia Dynamic social links platform, url, isEnabled
EmailTemplate Dynamic HTML emails name, subject, bodyHtml, placeholders[]
ContactMessage Customer contact submissions name, email, phone, subject, message, status

3. Backend API Architecture (Node & Express)

The backend follows the clean Routes → Controllers → Services → Models pattern:

  1. Routes (server/routes/): Map incoming HTTP endpoints (e.g. POST /api/products, PUT /api/orders/:id/status) to controller functions, applying authentication (protect) and authorization (authorize('Admin')) middlewares.
  2. Controllers (server/controllers/): Handle request data validation, invoke database queries through Mongoose models, format responses using standardized helper apiResponse.js, and trigger email notifications.
  3. Middlewares (server/middleware/):
    • authMiddleware.js: Verifies JWT tokens in Authorization: Bearer <token> headers and enforces role restrictions.
    • errorHandler.js: Intercepts Mongoose validation errors, duplicate keys, and invalid ObjectIds, returning clean JSON error payloads.
    • upload.js: Configures Multer for local disk storage of product images and banner media in server/uploads/.
  4. Email Sender (server/utils/emailSender.js): Loads dynamic EmailTemplate documents from MongoDB and performs placeholder replacement (e.g. {{customerName}}, {{orderId}}) before sending via Nodemailer.

4. Frontend Architecture (React, Vite & Redux Toolkit)

The frontend is structured in client/src/:

client/src/
├── api/            # Axios HTTP client with JWT interceptor
├── components/     # Reusable UI components (Navbar, Footer, ProductCard, Modals, Drawers)
├── pages/          # Customer & Admin pages
│   ├── customer/   # HomePage, ShopPage, ProductDetailPage, CartPage, CheckoutPage, etc.
│   └── admin/      # AdminDashboard, AdminProducts, AdminInventory, AdminOrders, etc.
├── store/          # Redux Toolkit Slices (auth, cart, wishlist, compare, ui)
└── index.css       # Tailwind CSS & custom scrollbars

Global Redux State Slices:

  • auth: Manages logged-in user profile, JWT token, and authentication state (login, register, logout).
  • cart: Manages shopping cart items, quantities, and coupon applications with persistent backend syncing.
  • wishlist: Synchronizes user saved guitars.
  • compare: Stores up to 4 instruments for side-by-side spec comparison.
  • ui: Controls floating modals (GuitarFinderModal, ProductQuickView), drawers, and toast notifications.

5. End-to-End Application Workflows

Customer Shopping Workflow

  1. Browse & Search: Customer lands on HomePage -> views Hero Banners -> filters products on ShopPage by Category, Brand, Guitar Type (Electric, Acoustic, Bass), Handedness, and Price range.
  2. Product Details & Spec Inspection: Clicking an item navigates to ProductDetailPage -> views high-res thumbnail gallery -> inspects luthier specs table (Body wood, Pickups, Scale length, Frets) -> selects Color/Finish variant.
  3. Cart & Coupons: Customer adds product to cart -> navigates to CartPage -> views Free Shipping Progress Bar -> enters promo code WELCOME10 for a 10% discount.
  4. Checkout & Order Placement: Proceeds to CheckoutPage -> enters shipping address -> selects payment method (Stripe Encrypted or Cash on Delivery) -> clicks Authorize & Place Order.
  5. Stock Deduction & Confirmation: Backend creates order document -> deducts inventory stock -> creates InventoryHistory audit entry -> sends Order Confirmation Email -> clears user cart -> redirects customer to OrderConfirmationPage.

Interactive Guitar Finder Tool

  • Triggered from Navbar or Home banner (GuitarFinderModal.jsx).
  • Asks 3 interactive questions:
    1. Instrument type (Electric, Acoustic, Bass, Classical)
    2. Target budget range ($800, $1800, $4000+)
    3. Hand orientation (Right-Handed, Left-Handed)
  • Calls POST /api/products/guitar-finder -> backend runs rule-based filtering on specs and ratings -> returns matching recommendations directly in the modal for instant cart addition.

Product Comparison Matrix

  • Customers click the compare button on up to 4 products -> floating CompareDrawer.jsx appears.
  • Navigating to /compare renders ComparePage.jsx showing a side-by-side spec table comparing body woods, pickups, fingerboards, scale lengths, and prices.

Admin Stock Audit & Inventory System

  • Admins access /admin/inventory -> view low-stock and out-of-stock alerts.
  • Admin selects a guitar, inputs new stock number, selects change type (Restock, Manual Adjustment, Order Cancelled, Returned), and adds a luthier note.
  • Backend updates product stock level AND logs an immutable audit document in InventoryHistory.

Order Fulfillment & Status Timeline

  • Admin views /admin/orders -> selects order -> updates status to Shipped -> enters courier tracking code (e.g. FDX-990842-US).
  • Backend saves status history timestamp -> triggers "Order Shipped" email to customer.
  • Customer views /track-order/:id -> sees visual horizontal progress timeline highlighting exact current fulfillment status.

6. API Endpoints Reference

Authentication (/api/auth)

  • POST /api/auth/register - Register customer account
  • POST /api/auth/login - Login user & receive JWT token
  • GET /api/auth/profile - Fetch profile (Protected)
  • PUT /api/auth/profile - Update profile & address book (Protected)

Products (/api/products)

  • GET /api/products - List products (filters: category, brand, guitarType, minPrice, maxPrice, search, sort, page)
  • POST /api/products/guitar-finder - Interactive recommendation engine
  • POST /api/products/compare - Compare multiple product IDs
  • GET /api/products/:slug - Detailed product specs by slug
  • POST /api/products - Create guitar (Admin)
  • PUT /api/products/:id - Update guitar specs & variants (Admin)
  • DELETE /api/products/:id - Delete guitar (Admin)

Cart & Wishlist (/api/cart, /api/wishlist)

  • GET /api/cart - Retrieve active session/user cart
  • POST /api/cart/add - Add item to cart (with stock validation)
  • PUT /api/cart/update - Change item quantity
  • DELETE /api/cart/item/:itemId - Remove item
  • POST /api/cart/coupon - Validate & apply coupon code
  • GET /api/wishlist & POST /api/wishlist/toggle - Manage saved items

Orders & Inventory (/api/orders, /api/inventory)

  • POST /api/orders - Place order & deduct stock
  • GET /api/orders/my-orders - List customer order history
  • GET /api/orders/:id - Get order receipt & status history
  • GET /api/orders/admin/all - List all store orders (Admin)
  • PUT /api/orders/:id/status - Update status & tracking number (Admin)
  • GET /api/inventory/overview - Stock overview & alerts (Admin)
  • POST /api/inventory/adjust - Adjust stock & log audit history (Admin)
  • GET /api/inventory/history - View stock audit trail log (Admin)

7. Installation & Execution Guide

1. Install All Dependencies

npm run install:all

2. Seed Database

Runs server/seed/seeder.js to clear old collections and populate demo data:

npm run seed

3. Run Development Servers

# Terminal 1: Backend Server (Port 5000)
npm run server

# Terminal 2: Frontend Client (Port 5173)
npm run client

4. Admin Credentials

  • Admin: admin@guitars.com | Password: Admin@123
  • Customer: john@example.com | Password: Customer@123