Skip to content
/ locus Public

Full-stack Inventory Management SaaS with Next.js 16, MongoDB, role-based access, dashboard analytics, stock tracking, and premium dark UI.

License

Notifications You must be signed in to change notification settings

m-taqii/locus

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

33 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎯 Locus - Inventory Management System

Next.js React MongoDB TailwindCSS NextAuth Recharts Resend License Version

Master Your Inventory β€” Precision. Control. Growth.

The operating system for modern commerce.

Live Demo Β· Report Bug Β· Request Feature


πŸ†• What's New in v0.9.0

πŸŽ‰ Major Feature Release! Password Reset, User Invitations, and Business Insights Dashboard!

πŸ”‘ Password Reset System

βœ… Forgot Password Page - Request password reset via email
βœ… Reset Password Page - Secure token-based password reset
βœ… Token Validation - 1-hour expiry with security checks
βœ… Branded Reset Emails - Professional HTML email templates
βœ… Support for Both Accounts - Works for Business owners and Staff

πŸ‘₯ User Invitation System

βœ… Email Invitations - Invite team members via email
βœ… Invitation Page - Beautiful onboarding experience
βœ… Self-Service Activation - Users create their own passwords
βœ… 7-Day Expiry - Secure invitation tokens
βœ… Role Assignment - Assign Admin or Staff role during invite
βœ… Pending Status - Users start as "pending" until activated
βœ… No Password Required - Admin doesn't set passwords for users

πŸ“ˆ Business Insights Dashboard

βœ… Insights Page - New /dashboard/insights with analytics
βœ… Sales Trend Chart - Line chart showing sales vs returns
βœ… Top Products Chart - Bar chart visualizing stock levels
βœ… Inventory Health Score - Overall health percentage (0-100%)
βœ… Turnover Rate - Monthly inventory turnover calculation
βœ… Dead/Fast/Slow Stock - Product velocity analysis
βœ… Date Range Filter - 7 days, 30 days, 90 days, or year
βœ… Recharts Integration - Beautiful, responsive charts

Complete authentication flow with self-service account management!

Previous Updates (v0.8.0)

βœ… Email Verification (OTP), Resend Integration, Branded Email Templates, Verify Page

Previous Updates (v0.7.0)

βœ… Backend Pagination, Pagination Component, Mobile Navigation, Admin Visibility Restriction

Previous Updates (v0.6.0)

βœ… Settings API, Profile/Business/Password updates, Business model extended

Previous Updates (v0.5.0)

βœ… Dashboard Analytics, Low Stock Alerts, Best Selling Staff Leaderboard

βœ… Stock Management System, Activity Logging, Stock History, Search Functionality

Previous Updates (v0.2.0)

βœ… Full CRUD, Edit Modals, Delete Confirmations, Toast Notifications, Role-Based UI Controls


πŸ“– Table of Contents


πŸ“– Overview

Locus is a modern, full-stack inventory management SaaS application built with Next.js 16 (App Router), React 19, and MongoDB. It provides businesses with a comprehensive platform to manage their inventory, track products, manage users, and maintain detailed logs of inventory operations.

v0.9.0 introduces password reset functionality, a user invitation system with email-based onboarding, and a comprehensive Business Insights dashboard. Combined with email verification, pagination, and role-based access control, Locus is a production-ready inventory management solution with enterprise-grade features.

The application features a dark-themed UI with stunning GSAP animations, glassmorphism effects, and a premium amber/orange gradient color scheme that creates an engaging user experience.

Key Highlights

  • 🏒 Multi-tenant Architecture - Each business has its own isolated data
  • πŸ” Secure Authentication - NextAuth.js with JWT session management
  • βœ‰οΈ Email Verification - OTP-based verification with Resend email service
  • πŸ”‘ Password Reset - Forgot password with secure token-based reset flow
  • πŸ‘₯ User Invitation System - Email invitations with self-service activation
  • πŸ“ˆ Business Insights - Charts, health scores, and inventory analytics
  • 🎭 Role-Based Access Control - Owner, Admin, and Staff roles with UI-level permissions
  • πŸ“¦ Complete Inventory Management - Track products with categories, SKUs, and thresholds
  • πŸ“Š Dashboard Analytics - Real-time statistics, sales tracking, and performance metrics
  • πŸ“‰ Interactive Charts - Line and bar charts powered by Recharts
  • πŸ“„ Pagination - Backend pagination for products and users with customizable page sizes
  • 🚨 Low Stock Alerts - Visual alerts for products below minimum threshold
  • πŸ† Staff Leaderboard - Track top performing staff by sales
  • πŸ“ Activity Logging - Complete audit trail of all inventory movements
  • πŸ” Search & Filter - Find products quickly by name or SKU
  • βš™οΈ Settings Management - Complete profile, business, and security settings
  • πŸ“± Mobile Navigation - Responsive hamburger menu with slide-out panel
  • 🎨 Modern UI/UX - Scroll-triggered animations, parallax effects, and glassmorphism

✨ Features

πŸ” Authentication & Security

  • NextAuth.js Integration with credentials provider
  • JWT-based Session Management with secure token handling
  • Email Verification System:
    • 6-digit OTP sent via email during registration
    • 10-minute expiry for security
    • Resend OTP with 60-second rate limiting
    • Professional branded email templates
    • Resend email service integration
  • Password Reset System:
    • Forgot password page at /login/forgot-password
    • Secure token-based reset with 1-hour expiry
    • Reset password page with token validation
    • Works for both Business owners and Staff
    • Professional reset email templates
  • User Invitation System:
    • Email-based team member invitations
    • Invitation page at /invitation for onboarding
    • 7-day token expiry for security
    • Self-service password creation
    • Users start as "pending" until activated
    • Role assignment during invitation (Admin/Staff)
  • Dual Login System - Supports both Business owners and Staff members
  • Password Encryption using bcrypt (10 rounds of hashing)
  • Protected API Routes with server-side session validation
  • Role-Based Access Control:
    • Owner Role: Full business access, sees all users including Admins
    • Admin Role: Manage users and products, can only see Staff (not other Admins)
    • Staff Role: View products, perform stock operations, see personal stats
    • API Level: Owner/Admin-only routes for create/delete operations
    • UI Level: Conditional rendering based on user role
  • Admin User Visibility: Admins are hidden from other Admins (Owner-only visibility)
  • Admin Restriction: Admins cannot create other Admins (Owner-only privilege)
  • Session Callbacks for custom user data in sessions

πŸ“¦ Inventory Management

  • Product CRUD Operations - Full Create, Read, Update, Delete functionality
  • Role-Based UI Controls:
    • Admin Only: Add Product, Delete Product buttons
    • All Users: View products, Edit products
  • Edit Modal - Pre-populated form for updating products
  • Delete Confirmation - Modal dialog before permanent deletion (Admin only)
  • Toast Notifications - Success/error feedback for all actions
  • Product Attributes:
    • Name, Price, SKU (Stock Keeping Unit)
    • Quantity tracking
    • Minimum threshold alerts
    • Category assignment
    • Status management (Active/Inactive)
    • Product images (placeholder support)
  • Category System with predefined categories:
    • Electronics, Clothing, Home & Kitchen
    • Beauty & Personal Care, Sports & Fitness
    • Books, Toys & Games, Furniture
    • Health & Safety, Others
  • Inventory Table View with role-based action buttons
  • Real-time Updates - Table refreshes after CRUD operations
  • Loading States - User feedback during async operations

πŸ‘₯ User & Business Management

  • Business Registration - Owner name, business name, email, password
  • Multi-User Support - Admins can add multiple staff members
  • User Management Dashboard - Full CRUD for staff members
  • Edit Modal - Update user details including optional password change
  • Delete Confirmation - Modal dialog before permanent deletion
  • Toast Notifications - Success/error feedback for all actions
  • User Attributes:
    • Name, Email, Password (hashed)
    • Role (Admin/Staff)
    • Status (Active/Inactive)
    • Business association (ObjectId reference)
  • Business Isolation - Users can only see data from their own business
  • Admin-Only Features - User management restricted to admins

πŸ“Š Dashboard Analytics

  • Statistics Cards:
    • Active Users count (Owner/Admin only)
    • Total Sales (stock-out quantities)
    • Total Products in inventory
  • Low Stock Alerts Section:
    • Visual list of products below minimum threshold
    • Shows current quantity and minimum threshold
    • Color-coded warnings (red for critical)
    • Category display for quick identification
  • Best Selling Staff Leaderboard (Owner/Admin only):
    • Top 3 staff members ranked by sales
    • Gold, Silver, Bronze ranking indicators
    • Total sales count per staff member
    • Visual icons (Trophy, Medal, Award)
  • Role-Based Dashboard Views:
    • Owner/Admin: See all team statistics and leaderboard
    • Staff: See personal sales and available products
  • Real-time Data: Dashboard refreshes with latest data on load
  • Quick Actions: Add Product button from dashboard (Owner/Admin only)

