Skip to content

johnlester-0369/SimpleStock

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

99 Commits
 
 
 
 
 
 

Repository files navigation

SimpleStock

SimpleStock

A full-stack inventory management system — with a live demo that needs no backend.

TypeScript React Express MongoDB Vite Tailwind CSS License

OverviewLive DemoQuick StartArchitectureCommandsPackages


📖 Overview

SimpleStock is a production-ready inventory management system built as a monorepo with two independent packages. Track stock levels, record product sales, manage suppliers, and analyze sales trends — all through a responsive dashboard. No backend required to evaluate: the demo mode runs entirely in the browser using localStorage.

Package Description Stack
web React SPA frontend React 19, Vite 7, Tailwind CSS, Chart.js
server Express REST API backend Express 4, MongoDB, Mongoose 9, Winston

Key Features

  • 📦 Product Management — Full CRUD with real-time stock tracking and low-stock alerts
  • 💰 Sales Transactions — Record sales with automatic inventory decrement
  • 👥 Supplier Directory — Manage vendor contacts and filter products by supplier
  • 📊 Analytics Dashboard — Sales charts, daily breakdowns, and summary statistics
  • 🔐 Authentication — Session-based auth with better-auth and role-based access control
  • 🎮 Demo Mode — Fully functional without a backend, data persisted in localStorage

🎮 Live Demo

No setup required. Visit the demo and explore every feature with pre-seeded data:

Field Value
Email demo@simplestock.com
Password demo123456

All data in the live demo is stored in your browser — nothing is sent to a server. Data persists across sessions.

What you can do in demo mode

  • ✅ Add, edit, delete, and sell products
  • ✅ Manage the supplier directory
  • ✅ Browse transaction history with period filters
  • ✅ View the dashboard with charts and analytics
  • ✅ Experience the responsive mobile layout

🚀 Quick Start

Option 1: Live Demo (No Setup)

Visit https://simplestock-demo.onrender.com and log in with the demo credentials above.

Option 2: Full Stack (Recommended for Development)

# Navigate to the project root
cd SimpleStock

# Install dependencies for all packages
make install

# Copy the server environment template and add your MongoDB credentials
cp packages/server/.env.example packages/server/.env

# Seed an initial admin user (optional)
make seed-admin

# Start both the web frontend and API server concurrently
make dev
Service URL
🌐 Web UI http://localhost:5173
🔌 API Server http://localhost:3000
❤️ Health Check http://localhost:3000/health

Option 3: Demo Mode Locally (No Backend)

cd SimpleStock/packages/web
npm install
npm run dev:demo

Demo credentials: demo@simplestock.com / demo123456

Option 4: Manual Setup (Separate Terminals)

# Terminal 1 — API server
cd SimpleStock/packages/server
npm install
cp .env.example .env
# Configure .env with your MongoDB credentials
npm run dev

# Terminal 2 — web frontend
cd SimpleStock/packages/web
npm install
npm run dev

🏗️ Architecture

System Overview

┌────────────────────────────────────────────────────────────────────────┐
│                              CLIENTS                                   │
│                    (Browser / Mobile / API Consumer)                   │
└─────────────────────────────────┬──────────────────────────────────────┘
                                  │
                                  ▼