οΏ½ Business Insights

  • Insights Page - Dedicated /dashboard/insights analytics page
  • Interactive Charts (Recharts):
    • Line Chart: Sales vs Returns trend over time
    • Bar Chart: Top products by stock quantity
    • Responsive design with tooltips and legends
  • Inventory Health Score:
    • 0-100% overall health rating
    • Color-coded display (green/yellow/red)
    • Calculated from dead stock, overstock, and low stock counts
  • Key Metrics:
    • Turnover Rate: Monthly inventory turnover calculation
    • Avg. Days in Stock: Average holding time for products
    • Dead Stock Count: Products with no sales in 30+ days
    • Overstock Count: Products above 3x minimum threshold
  • Stock Analysis:
    • Fast Moving Stock: Products selling above average velocity
    • Slow Moving Stock: Products selling below average velocity
    • Dead Stock Alerts: Products needing attention
  • Date Range Filter:
    • Last 7 Days
    • Last 30 Days
    • Last 90 Days
    • This Year
  • Real-time Refresh: Manual refresh button for latest data
  • Loading States: Skeleton loading and error handling

οΏ½πŸ“Š Stock Management & Activity Logging

  • Stock Adjustment System - Manually adjust inventory levels
  • Stock-In Operations:
    • Add new inventory (shipments, restocking)
    • Optional reason/notes for adjustments
    • Real-time stock updates
  • Stock-Out Operations:
    • Remove inventory (sales, damage, theft)
    • Validation to prevent negative stock
    • Automatic quantity updates
  • Activity Logging:
    • Complete audit trail of all adjustments
    • Tracks: User, Product, Quantity, Type, Reason
    • Records previous and new quantities
    • Timestamps for every transaction
  • Stock History View:
    • Recent 10 adjustments displayed
    • Color-coded (green for in, red for out)
    • Filterable by product
    • Sortable by date (newest first)
  • Search Functionality:
    • Search products by name or SKU
    • Real-time filter as you type
    • Shows current stock levels
  • Stock Validation:
    • Prevents stock going below zero
    • Shows available quantity
    • Displays minimum threshold warnings

🎨 UI/UX Features

  • Landing Page with GSAP scroll animations:
    • Hero section with gradient text
    • Animated dashboard preview
    • Feature sections (Analytics & Security)
    • Parallax scrolling effects
    • Call-to-action sections
  • Dark Theme throughout the application
  • Glassmorphism Effects - Frosted glass panels with backdrop blur
  • Gradient Backgrounds - Ambient circular gradients
  • Responsive Sidebar - Collapsible navigation with smooth transitions
  • Modal Forms - Overlay modals for adding products and users
  • Loading States - User feedback during async operations
  • Error Handling - User-friendly error messages
  • Lucide Icons - Clean, modern iconography

πŸ“± Responsive Design

  • Mobile-First Approach
  • Adaptive Layouts - Different layouts for mobile, tablet, and desktop
  • Mobile Menu - Touch-friendly navigation
  • Responsive Tables - Optimized data display on smaller screens
  • Flexible Typography - Scales appropriately across devices

πŸ› οΈ Tech Stack

Frontend

  • Next.js 16.1.3 - React framework with App Router
  • React 19.2.3 - UI library with latest features
  • TailwindCSS 4 - Utility-first CSS framework
  • GSAP 3.14.2 - Professional-grade animation library
  • @gsap/react 2.1.2 - GSAP React integration
  • Recharts 3.7.0 - Composable charting library
  • Lucide React 0.562.0 - Beautiful icon library
  • Axios 1.13.2 - HTTP client for API requests

Backend

  • Next.js API Routes - Serverless API endpoints
  • NextAuth.js 4.24.13 - Authentication solution
  • MongoDB (via Mongoose 9.1.4) - NoSQL database
  • bcrypt 6.0.0 - Password hashing
  • Resend - Email service provider

Development Tools

  • ESLint 9 - Code linting
  • PostCSS - CSS processing
  • Tailwind PostCSS 4 - Tailwind processing

πŸ“ Project Structure

locus/
β”œβ”€β”€ app/                           # Next.js App Directory
β”‚   β”œβ”€β”€ api/                       # API Routes
β”‚   β”‚   β”œβ”€β”€ auth/                  # Authentication endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ [...nextauth]/     # NextAuth configuration
β”‚   β”‚   β”‚   β”‚   └── route.js       # Auth handler (credentials provider)
β”‚   β”‚   β”‚   β”œβ”€β”€ registerBusiness/  # Business registration
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ route.js       # POST - Register new business + send OTP
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ verify/        # Email verification
β”‚   β”‚   β”‚   β”‚   β”‚   └── route.js   # POST - Verify OTP code
β”‚   β”‚   β”‚   β”‚   └── resend-otp/    # Resend verification
β”‚   β”‚   β”‚   β”‚       └── route.js   # POST - Resend OTP (rate limited)
β”‚   β”‚   β”‚   β”œβ”€β”€ forgot-password/   # Password reset
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ route.js       # POST - Reset password with token
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ generate-token/# Generate reset token
β”‚   β”‚   β”‚   β”‚   β”‚   └── route.js   # POST - Send reset email
β”‚   β”‚   β”‚   β”‚   └── verify-token/  # Validate reset token
β”‚   β”‚   β”‚   β”‚       └── route.js   # POST - Check token validity
β”‚   β”‚   β”‚   └── users/             # User management
β”‚   β”‚   β”‚       β”œβ”€β”€ route.js       # GET/POST - Fetch/Invite users
β”‚   β”‚   β”‚       β”œβ”€β”€ verify-token/  # User invitation verification
β”‚   β”‚   β”‚       β”‚   └── route.js   # GET/POST - Validate & activate user
β”‚   β”‚   β”‚       └── [id]/          # Dynamic user routes
β”‚   β”‚   β”‚           └── route.js   # PATCH/DELETE - Update/Delete user
β”‚   β”‚   β”œβ”€β”€ products/              # Product management
β”‚   β”‚   β”‚   β”œβ”€β”€ route.js           # GET/POST - Fetch/Create products
β”‚   β”‚   β”‚   └── [id]/              # Dynamic product routes
β”‚   β”‚   β”‚       └── route.js       # PATCH/DELETE - Update/Delete product
β”‚   β”‚   β”œβ”€β”€ dashboard/             # Dashboard analytics
β”‚   β”‚   β”‚   └── route.js           # GET - Fetch dashboard statistics
β”‚   β”‚   β”œβ”€β”€ insights/              # Business insights analytics
β”‚   β”‚   β”‚   └── route.js           # GET - Fetch insights data with charts
β”‚   β”‚   β”œβ”€β”€ settings/              # Settings management
β”‚   β”‚   β”‚   └── account/           # Account settings
β”‚   β”‚   β”‚       └── route.js       # GET/PATCH - Fetch/Update settings
β”‚   β”‚   └── stock-adjustments/     # Stock management
β”‚   β”‚       └── route.js           # GET/POST - Fetch/Create stock adjustments
β”‚   β”‚
β”‚   β”œβ”€β”€ components/                # Reusable React components
β”‚   β”‚   β”œβ”€β”€ AddProducts.jsx        # Product creation modal form
β”‚   β”‚   β”œβ”€β”€ AddUser.jsx            # User creation modal form
β”‚   β”‚   β”œβ”€β”€ BarChart.jsx           # Bar chart component (Recharts)
β”‚   β”‚   β”œβ”€β”€ EditProduct.jsx        # Product edit modal form
β”‚   β”‚   β”œβ”€β”€ EditUser.jsx           # User edit modal form
β”‚   β”‚   β”œβ”€β”€ LineGraph.jsx          # Line chart component (Recharts)
β”‚   β”‚   β”œβ”€β”€ Pagination.jsx         # Reusable pagination component
β”‚   β”‚   β”œβ”€β”€ Toast.jsx              # Toast notification component
β”‚   β”‚   β”œβ”€β”€ Navbar.jsx             # Navigation with mobile menu
β”‚   β”‚   └── SessionWrapper.jsx     # NextAuth session provider
β”‚   β”‚
β”‚   β”œβ”€β”€ dashboard/                 # Protected dashboard area
β”‚   β”‚   β”œβ”€β”€ insights/              # Business insights page
β”‚   β”‚   β”‚   └── page.js            # Charts, health scores, analytics
β”‚   β”‚   β”œβ”€β”€ inventory/             # Inventory management page
β”‚   β”‚   β”‚   └── page.js            # Products table with pagination
β”‚   β”‚   β”œβ”€β”€ manage-stocks/         # Stock adjustment page
β”‚   β”‚   β”‚   └── page.js            # Stock-in/stock-out with history
β”‚   β”‚   β”œβ”€β”€ users/                 # User management page (Admin only)
β”‚   β”‚   β”‚   └── page.js            # Users table with pagination
β”‚   β”‚   β”œβ”€β”€ settings/              # Settings page
β”‚   β”‚   β”‚   └── page.js            # Profile, Business, Security settings
β”‚   β”‚   β”œβ”€β”€ layout.js              # Dashboard layout with sidebar
β”‚   β”‚   └── page.js                # Dashboard home with analytics
β”‚   β”‚
β”‚   β”œβ”€β”€ about/                     # About page
β”‚   β”‚   └── page.js                # About Locus information
β”‚   β”‚
β”‚   β”œβ”€β”€ privacy/                   # Privacy Policy page
β”‚   β”‚   └── page.js                # Privacy policy content
β”‚   β”‚
β”‚   β”œβ”€β”€ lib/                       # Utility functions
β”‚   β”‚   β”œβ”€β”€ db.js                  # MongoDB connection utility
β”‚   β”‚   β”œβ”€β”€ emailTemplates.js      # Branded HTML email templates
β”‚   β”‚   └── services/              # External services
β”‚   β”‚       └── email.js           # Resend email sending utility
β”‚   β”‚
β”‚   β”œβ”€β”€ login/                     # Login pages
β”‚   β”‚   β”œβ”€β”€ page.js                # Login form with NextAuth signIn
β”‚   β”‚   β”œβ”€β”€ forgot-password/       # Forgot password page
β”‚   β”‚   β”‚   └── page.js            # Request password reset form
β”‚   β”‚   └── reset-password/        # Reset password page
β”‚   β”‚       └── page.js            # New password form with token
β”‚   β”‚
β”‚   β”œβ”€β”€ register/                  # Registration pages
β”‚   β”‚   β”œβ”€β”€ page.js                # Business registration form
β”‚   β”‚   └── verify/                # Email verification page
β”‚   β”‚       └── page.js            # OTP input form
β”‚   β”‚
β”‚   β”œβ”€β”€ invitation/                # User invitation page
β”‚   β”‚   └── page.js                # Accept invitation & set password
β”‚   β”‚
β”‚   β”œβ”€β”€ favicon.ico                # Site favicon
β”‚   β”œβ”€β”€ globals.css                # Global styles and Tailwind imports
β”‚   β”œβ”€β”€ layout.js                  # Root layout with SessionProvider
β”‚   └── page.js                    # Landing page with GSAP animations
β”‚
β”œβ”€β”€ models/                        # Mongoose schemas
β”‚   β”œβ”€β”€ business.model.js          # Business/Owner schema
β”‚   β”œβ”€β”€ product.model.js           # Product schema
β”‚   β”œβ”€β”€ stockLogs.model.js         # Stock adjustment logs schema
β”‚   └── user.model.js              # User/Staff schema
β”‚
β”œβ”€β”€ public/                        # Static assets
β”‚   β”œβ”€β”€ logo.png                   # Locus logo
β”‚   β”œβ”€β”€ dashboard.png              # Dashboard preview image
β”‚   β”œβ”€β”€ analytics.png              # Analytics visualization
β”‚   β”œβ”€β”€ mobile.png                 # Mobile preview image
β”‚   β”œβ”€β”€ file.svg                   # File icon
β”‚   β”œβ”€β”€ globe.svg                  # Globe icon
β”‚   └── window.svg                 # Window icon
β”‚
β”œβ”€β”€ .env                           # Environment variables (gitignored)
β”œβ”€β”€ .gitignore                     # Git ignore rules
β”œβ”€β”€ LICENSE                        # MIT License
β”œβ”€β”€ eslint.config.mjs              # ESLint configuration
β”œβ”€β”€ jsconfig.json                  # JavaScript configuration
β”œβ”€β”€ next.config.mjs                # Next.js configuration
β”œβ”€β”€ package.json                   # Dependencies and scripts
β”œβ”€β”€ pnpm-lock.yaml                 # pnpm lock file
β”œβ”€β”€ pnpm-workspace.yaml            # pnpm workspace config
β”œβ”€β”€ postcss.config.mjs             # PostCSS configuration
└── README.md                      # This file

πŸš€ Getting Started

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js 18.x or higher (Download)
  • MongoDB - Local installation or MongoDB Atlas account (Setup Guide)
  • npm, yarn, pnpm, or bun package manager

Installation Steps

  1. Clone the repository

    git clone https://github.com/m-taqii/locus.git
    cd locus
  2. Install dependencies

    pnpm install
    # or
    npm install
    # or
    yarn install
    # or
    bun install
  3. Set up MongoDB

    • Option A: Local MongoDB

      # Start MongoDB service
      # Windows: Run MongoDB as a service
      # macOS/Linux: 
      mongod --dbpath /path/to/data/directory
    • Option B: MongoDB Atlas (Cloud)

      • Create a free cluster at MongoDB Atlas
      • Get your connection string
  4. Configure environment variables

    Create a .env file in the root directory:

    # Database
    MONGODB_URI=mongodb://localhost:27017/locus
    # Or for MongoDB Atlas:
    # MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/locus
    
    # NextAuth Configuration
    NEXTAUTH_SECRET=your-super-secret-key-change-this-in-production
    NEXTAUTH_URL=http://localhost:3000

    ⚠️ Security Note: Generate a secure random string for NEXTAUTH_SECRET using:

    openssl rand -base64 32
  5. Run the development server

    pnpm dev
    # or
    npm run dev
    # or
    yarn dev
    # or
    bun dev
  6. Open in browser

    Navigate to http://localhost:3000

  7. Create your first account

    • Click "Get Started" or "Register"
    • Fill in business details
    • You'll be redirected to the dashboard

πŸ” Environment Variables

Variable Description Example Required
MONGODB_URI MongoDB connection string mongodb://localhost:27017/locus βœ… Yes
NEXTAUTH_SECRET Secret key for JWT encryption random-32-char-string βœ… Yes
NEXTAUTH_URL Base URL for NextAuth http://localhost:3000 βœ… Yes
APP_URL Public URL for invitation/reset links http://localhost:3000 βœ… Yes
RESEND_API_KEY Resend API key for emails re_xxxxxxxxxxxxx βœ… Yes
EMAIL_FROM Sender email address Locus <noreply@yourdomain.com> βœ… Yes

Development vs Production

Development (.env.local):

MONGODB_URI=mongodb://localhost:27017/locus
NEXTAUTH_SECRET=dev-secret-key-not-for-production
NEXTAUTH_URL=http://localhost:3000
APP_URL=http://localhost:3000
RESEND_API_KEY=re_your_api_key
EMAIL_FROM=Locus <onboarding@resend.dev>

Production (.env.production):

MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/locus?retryWrites=true&w=majority
NEXTAUTH_SECRET=strong-production-secret-key-32chars+
NEXTAUTH_URL=https://yourdomain.com
APP_URL=https://yourdomain.com
RESEND_API_KEY=re_production_api_key
EMAIL_FROM=Locus <noreply@yourdomain.com>

πŸ—ƒοΈ Database Models

1. Business Model

File: models/business.model.js

Stores business/owner account information with email verification.

{
  ownerName: String (required),        // Owner's full name
  businessName: String (required),     // Business/company name
  industry: String (default: ""),      // Business industry
  address: String (default: ""),       // Street address
  city: String (default: ""),          // City
  country: String (default: ""),       // Country
  website: String (default: ""),       // Business website URL
  email: String (required, unique),    // Login email
  password: String (required, select: false), // Bcrypt hashed password
  role: String (default: "Owner"),     // User role (Owner)
  status: String (default: "Active"),  // Account status
  emailVerified: Boolean (default: false), // Email verification status
  otpCode: String,                     // 6-digit verification code
  otpExpiry: Date,                     // OTP expiration timestamp
  lastOtpSentAt: Date,                 // Rate limiting for OTP resend
  createdAt: Date,                     // Auto-generated
  updatedAt: Date                      // Auto-generated
}

Features:

  • Email verification with OTP
  • 10-minute OTP expiry
  • 60-second rate limiting for resend
  • Password excluded from queries by default

Relationships:

  • One-to-Many with Users (business owner β†’ staff members)
  • One-to-Many with Products (business β†’ inventory items)

2. User Model

File: models/user.model.js

Stores staff member information with invitation and password reset support.