┌────────────────────────────────────────────────────────────────────────┐
│                           WEB PACKAGE                                  │
│                        (React 19 + Vite 7)                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐    │
│  │   Pages     │  │  Components │  │   Hooks     │  │  Services   │    │
│  │  Dashboard  │  │     UI      │  │ useProducts │  │  API/Local  │    │
│  │  Products   │  │   Layout    │  │ useSupplier │  │   Client    │    │
│  │  Reports    │  │   Common    │  │ useTrans... │  │             │    │
│  └─────────────┘  └─────────────┘  └─────────────┘  └──────┬──────┘    │
│                                                            │           │
│  Vite Dev Proxy: /api/* ──────────────────────────────────►│           │
└────────────────────────────────────────────────────────────┼───────────┘
                                                             │
                                  ┌──────────────────────────┘
                                  │
                                  ▼
┌────────────────────────────────────────────────────────────────────────┐
│                          SERVER PACKAGE                                │
│                       (Express 4 + MongoDB)                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐    │
│  │   Routes    │  │ Controllers │  │  Services   │  │   Repos     │    │
│  │  /products  │──│  Product    │──│  Product    │──│  Product    │    │
│  │  /suppliers │  │  Supplier   │  │  Supplier   │  │  Supplier   │    │
│  │  /transact  │  │ Transaction │  │ Transaction │  │ Transaction │    │
│  └─────────────┘  └─────────────┘  └─────────────┘  └──────┬──────┘    │
│                                                            │           │
│                                 ┌──────────────────────────┘           │
│                                 │                                      │
│                                 ▼                                      │
│  ┌─────────────────────────────────────────────────────────────────┐   │
│  │                         DATABASE LAYER                          │   │
│  │  ┌──────────────────┐              ┌──────────────────────┐     │   │
│  │  │   MongoClient    │              │      Mongoose        │     │   │
│  │  │  (better-auth)   │              │   (ODM Operations)   │     │   │
│  │  │                  │              │                      │     │   │
│  │  │  • user          │              │  • Product Model     │     │   │
│  │  │  • session       │              │  • Supplier Model    │     │   │
│  │  │  • verification  │              │  • Transaction Model │     │   │
│  │  └────────┬─────────┘              └──────────┬───────────┘     │   │
│  │           │                                   │                 │   │
│  │           └───────────────┬───────────────────┘                 │   │
│  │                           ▼                                     │   │
│  │                  ┌─────────────────┐                            │   │
│  │                  │    MongoDB      │                            │   │
│  │                  │  (Atlas/Local)  │                            │   │
│  │                  └─────────────────┘                            │   │
│  └─────────────────────────────────────────────────────────────────┘   │
└────────────────────────────────────────────────────────────────────────┘

API Endpoints

Category Base Path Description
Auth /api/v1/admin/auth/* Authentication (better-auth)
Products /api/v1/admin/products Product CRUD + sell
Suppliers /api/v1/admin/suppliers Supplier CRUD
Transactions /api/v1/admin/transactions Transaction queries

Request Flow

┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│  React Hook  │────►│   Service    │────►│  API Client  │
│ useProducts  │     │productService│     │  fetch/axios │
└──────────────┘     └──────────────┘     └───────┬──────┘
                                                  │
       ┌──────────────────────────────────────────┘
       │ HTTP Request
       ▼
┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│    Route     │────►│  Controller  │────►│   Service    │
│   Handler    │     │ parseRequest │     │ businessLogic│
└──────────────┘     └──────────────┘     └──────┬───────┘
                                                 │
                                                 ▼
                     ┌──────────────┐     ┌──────────────┐
                     │   MongoDB    │◄────│   Repository │
                     │   Database   │     │   dataAccess │
                     └──────────────┘     └──────────────┘

Authentication Flow

┌─────────┐    ┌─────────────┐    ┌──────────────┐     ┌──────────┐
│  Login  │───►│ AuthContext │───►│ AuthClient   │────►│ better-  │
│  Page   │    │  Provider   │    │ (API/Local)  │     │  auth    │
└─────────┘    └──────┬──────┘    └──────────────┘     └────┬─────┘
                      │                                     │
                      ▼                                     ▼
               ┌─────────────┐                        ┌─────────────┐
               │   Route     │                        │   MongoDB   │
               │   Guards    │                        │  Sessions   │
               │ Protected/  │                        │             │
               │   Public    │                        └─────────────┘
               └─────────────┘

📋 Make Commands

All commands run from the SimpleStock/ project root.

Installation

Command Description
make install Install dependencies for all packages
make install-web Install web package dependencies only
make install-server Install server package dependencies only

Development

Command Description
make dev Start both web and server concurrently
make dev-web Start web frontend only (port 5173)
make dev-server Start server backend only (port 3000)
make dev-demo Start web in demo mode (localStorage)

Build & Production

Command Description
make build Build both packages for production
make build-web Build web package
make build-server Build server package
make build-demo Build web in demo mode
make start Start server in production mode
make preview Preview web production build
make preview-demo Preview demo production build

Code Quality

Command Description
make lint Run ESLint on all packages
make lint-web Lint web package
make lint-server Lint server package
make format Format server code with Prettier

Testing

Command Description
make test Run web tests once
make test-watch Run web tests in watch mode
make test-coverage Run web tests with coverage report

Database & Utilities

Command Description
make seed-admin Create initial admin user
make clean Remove all build artifacts and node_modules
make clean-web Clean web package only
make clean-server Clean server package only
make check Verify required tools are installed
make status Show project installation status

Quick Reference

# Full development setup
make install && make dev

# Demo mode — no backend needed
make install-web && make dev-demo

# Production build
make build && make start

# Run tests with coverage
make test-coverage

📦 Packages

Web Package (packages/web/)

React SPA with a comprehensive UI component library, dual data source support, and interactive charts.

Stack: React 19.2 · TypeScript 5.9 · Vite 7.2 · Tailwind CSS 3.4 · Chart.js · React Router 7 · Zod · Vitest

  • 🎨 Custom UI component library (Button, Card, Dialog, Table, Pagination, and more)
  • 📊 Interactive dashboard with weekly and monthly sales charts
  • 🔄 Automatic API/localStorage switching via VITE_DATA_SOURCE
  • 📱 Responsive mobile-first design
  • ✅ Component tests with Vitest + Testing Library

📖 Full Documentation →


Server Package (packages/server/)

RESTful API backend with layered architecture, dual MongoDB connection strategy, and session-based authentication.

Stack: Express 4.21 · TypeScript 5.9 · MongoDB 7.0 · Mongoose 9.0 · better-auth · Winston · Zod

  • 🔐 Session-based authentication with admin role support via better-auth
  • 🗄️ Dual MongoDB connection (MongoClient for auth, Mongoose for business data)
  • ✅ Zod validation with typed domain error propagation
  • 📝 Winston structured logging with environment-specific formatters
  • ⚡ Graceful shutdown with connection pool cleanup

📖 Full Documentation →


🔧 Configuration

Environment Files

File Package Purpose
packages/server/.env Server Database, auth, logging config
packages/web/.env.development Web Development settings (VITE_DATA_SOURCE=api)
packages/web/.env.production Web Production settings
packages/web/.env.demo Web Demo mode settings (VITE_DATA_SOURCE=local)

Server Configuration

# packages/server/.env
NODE_ENV=development
PORT=3000

# Database
MONGODB_URI=mongodb+srv://user:<PASSWORD>@cluster.mongodb.net
MONGO_PASSWORD=your-password
DATABASE_NAME=simplestock

# Authentication
BASE_URL=http://localhost:3000
AUTH_SECRET_USER=your-32-char-secret-key
TRUSTED_ORIGINS=http://localhost:3000,http://localhost:5173

# Logging
LOG_LEVEL=info

Web Configuration

# API mode — connects to backend at localhost:3000
VITE_DATA_SOURCE=api

# Demo mode — uses localStorage, no backend required
VITE_DATA_SOURCE=local

Vite Dev Proxy

The Vite dev server forwards all /api requests to the backend automatically:

// vite.config.ts
server: {
  proxy: {
    '/api': {
      target: 'http://localhost:3000',
      changeOrigin: true,
    },
  },
}

📊 Technology Stack

Frontend (Web)

Category Technology Version
Framework React 19.2
Language TypeScript ~5.9.3
Build Tool Vite 7.2
Styling Tailwind CSS 3.4
Routing React Router 7.10
Charts Chart.js 4.5
Auth Client better-auth 1.4
Validation Zod 4.1
Icons Lucide React 0.555
Testing Vitest 4.0

Backend (Server)

Category Technology Version
Framework Express 4.21
Language TypeScript ~5.9.3
Database MongoDB 7.0
ODM Mongoose 9.0
Auth better-auth 1.4
Validation Zod 4.3
Logging Winston 3.19
Dev Runner tsx 4.21

🔐 Security

Authentication

  • Session-based with HTTP-only cookies and role-based access (user/admin)
  • Rate limiting on auth endpoints — 3 sign-in attempts per 10 seconds, 5 sign-ups per minute
  • Configurable session expiry with daily refresh

Data Protection

  • All inputs validated with Zod schemas on both client and server
  • Parameterized database queries via Mongoose — no raw query construction
  • Environment variables for all secrets — no hardcoded credentials
  • Password hashing via bcrypt

API Security

  • CORS restricted to configured trusted origins
  • HTTP request logging for audit trails
  • Generic error messages to clients — no internal stack trace exposure
  • Authentication middleware on all protected routes with userId-scoped queries

🧪 Testing

Web Tests

make test           # Run all tests once
make test-watch     # Watch mode during development
make test-coverage  # Generate coverage report

Manual API Testing

# Health check
curl http://localhost:3000/health

# Login and save session cookie
curl -X POST http://localhost:3000/api/v1/admin/auth/sign-in/email \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@example.com","password":"password"}' \
  -c cookies.txt

# Get products (authenticated)
curl http://localhost:3000/api/v1/admin/products -b cookies.txt

🚨 Troubleshooting

Issue Solution
MongoDB connection failed Check MONGODB_URI and MONGO_PASSWORD in .env; verify Atlas IP allowlist
Port 3000 already in use Kill existing process or change PORT in .env
Auth not working Verify AUTH_SECRET_USER is 32+ characters
CORS errors Add frontend URL to TRUSTED_ORIGINS in server .env
Demo mode not loading Ensure VITE_DATA_SOURCE=local in packages/web/.env.demo
make status                  # Show installation status for all packages
make check                   # Verify required tools are installed
make clean && make install   # Reset and reinstall everything

📁 Project Structure

SimpleStock/
├── Makefile                    # Orchestration commands for all packages
├── README.md                   # This file
└── packages/
    ├── server/                 # Backend API
    │   ├── src/
    │   │   ├── config/         # Environment configuration
    │   │   ├── controllers/    # HTTP request handlers
    │   │   ├── dtos/           # Data transfer objects & mappers
    │   │   ├── lib/            # Core libraries (auth, db, logger)
    │   │   ├── middleware/     # Express middleware
    │   │   ├── models/         # Mongoose schemas
    │   │   ├── repos/          # Data access layer
    │   │   ├── routes/         # API route definitions
    │   │   ├── services/       # Business logic
    │   │   ├── shared/         # Shared utilities (domain errors)
    │   │   ├── types/          # TypeScript declarations
    │   │   ├── validators/     # Zod schemas
    │   │   ├── app.ts          # Express app factory
    │   │   └── server.ts       # Entry point
    │   ├── scripts/            # Utility scripts (seed-admin)
    │   ├── .env.example        # Environment template
    │   ├── package.json
    │   ├── tsconfig.json
    │   └── README.md
    └── web/                    # Frontend SPA
        ├── public/             # Static assets
        ├── src/
        │   ├── assets/         # App assets (logo)
        │   ├── components/
        │   │   ├── common/     # Brand, PageHead
        │   │   ├── layout/     # DashboardLayout, Navbar, Sidebar
        │   │   └── ui/         # UI component library
        │   ├── constants/      # App constants and route definitions
        │   ├── contexts/       # UserAuthContext
        │   ├── guards/         # PublicRoute, UserProtectedRoute
        │   ├── hooks/          # Custom data hooks
        │   ├── lib/
        │   │   └── local-storage/  # Demo mode storage layer
        │   ├── pages/          # Page components
        │   ├── routes/         # Router configuration
        │   ├── services/       # API service layer
        │   ├── styles/         # Global CSS and theme variables
        │   ├── utils/          # Utility functions
        │   ├── validators/     # Zod schemas
        │   ├── App.tsx         # Root component with providers
        │   └── main.tsx        # Entry point
        ├── .env.development
        ├── .env.demo
        ├── .env.production
        ├── package.json
        ├── vite.config.ts
        ├── vitest.config.ts
        └── README.md

📄 License

This project is private and proprietary. All rights reserved.


Built with ❤️ using React, Express, TypeScript, and MongoDB

Web PackageServer PackageBack to Top

Releases

No releases published

Packages

 
 
 

Contributors