{
  name: String (required),                          // User's full name
  business: ObjectId (required, ref: "Business"),   // Link to Business
  email: String (required, unique, 6-320 chars),    // Login email
  password: String (min 6 chars, default: null),    // Bcrypt hashed (set on invite accept)
  role: String (enum: ["Admin", "Staff"], default: "Staff"),
  status: String (enum: ["pending", "active", "inactive"], default: "pending"),
  inviteToken: String (default: null),              // Invitation token
  inviteTokenExpires: Date (default: null),         // 7-day expiry
  resetPasswordToken: String (default: null),       // Password reset token
  resetPasswordExpires: Date (default: null),       // 1-hour expiry
  createdAt: Date,                                  // Auto-generated
  updatedAt: Date                                   // Auto-generated
}

Features:

  • Email-based invitation system
  • Self-service password creation
  • Users start as "pending" until activation
  • Password reset support
  • 7-day invitation token expiry
  • Secure fields excluded from queries by default

Relationships:

  • Many-to-One with Business (multiple users β†’ one business)
  • One-to-Many with Products (user β†’ products they manage)
  • One-to-Many with Logs (user β†’ activity logs)

3. Product Model

File: models/product.model.js

Stores inventory product information.

{
  user: ObjectId (required, ref: "User"),      // Product owner/creator
  name: String (required),                     // Product name
  price: Number (required),                    // Product price
  sku: String (required),                      // Stock Keeping Unit
  quantity: Number (required),                 // Current stock quantity
  minThreshold: Number (required),             // Alert threshold
  category: String (required),                 // Product category
  image: String (required),                    // Image URL (placeholder)
  status: String (enum: ["active", "inactive"], default: "active"),
  createdAt: Date,                             // Auto-generated
  updatedAt: Date                              // Auto-generated
}

Relationships:

  • Many-to-One with User (products β†’ created by user)
  • One-to-Many with Logs (product β†’ activity logs)

Categories:

  • Electronics, Clothing, Home & Kitchen, Beauty & Personal Care
  • Sports & Fitness, Books, Toys & Games, Furniture
  • Health & Safety, Others

4. StockLogs Model

File: models/stockLogs.model.js

Tracks all stock adjustments and inventory movements.

{
  userId: ObjectId (ref: "User"),                   // Who made the adjustment
  role: String (enum: ["Admin", "Owner", "Staff"], required), // User's role
  businessId: ObjectId (required, ref: "Business"), // Business reference
  product: ObjectId (required, ref: "Product"),     // Which product
  productName: String (required),                   // Product name snapshot
  quantity: Number (required),                      // Amount adjusted
  type: String (enum: ["stock-in", "stock-out"], required), // Adjustment type
  reason: String (default: "Stock adjustment"),     // Optional reason/notes
  previousQuantity: Number (required),              // Stock before adjustment
  newQuantity: Number (required),                   // Stock after adjustment
  createdAt: Date,                                  // Auto-generated timestamp
  updatedAt: Date                                   // Auto-generated
}

Features:

  • Complete audit trail of all inventory changes
  • Captures before/after quantities for verification
  • Supports custom reasons for adjustments
  • Automatic timestamp tracking
  • Business isolation for multi-tenant queries
  • Role tracking for analytics and leaderboard
  • Used for Dashboard analytics and "Manage Stocks" page

πŸ›£οΈ API Routes

Dashboard Routes

GET /api/dashboard

File: app/api/dashboard/route.js

Fetch dashboard statistics and analytics data.

Headers: Requires authenticated session

Response (Success - Owner/Admin):

{
  "productsCount": 150,
  "users": 12,
  "totalSold": 1250,
  "lowStockProducts": [
    {
      "_id": "507f1f77bcf86cd799439013",
      "name": "Laptop",
      "quantity": 5,
      "minThreshold": 10,
      "category": "Electronics"
    }
  ],
  "topSellingStaff": [
    {
      "userId": "507f1f77bcf86cd799439012",
      "name": "John Smith",
      "email": "john@example.com",
      "role": "Staff",
      "totalSold": 450
    }
  ]
}

Response (Success - Staff):

{
  "productsCount": 150,
  "totalSold": 75,
  "lowStockProducts": [...]
}

Features:

  • Owner/Admin View:
    • Active users count (business-wide)
    • Total sales (all stock-out operations)
    • Low stock products (below threshold)
    • Top 3 selling staff with leaderboard
  • Staff View:
    • Total products available
    • Personal sales count only
    • Low stock products
  • Uses MongoDB aggregation for efficient queries
  • Business isolation via businessId

Insights Routes

GET /api/insights

File: app/api/insights/route.js

Fetch comprehensive business insights and analytics data for charts.

Headers: Requires authenticated session

Query Parameters:

Parameter Type Default Description
range String 30days Date range: 7days, 30days, 90days, year

Example: /api/insights?range=7days

Response (Success):

{
  "salesTrendData": [
    { "name": "Mon", "sales": 45, "returns": 5 },
    { "name": "Tue", "sales": 62, "returns": 8 },
    { "name": "Wed", "sales": 38, "returns": 3 }
  ],
  "productChartData": [
    { "name": "Laptop...", "quantity": 150, "fullName": "Laptop Pro 15" },
    { "name": "Mouse", "quantity": 85, "fullName": "Mouse" }
  ],
  "inventoryHealth": {
    "turnoverRate": 2.5,
    "avgDaysInStock": 12,
    "deadStockCount": 3,
    "overstockCount": 5,
    "healthScore": 78
  },
  "deadStock": [
    { "name": "Old Product", "quantity": 25, "daysSinceLastSale": "45 days" }
  ],
  "fastMoving": [
    { "name": "Popular Item", "velocity": "+150%", "totalSold": 125 }
  ],
  "slowMoving": [
    { "name": "Slow Product", "velocity": "-60%", "totalSold": 5 }
  ],
  "summary": {
    "totalProducts": 50,
    "totalStock": 2500,
    "totalSold": 850,
    "lowStockCount": 8
  }
}

Features:

  • Sales Trend Data - Line chart data for sales vs returns
  • Product Chart Data - Top 6 products by stock quantity
  • Inventory Health Score - 0-100% health calculation
  • Turnover Rate - Monthly inventory turnover
  • Dead Stock Analysis - Products with no sales in 30+ days
  • Fast Moving Stock - Products selling above average velocity
  • Slow Moving Stock - Products selling below average velocity
  • Overstock Detection - Products above 3x minimum threshold
  • Date Range Filtering - Configurable time periods
  • Uses MongoDB aggregation pipelines for performance

Settings Routes

GET /api/settings/account

File: app/api/settings/account/route.js

Fetch current user's profile and business data for settings page.

Headers: Requires authenticated session

Response (Success - Owner):

{
  "profile": {
    "name": "John Doe",
    "email": "john@acme.com",
    "role": "Owner"
  },
  "business": {
    "businessName": "Acme Corp",
    "industry": "retail",
    "address": "123 Main St",
    "city": "New York",
    "country": "USA",
    "website": "https://acme.com"
  }
}

Response (Success - Admin/Staff):

{
  "profile": {
    "name": "Jane Smith",
    "email": "jane@acme.com",
    "role": "Staff"
  },
  "business": {}
}

PATCH /api/settings/account?account=profile

File: app/api/settings/account/route.js

Update user's profile information.

Headers: Requires authenticated session

Request Body:

{
  "name": "John Doe Updated",
  "email": "john.new@acme.com"
}

Response (Success):

{
  "message": "Profile updated successfully"
}

PATCH /api/settings/account?account=business

File: app/api/settings/account/route.js

Update business information (Owner only).

Headers: Requires authenticated session (Owner role)

Request Body:

{
  "businessName": "Acme Corporation",
  "industry": "retail",
  "address": "456 Commerce Ave",
  "city": "Los Angeles",
  "country": "USA",
  "website": "https://acme.io"
}

Response (Success):

{
  "message": "Business updated successfully"
}

PATCH /api/settings/account?account=password

File: app/api/settings/account/route.js

Change user's password with validation.

Headers: Requires authenticated session

Request Body:

{
  "currentPassword": "oldPassword123",
  "newPassword": "newSecurePassword456",
  "confirmPassword": "newSecurePassword456"
}

Response (Success):

{
  "message": "Password changed successfully"
}

Response (Error - Wrong Password):

{
  "message": "Current password is incorrect"
}

Response (Error - Mismatch):

{
  "message": "Passwords do not match"
}

Features:

  • Current password verification required
  • Password hashing with bcrypt
  • Works for both Owner and User accounts
  • Validates password confirmation

Authentication Routes

POST /api/auth/registerBusiness

File: app/api/auth/registerBusiness/route.js

Register a new business account and send OTP verification email.

Request Body:

{
  "ownerName": "John Doe",
  "businessName": "Acme Corp",
  "email": "john@acme.com",
  "password": "securePassword123"
}

Response (Success):

{
  "message": "Business created",
  "ok": true,
  "businessId": "507f1f77bcf86cd799439011"
}

Process:

  1. Validates all input fields
  2. Checks email uniqueness
  3. Hashes password with bcrypt
  4. Generates 6-digit OTP code
  5. Sends verification email via Resend
  6. Creates business with emailVerified: false

Validations:

  • Email format validation (regex)
  • Password minimum 6 characters
  • All fields required
  • Email uniqueness check

POST /api/auth/registerBusiness/verify

File: app/api/auth/registerBusiness/verify/route.js

Verify email using OTP code.

Request Body:

{
  "otp": "123456"
}

Response (Success):

{
  "message": "Email verified successfully",
  "ok": true
}

Response (Error - Invalid OTP):

{
  "error": "Invalid OTP"
}

Response (Error - Expired OTP):

{
  "error": "OTP has expired"
}

Process:

  1. Finds business by OTP code
  2. Checks OTP expiry (10 minutes)
  3. Sets emailVerified: true
  4. Clears OTP code and expiry

POST /api/auth/registerBusiness/resend-otp

File: app/api/auth/registerBusiness/resend-otp/route.js

Resend OTP verification email with rate limiting.

Request Body:

{
  "id": "507f1f77bcf86cd799439011"
}

Response (Success):

{
  "message": "OTP resent successfully",
  "ok": true
}

Response (Error - Rate Limited):

{
  "error": "Please wait before resending OTP"
}

Features:

  • 60-second rate limiting between requests
  • Generates new 6-digit OTP
  • Updates expiry to 10 minutes from now
  • Sends branded email via Resend

POST /api/auth/users

File: app/api/auth/users/route.js

Invite a new user (staff member) to join the business via email.

Headers: Requires authenticated session (Owner/Admin)

Request Body:

{
  "name": "Jane Smith",
  "email": "jane@acme.com",
  "role": "Staff",
  "status": "pending"
}

Response (Success):

{
  "message": "Invitation sent successfully",
  "ok": true,
  "userId": "507f1f77bcf86cd799439012"
}

Features:

  • Sends branded invitation email to user
  • User starts with "pending" status
  • 7-day invitation token expiry
  • User sets their own password on accepting
  • Admins cannot invite other Admins
  • Includes business name and inviter name in email

GET /api/auth/users

File: app/api/auth/users/route.js

Fetch users belonging to the logged-in business with pagination.

Headers: Requires authenticated session

Query Parameters:

Parameter Type Default Description
page number 1 Current page number
limit number 10 Items per page

Example: /api/auth/users?page=2&limit=10

Response (Success):

{
  "users": [
    {
      "_id": "507f1f77bcf86cd799439012",
      "name": "Jane Smith",
      "email": "jane@acme.com",
      "role": "staff",
      "status": "active",
      "business": "507f1f77bcf86cd799439011",
      "createdAt": "2026-01-24T10:00:00.000Z",
      "updatedAt": "2026-01-24T10:00:00.000Z"
    }
  ],
  "pagination": {
    "currentPage": 2,
    "totalPages": 5,
    "totalItems": 47,
    "itemsPerPage": 10
  }
}

Permissions:

  • Owner: Can see all users (Staff + Admin)
  • Admin: Can only see Staff users (other Admins are hidden)

POST /api/auth/forgot-password/generate-token

File: app/api/auth/forgot-password/generate-token/route.js

Request a password reset link via email.

Request Body:

{
  "email": "john@acme.com"
}

Response (Success):

{
  "message": "Reset link sent! Check your email."
}

Features:

  • Generates secure 32-byte random token
  • 1-hour token expiry
  • Works for both Business and User accounts
  • Sends branded reset email
  • Silent failure for non-existent emails (security)

POST /api/auth/forgot-password/verify-token

File: app/api/auth/forgot-password/verify-token/route.js

Validate a password reset token.

Request Body:

{
  "token": "abc123..."
}

Response (Valid):

{
  "status": 200,
  "message": "Token is valid"
}

Response (Invalid/Expired):

{
  "status": 400,
  "error": "Invalid or expired token"
}

POST /api/auth/forgot-password

File: app/api/auth/forgot-password/route.js

Reset password using a valid token.

Request Body:

{
  "token": "abc123...",
  "password": "newSecurePassword123"
}

Response (Success):

{
  "status": 200,
  "message": "Password reset successfully"
}

Validations:

  • Token must be valid and not expired
  • Password 6-128 characters
  • Works for both Business and User accounts
  • Clears token after successful reset

GET /api/auth/users/verify-token

File: app/api/auth/users/verify-token/route.js

Validate a user invitation token.

Query Parameters:

Parameter Type Required Description
token String Yes Invitation token

Example: /api/auth/users/verify-token?token=abc123...

Response (Valid):

{
  "valid": true,
  "userName": "Jane Smith",
  "userEmail": "jane@acme.com",
  "role": "Staff"
}

Response (Invalid/Expired):

{
  "valid": false,
  "error": "Invalid or expired invitation"
}

POST /api/auth/users/verify-token

File: app/api/auth/users/verify-token/route.js

Accept an invitation and set password.

Request Body:

{
  "token": "abc123...",
  "password": "mySecurePassword123"
}

Response (Success):

{
  "message": "Account activated successfully! You can now login."
}

Process:

  1. Validates invitation token
  2. Hashes password with bcrypt
  3. Sets user status to "active"
  4. Clears invitation token
  5. User can now login

POST /api/auth/[...nextauth]

File: app/api/auth/[...nextauth]/route.js

NextAuth.js authentication handler (credentials provider).

Login Process:

  1. Checks User collection first
  2. If not found, checks Business collection
  3. Validates password with bcrypt
  4. Returns user data with session

Session Structure:

{
  user: {
    id: "507f1f77bcf86cd799439011",
    email: "john@acme.com",
    role: "Admin",
    businessId: "507f1f77bcf86cd799439011",
    businessName: "Acme Corp",
    name: "John Doe",         // For staff users
    ownerName: "John Doe"     // For business owners
  }
}

Product Routes

GET /api/products

File: app/api/products/route.js

Fetch products for the logged-in user's business with pagination.

Headers: Requires authenticated session

Query Parameters:

Parameter Type Default Description
page number 1 Current page number
limit number 10 Items per page

Example: /api/products?page=1&limit=10

Response (Success):

{
  "products": [
    {
      "_id": "507f1f77bcf86cd799439013",
      "name": "Laptop",
      "price": 999.99,
      "sku": "SKU-12345",
      "quantity": 50,
      "minThreshold": 10,
      "category": "Electronics",
      "image": "placeholder-url",
      "status": "active",
      "owner": "507f1f77bcf86cd799439011",
      "createdAt": "2026-01-25T10:00:00.000Z",
      "updatedAt": "2026-01-25T10:00:00.000Z"
    }
  ],
  "pagination": {
    "currentPage": 1,
    "totalPages": 15,
    "totalItems": 150,
    "itemsPerPage": 10
  },
  "message": "Products fetched successfully"
}

Features:

  • Backend pagination for efficient data loading
  • Sorted by newest first (createdAt: -1)
  • Business isolation via owner field

POST /api/products

File: app/api/products/route.js

Create a new product.

Headers: Requires authenticated session (Admin only)

Request Body:

{
  "name": "Laptop",
  "price": 999.99,
  "quantity": 50,
  "minThreshold": 10,
  "sku": "SKU-12345",
  "category": "Electronics",
  "status": "active"
}

Response (Success):

{
  "_id": "507f1f77bcf86cd799439013",
  "name": "Laptop",
  "price": 999.99,
  "sku": "SKU-12345",
  "quantity": 50,
  "minThreshold": 10,
  "category": "Electronics",
  "image": "placeholder-url",
  "status": "active",
  "owner": "507f1f77bcf86cd799439011",
  "message": "Product created successfully"
}

Authorization:

  • Requires "Admin" or "admin" role
  • Product automatically linked to the creator

PATCH /api/products/${id}

File: app/api/products/[id]/route.js

Update an existing product.

Headers: Requires authenticated session (Admin only)

URL Parameters:

  • id - MongoDB ObjectId of the product to update

Request Body:

{
  "name": "Updated Laptop Name",
  "price": 1099.99,
  "quantity": 45,
  "minThreshold": 15,
  "sku": "SKU-12345",
  "category": "Electronics",
  "status": "active"
}

Response (Success):

{
  "_id": "507f1f77bcf86cd799439013",
  "name": "Updated Laptop Name",
  "price": 1099.99,
  "sku": "SKU-12345",
  "quantity": 45,
  "minThreshold": 15,
  "category": "Electronics",
  "status": "active",
  "updatedAt": "2026-01-25T12:00:00.000Z"
}

Validations:

  • Valid MongoDB ObjectId format
  • User must be Admin
  • All existing validations apply

DELETE /api/products/${id}

File: app/api/products/[id]/route.js

Delete a product permanently.

Headers: Requires authenticated session (Admin only)

URL Parameters:

  • id - MongoDB ObjectId of the product to delete

Response (Success):

{
  "message": "Product deleted successfully"
}

Response (Error - Not Found):

{
  "message": "Product not found"
}

Validations:

  • Valid MongoDB ObjectId format
  • User must be Admin
  • Product must exist

PATCH /api/auth/users/${id}

File: app/api/auth/users/[id]/route.js

Update an existing user.

Headers: Requires authenticated session (Admin only)

URL Parameters:

  • id - MongoDB ObjectId of the user to update

Request Body:

{
  "name": "Updated Name",
  "email": "updated@email.com",
  "password": "",
  "role": "staff",
  "status": "active"
}

Note: Leave password field empty to keep existing password. If password is provided, it will be hashed before updating.

Response (Success):

{
  "message": "User updated successfully",
  "user": {
    "_id": "507f1f77bcf86cd799439012",
    "name": "Updated Name",
    "email": "updated@email.com",
    "role": "staff",
    "status": "active",
    "updatedAt": "2026-01-25T12:00:00.000Z"
  }
}

Validations:

  • Valid MongoDB ObjectId format
  • User must be Admin
  • Password hashed automatically if provided

DELETE /api/auth/users/${id}

File: app/api/auth/users/[id]/route.js

Delete a user permanently.

Headers: Requires authenticated session (Admin only)

URL Parameters:

  • id - MongoDB ObjectId of the user to delete

Response (Success):

{
  "message": "User deleted successfully"
}

Response (Error - Not Found):

{
  "message": "User not found"
}

Validations:

  • Valid MongoDB ObjectId format
  • User must be Admin
  • User must exist

Stock Management Routes

POST /api/stock-adjustments

File: app/api/stock-adjustments/route.js

Create a new stock adjustment (add or remove inventory).

Headers: Requires authenticated session

Request Body:

{
  "productId": "507f1f77bcf86cd799439013",
  "quantity": 50,
  "type": "stock-in",
  "reason": "New shipment from supplier"
}

Response (Success):

{
  "message": "Stock added successfully",
  "adjustment": {
    "_id": "507f1f77bcf86cd799439014",
    "userId": "507f1f77bcf86cd799439011",
    "product": "507f1f77bcf86cd799439013",
    "productName": "Laptop",
    "quantity": 50,
    "type": "stock-in",
    "reason": "New shipment from supplier",
    "previousQuantity": 100,
    "newQuantity": 150,
    "createdAt": "2026-01-26T10:00:00.000Z"
  },
  "product": {
    "_id": "507f1f77bcf86cd799439013",
    "name": "Laptop",
    "quantity": 150
  }
}

Response (Error - Insufficient Stock):

{
  "message": "Insufficient stock. Current quantity: 10"
}

Validations:

  • Product ID, quantity, and type are required
  • Quantity must be greater than 0
  • Type must be "stock-in" or "stock-out"
  • For stock-out: validates sufficient quantity available
  • Product must exist

Features:

  • Automatically updates product quantity
  • Creates audit log entry
  • Prevents negative stock levels

GET /api/stock-adjustments

File: app/api/stock-adjustments/route.js

Fetch all stock adjustments with optional filtering.

Headers: Requires authenticated session

Query Parameters:

  • limit (optional) - Number of records to return (default: 50)
  • productId (optional) - Filter by specific product

Response (Success):

{
  "adjustments": [
    {
      "_id": "507f1f77bcf86cd799439014",
      "userId": "507f1f77bcf86cd799439011",
      "product": {
        "_id": "507f1f77bcf86cd799439013",
        "name": "Laptop",
        "sku": "SKU-12345"
      },
      "productName": "Laptop",
      "quantity": 50,
      "type": "stock-in",
      "reason": "New shipment from supplier",
      "previousQuantity": 100,
      "newQuantity": 150,
      "createdAt": "2026-01-26T10:00:00.000Z",
      "updatedAt": "2026-01-26T10:00:00.000Z"
    }
  ]
}

Features:

  • Returns most recent adjustments first
  • Populates product details
  • Supports pagination via limit
  • Can filter by product

πŸ“„ Pages & Routes

Public Pages

Route File Description
/ app/page.js Landing Page - Hero section, features, CTA with GSAP animations
/login app/login/page.js Login Page - Email/password form with NextAuth integration
/register app/register/page.js Registration Page - Business signup form

Protected Pages (Requires Authentication)

Route File Description Access
/dashboard app/dashboard/page.js Dashboard Home - Overview with welcome message All Users
/dashboard/inventory app/dashboard/inventory/page.js Inventory Management - Products table, add/edit/delete All Users
/dashboard/manage-stocks app/dashboard/manage-stocks/page.js Stock Management - Adjust inventory, view history All Users
/dashboard/users app/dashboard/users/page.js User Management - Staff table, add/edit/delete Admin Only
/dashboard/settings app/dashboard/settings/page.js Settings - Profile, business, security (fully functional) All Users

🧩 Components

Landing Page Components

Navbar.jsx

Location: app/components/Navbar.jsx

Features:

  • Responsive navigation bar
  • Logo linking to home
  • Dynamic auth state (Login/Register vs Dashboard)
  • Session-aware display
  • Gradient hover effects

Usage:

import Navbar from '@/app/components/Navbar'

<Navbar />

Dashboard Components

SessionWrapper.jsx

Location: app/components/SessionWrapper.jsx

Features:

  • Wraps app with NextAuth SessionProvider
  • Enables useSession hook throughout app

Usage:

import SessionWrapper from '@/app/components/SessionWrapper'

<SessionWrapper>
  {children}
</SessionWrapper>

AddProducts.jsx

Location: app/components/AddProducts.jsx

Features:

  • Modal overlay with glassmorphism
  • Product creation form with validations
  • Real-time form state management
  • Category dropdown (10 categories)
  • Status toggle (Active/Inactive)
  • Loading states and error handling
  • Click-outside-to-close functionality

Props:

  • setAddProductOpen(boolean) - Function to toggle modal visibility

Form Fields:

  • Product Name (text, required)
  • Price (number, required)
  • Quantity (number, required)
  • Minimum Threshold (number, required)
  • SKU (text, required, format: SKU-XXXXX)
  • Category (select, required)
  • Status (select, default: active)

AddUser.jsx

Location: app/components/AddUser.jsx

Features:

  • Modal overlay for user creation
  • Staff member registration form
  • Role selection (Admin/Staff)
  • Status selection (Active/Inactive)
  • Automatic refresh on successful creation
  • Password validation (min 6 chars)
  • Email validation (regex)

Props:

  • setAddUserOpen(shouldRefetch) - Function to toggle modal and trigger refetch

Form Fields:

  • Name (text, required, min 3 chars)
  • Email (email, required)
  • Password (password, required, min 6 chars)
  • Role (select: Admin/Staff)
  • Status (select: Active/Inactive)

Dashboard Layout (layout.js)

Location: app/dashboard/layout.js

Features:

  • Collapsible Sidebar:
    • Dashboard, Inventory, Users (Admin only), Settings
    • Icon-only mode when collapsed
    • Smooth width transitions
    • Active route highlighting
    • Logout button
  • Top Navigation:
    • Logo (desktop)
    • Hamburger menu (mobile)
    • User avatar and name display
  • Responsive Design:
    • Mobile: Overlay sidebar with backdrop
    • Desktop: Fixed sidebar with resize
  • Session Integration:
    • Displays current user name
    • Role-based menu items

Icons Used (Lucide):

  • LayoutDashboard - Dashboard
  • Package - Inventory
  • Users - User Management
  • Settings - Settings
  • LogOut - Logout
  • PanelRightOpen/Close - Sidebar toggle

EditProduct.jsx

Location: app/components/EditProduct.jsx

Features:

  • Modal overlay with glassmorphism for editing products
  • Pre-populated form with existing product data
  • Real-time form state management
  • Category dropdown (10 categories)
  • Status toggle (Active/Inactive)
  • Toast notifications on success/error
  • Automatic table refresh after update
  • Loading states and error handling

Props:

  • setEditProductOpen(boolean) - Function to toggle modal visibility
  • setToast(object) - Function to show toast notifications
  • product(object) - Product object to edit
  • fetchProducts() - Function to refresh product list

API Call:

  • PATCH /api/products/${productId} - Updates product

Form Fields:

  • Product Name (text, required, pre-filled)
  • Price (number, required, pre-filled)
  • Quantity (number, required, pre-filled)
  • Minimum Threshold (number, required, pre-filled)
  • SKU (text, required, pre-filled)
  • Category (select, required, pre-filled)
  • Status (select, pre-filled)

EditUser.jsx

Location: app/components/EditUser.jsx

Features:

  • Modal overlay for editing staff members
  • Pre-populated form with user data
  • Optional password update (leave blank to keep current)
  • Role modification (Admin/Staff)
  • Status modification (Active/Inactive)
  • Toast notifications on success/error
  • Automatic password hashing when changed
  • Automatic table refresh after update

Props:

  • setEditUserOpen(boolean) - Function to toggle modal visibility
  • user(object) - User object to edit
  • fetchUsers() - Function to refresh user list
  • setToast(object) - Function to show toast notifications

API Call:

  • PATCH /api/auth/users/${userId} - Updates user

Form Fields:

  • Name (text, required, pre-filled)
  • Email (email, required, pre-filled)
  • Password (password, optional - leave blank to keep current)
  • Role (select: Admin/Staff, pre-filled)
  • Status (select: Active/Inactive, pre-filled)

Toast.jsx

Location: app/components/Toast.jsx

Features:

  • Fixed position toast notifications (top-right corner)
  • Success (green) and error (red) variants
  • Auto-dismiss after configurable duration (default: 3s)
  • Manual dismiss with close button
  • Animated progress bar showing time remaining
  • Slide-in animation on appear
  • Glassmorphism backdrop with colored border
  • Lucide icons (CheckCircle for success, XCircle for error)

Props:

  • message(string) - The message to display
  • type(string) - Either "success" or "error"
  • onClose(function) - Callback to close toast
  • duration(number) - Auto-dismiss time in ms (default: 3000)

Usage:

const [toast, setToast] = useState(null)

// Show success toast
setToast({
  message: 'Product created successfully',
  type: 'success'
})

// Show error toast
setToast({
  message: 'Failed to create product',
  type: 'error'
})

// Render toast
{toast && (
  <Toast
    message={toast.message}
    type={toast.type}
    onClose={() => setToast(null)}
  />
)}

Settings Page

Location: app/dashboard/settings/page.js

Features:

  • Three-Tab Interface: Profile, Business, Security
  • Profile Management:
    • Update user name and email
    • Avatar upload placeholder
    • Phone number field
    • Location information
    • Session-aware data loading
  • Business Settings:
    • Business name and industry
    • Tax ID/Business registration
    • Full address (street, city, state, zip, country)
    • Email and phone contacts
    • Timezone selection
  • Security Settings:
    • Change password functionality
    • Current password verification
    • New password with confirmation
    • Password strength validation
    • Password matching validation
  • Success Feedback:
    • Toast notifications on save
    • Loading states during updates
    • Auto-populated from session

State Management:

const [activeTab, setActiveTab] = useState('profile')
const [profileData, setProfileData] = useState({
  name: session?.user?.name || '',
  email: session?.user?.email || '',
  phone: '',
  location: ''
})
const [businessData, setBusinessData] = useState({
  businessName: session?.user?.businessName || '',
  industry: '',
  taxId: '',
  // ... address fields
})
const [passwordData, setPasswordData] = useState({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

API Integration:

  • Currently uses simulated save (setTimeout)
  • Ready for API endpoints:
    • PATCH /api/auth/profile - Update profile
    • PATCH /api/businesses/${id} - Update business
    • POST /api/auth/change-password - Change password

Icons Used (Lucide):

  • User - Profile tab
  • Building2 - Business tab
  • Lock - Security tab
  • Camera - Avatar upload
  • Save - Save buttons

πŸ”‘ Authentication Flow

Registration Flow

  1. User visits /register
  2. Fills form: Owner Name, Business Name, Email, Password
  3. Client validation: Email format, password length
  4. POST request to /api/auth/registerBusiness
  5. Server validation: Email uniqueness, all fields present
  6. Password hashing: bcrypt with 10 salt rounds
  7. Database insertion: New Business document created
  8. Redirect to /dashboard (or login)

Login Flow

  1. User visits /login
  2. Fills form: Email, Password
  3. Client calls signIn("credentials", {...})
  4. NextAuth handler at /api/auth/[...nextauth]
  5. Checks User collection β†’ if not found, checks Business collection
  6. Password verification: bcrypt compare
  7. JWT creation: Session token with user data
  8. Session callbacks: Add custom fields to session
  9. Redirect to /dashboard

Session Management

Session Data Structure:

const session = {
  user: {
    id: "mongo-object-id",
    email: "user@example.com",
    role: "Admin" | "staff",
    businessId: "business-mongo-id",
    businessName: "Business Name",
    name: "User Name",           // Staff members
    ownerName: "Owner Name"      // Business owners
  },
  expires: "2026-02-25T00:00:00.000Z"
}

Accessing Session:

// Client Component
import { useSession } from 'next-auth/react'

const { data: session, status } = useSession()
console.log(session?.user?.name)

// Server Component / API Route
import { getServerSession } from 'next-auth'
import { authOptions } from '@/app/api/auth/[...nextauth]/route'

const session = await getServerSession(authOptions)

Protected Routes

Client-side Protection:

// Uses SessionProvider context
const { data: session } = useSession()
if (!session) router.push('/login')

Server-side Protection:

// API routes validate session
const session = await getServerSession(authOptions)
if (!session) {
  return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}

🎨 Design System

Color Palette

Primary Colors:

/* Amber/Orange Gradient */
--primary-start: #a34b27;
--primary-mid: #F0A728;
--primary-end: #9C2906;

/* Backgrounds */
--bg-dark: #0a050a;
--bg-card: #1a1a1e;
--bg-sidebar: #242529;

/* Text */
--text-primary: #ffffff;
--text-secondary: rgba(255, 255, 255, 0.6);
--text-muted: rgba(255, 255, 255, 0.4);

Usage Examples:

/* Gradient Button */
bg-linear-to-r from-[#a34b27] to-[#F0A728]

/* Gradient Text */
bg-linear-to-tl from-[#F0A728] to-[#9C2906] bg-clip-text text-transparent

/* Dark Background */
bg-[#1a1a1e]

Typography

Font Stack:

  • System fonts with Geist fallback (Next.js default)

Text Sizes:

/* Headlines */
text-8xl (96px)  - Hero titles
text-6xl (60px)  - Section titles
text-4xl (36px)  - Modal titles
text-2xl (24px)  - Page titles

/* Body */
text-xl (20px)   - Large body
text-base (16px) - Default body
text-sm (14px)   - Small text
text-xs (12px)   - Labels

Effects

Glassmorphism:

/* Glass Panel */
backdrop-blur-md bg-white/5 border border-white/10

/* Strong Glass */
backdrop-blur-2xl bg-white/5 border border-white/15

Shadows:

/* Glow Effect */
hover:shadow-[0_8px_25px_rgba(255,153,51,0.45)]

/* Large Glow */
shadow-[0_10px_60px_rgba(163,75,39,0.7)]

/* Standard Shadow */
shadow-2xl shadow-[#a34b27]/20

Animations:

/* GSAP Timeline */
- Fade in from opacity 0
- Slide from left/right (x: -50/50)
- Scale effects (scale: 0.8)
- Parallax scroll (scrub: 1)

/* CSS Transitions */
transition-all duration-300 ease-in-out
hover:brightness-110
hover:scale-105

Components Styling

Buttons:

// Primary Button
className="bg-linear-to-r from-[#a34b27] to-[#F0A728] 
           text-white px-5 py-2 rounded-xl 
           font-semibold 
           hover:shadow-[0_8px_25px_rgba(255,153,51,0.45)] 
           hover:brightness-110 
           transition-all duration-300 ease-in-out"

// Ghost Button
className="backdrop-blur-md bg-white/5 
           border border-white/10 
           text-white px-8 py-4 rounded-full
           hover:bg-white/10 
           hover:border-[#a34b27]/50"

Input Fields:

className="p-2 rounded-lg 
           bg-white/10 
           focus:border-[#a34b27] 
           focus:border focus:outline-none 
           focus:shadow focus:shadow-[#a34b27] 
           transition-all duration-300 ease-in-out"

Cards:

className="p-6 rounded-2xl 
           bg-white/5 
           border border-white/10 
           backdrop-blur-md"

πŸ“œ Available Scripts

Command Description
pnpm dev Start development server on port 3000
pnpm build Build production bundle
pnpm start Start production server
pnpm lint Run ESLint for code quality

Note: You can also use npm run, yarn, or bun instead of pnpm.

Development:

pnpm dev
# or: npm run dev / bun dev
  • Runs on http://localhost:3000
  • Hot Module Replacement (HMR) enabled
  • Error overlay in browser

Production:

pnpm build
pnpm start
# or: npm run build && npm run start
  • Optimized bundle
  • Server-side rendering
  • Static page generation where applicable

πŸ› Known Issues & Limitations

Current State (v0.9.0)

βœ… Fully Implemented:

  • βœ… Business registration and authentication
  • βœ… Email verification with OTP (6-digit code)
  • βœ… OTP resend with rate limiting (60 seconds)
  • βœ… Professional branded email templates
  • βœ… Resend email service integration
  • βœ… User management (Create, Read, Update, Delete)
  • βœ… Product management (Create, Read, Update, Delete)
  • βœ… Stock management & adjustments (Stock-In/Stock-Out)
  • βœ… Activity logging (Complete audit trail)
  • βœ… Stock history view with search
  • βœ… Dashboard with collapsible sidebar navigation
  • βœ… Landing page with GSAP animations
  • βœ… Role-based access control (API & UI level)
  • βœ… Session management with NextAuth
  • βœ… Toast notifications for success/error feedback
  • βœ… Delete confirmations for products and users
  • βœ… Edit functionality for products and users
  • βœ… Form validations
  • βœ… Admin-only UI controls (Add/Delete buttons)
  • βœ… Settings page with full API integration
  • βœ… Profile updates (name, email)
  • βœ… Business settings (Owner only)
  • βœ… Password change functionality
  • βœ… Dashboard analytics (statistics, low stock alerts)
  • βœ… Best selling staff leaderboard
  • βœ… Owner role with full business access
  • βœ… Admin visibility restriction (Admins can't see other Admins)
  • βœ… Admin creation restriction (Admins can't create Admins)
  • βœ… Backend pagination for Products and Users
  • βœ… Reusable Pagination component
  • βœ… Mobile navigation (hamburger menu)
  • βœ… About and Privacy pages
  • βœ… Business Insights page with interactive charts
  • βœ… Inventory health score (0-100%)
  • βœ… Sales trend line chart
  • βœ… Top products bar chart
  • βœ… Dead/Fast/Slow moving stock analysis
  • βœ… Recharts integration
  • βœ… Password reset (forgot password with email)
  • βœ… User invitation system (email-based onboarding)
  • βœ… Pending user status (activated on invite accept)
  • βœ… Self-service password creation for invited users
  • βœ… Reset password page with token validation

❌ Not Yet Implemented:

  • ❌ Advanced filtering (by category, status, etc.)
  • ❌ Image upload for products (currently uses placeholder)
  • ❌ Export functionality (CSV/PDF)
  • ❌ Bulk operations (multi-select delete/update)
  • ❌ Product categories management (hardcoded list)
  • ❌ Invitation resend functionality

Known Issues:

  • Product image field requires a value but doesn't support actual file uploads yet
  • Avatar upload UI exists but functionality not yet implemented
  • Toast notifications use fixed 3-second duration

πŸ—ΊοΈ Roadmap

Phase 1: MVP Completion βœ… COMPLETE

  • βœ… Basic authentication
  • βœ… Product full CRUD (Create, Read, Update, Delete)
  • βœ… User full CRUD (Create, Read, Update, Delete)
  • βœ… Toast notifications
  • βœ… Delete confirmations
  • βœ… Form validation improvements
  • βœ… Role-based UI controls

Phase 2: Core Features βœ… COMPLETE

  • βœ… Activity logging implementation
  • βœ… Stock adjustment system (Stock-in/Stock-out)
  • βœ… Search products (by name/SKU)
  • βœ… Settings page (Profile, Business, Security)
  • βœ… Dashboard with collapsible sidebar
  • βœ… Role-based access control (UI + API)
  • βœ… Toast notifications system
  • βœ… Complete audit trail

Phase 3: Enhanced UX βœ… COMPLETE

  • βœ… Dashboard analytics/statistics
  • βœ… Low stock alerts/notifications
  • βœ… Best selling staff leaderboard
  • βœ… Owner role implementation
  • βœ… Settings API (profile, business, password)
  • βœ… Business model extension (address, industry, website)
  • βœ… Backend pagination (Products, Users)
  • βœ… Pagination component (reusable)
  • βœ… Mobile navigation (hamburger menu)
  • βœ… About and Privacy pages
  • βœ… Email verification (OTP system)
  • βœ… Resend email service integration
  • βœ… Branded email templates
  • βœ… Admin visibility restriction
  • βœ… Admin creation restriction
  • βœ… Business Insights page
  • βœ… Interactive charts (Recharts)
  • βœ… Inventory health score
  • βœ… Sales trend & product charts
  • βœ… Dead/Fast/Slow stock analysis
  • βœ… Date range filtering
  • βœ… Password reset (forgot password)
  • βœ… User invitation system
  • βœ… Self-service account activation
  • βœ… Pending user status

Phase 4: Advanced Features (Current Focus)

  • Advanced filtering (category, status, date range)
  • Bulk operations (multi-select)
  • Image upload for products
  • Avatar upload for users
  • Invitation resend functionality
  • Export data (CSV, PDF)
  • Print-friendly views
  • Barcode scanning
  • QR code generation for products
  • Multi-location inventory
  • Supplier management
  • Purchase orders
  • Sales tracking
  • API documentation
  • Webhook support

Phase 5: SaaS Transformation

  • πŸ’³ Subscription-based pricing (Stripe integration)
  • ☁️ Hosted cloud solution (Vercel/AWS deployment)
  • 🏒 Enterprise features:
    • SSO (Single Sign-On)
    • Advanced permissions
    • Audit logs
    • SLA guarantees
    • Priority support
  • πŸ”Œ Third-party integrations:
    • Shopify, WooCommerce
    • QuickBooks, Xero
    • Slack, Discord notifications
    • Zapier/Make automation

🀝 Contributing

Contributions are welcome! This project is open-source and we encourage community involvement.

How to Contribute

  1. Fork the repository

    git clone https://github.com/yourusername/locus.git
  2. Create a feature branch

    git checkout -b feature/amazing-feature
  3. Make your changes

    • Write clean, documented code
    • Follow existing code style
    • Add comments where necessary
  4. Test your changes

    npm run dev
    # Test thoroughly in browser
  5. Commit your changes

    git commit -m 'Add some amazing feature'
  6. Push to your branch

    git push origin feature/amazing-feature
  7. Open a Pull Request

    • Describe what you changed
    • Reference any related issues

Development Guidelines

Code Style:

  • Use functional components and hooks
  • Follow Next.js best practices
  • Use meaningful variable names
  • Add JSDoc comments for functions

Commit Messages:

feat: Add user profile page
fix: Resolve login redirect bug
docs: Update API documentation
style: Format code with Prettier
refactor: Simplify product fetch logic
test: Add unit tests for auth

Testing:

  • Test all user flows
  • Check mobile responsiveness
  • Verify authentication works
  • Test with different roles (Admin, Staff)

πŸ“„ License

This project is licensed under the MIT License.

MIT License Summary:

  • βœ… Commercial use allowed
  • βœ… Modification allowed
  • βœ… Distribution allowed
  • βœ… Private use allowed
  • ⚠️ No warranty provided

πŸ™ Acknowledgments

  • Next.js Team - For the amazing React framework
  • Vercel - For hosting and deployment platform
  • MongoDB - For the flexible NoSQL database
  • NextAuth.js - For authentication made simple
  • GSAP - For professional animations
  • Lucide - For beautiful icons
  • TailwindCSS - For utility-first styling

πŸš€ Future Plans

This project is currently a public repository serving as the foundation for a complete SaaS inventory management platform.

Planned Commercial Features

When we transition to SaaS:

  • πŸ’³ Subscription Tiers:

    • Free: 50 products, 1 user
    • Starter: 500 products, 5 users - $29/month
    • Professional: 5000 products, 25 users - $99/month
    • Enterprise: Unlimited - Custom pricing
  • ☁️ Fully Hosted Solution:

    • No setup required
    • Automatic updates
    • 99.9% uptime SLA
    • Global CDN
  • 🏒 Enterprise Add-ons:

    • White-label branding
    • Dedicated support
    • Custom integrations
    • On-premise deployment
  • πŸ”Œ Marketplace Integrations:

    • Shopify, WooCommerce, Magento
    • Amazon, eBay, Etsy
    • QuickBooks, Xero, Stripe
    • Zapier, Make, n8n

Stay tuned for updates!


Β© 2026 Locus. Crafted with precision.

⭐ Star this repo if you find it useful!

Website Β· Twitter Β· LinkedIn

About

Full-stack Inventory Management SaaS with Next.js 16, MongoDB, role-based access, dashboard analytics, stock tracking, and premium dark UI.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published