Skip to content

Repository files navigation

πŸ›’ ShopERP

Enterprise-Grade Retail Point of Sale (POS), Inventory & Financial ERP System

Next.js React TypeScript TailwindCSS MySQL Security License

A high-performance, security-first ERP and Point of Sale (POS) application architected for modern retail businesses, grocery chains, supermarkets, and wholesale distributors. Powered by Next.js 15 App Router, React 19, MySQL, and military-grade AES-256-GCM encrypted database backups.


πŸ“‘ Table of Contents


πŸ›οΈ Technical Architecture

ShopERP is engineered for high-throughput transactional consistency, zero memory leaks, and sub-millisecond route resolution. All write operations (Checkout, Refunds, Customer Due Repayments, Inventory Adjustments) are bound within atomic ACID database transactions.

+-------------------------------------------------------------------------------+
|                            ShopERP Client (Next.js 15)                        |
|  [ POS Terminal ]    [ Inventory Ledger ]    [ Customer CRM ]    [ Analytics ]|
+---------------------------------------+---------------------------------------+
                                        |
                                        v
+-------------------------------------------------------------------------------+
|                       API Route Handlers & Server Guards                      |
|   - Server-Side Page Guards (RBAC)        - Idempotency Deduplication Key     |
|   - HTTP-Only JWT Cookie Rotation         - Input Validation (Zod Schemas)    |
+---------------------------------------+---------------------------------------+
                                        |
                                        v
+-------------------------------------------------------------------------------+
|                      Enterprise Database & Storage Engine                     |
|  +--------------------+   +--------------------+   +-----------------------+  |
|  | MySQL Database     |   | Immutable Audit Log|   | AES-256-GCM Encrypted |  |
|  | 17 Relational Tbls |   | Mutation Trail     |   | Backup Snapshot Vault |  |
|  +--------------------+   +--------------------+   +-----------------------+  |
+-------------------------------------------------------------------------------+

πŸš€ Key Features & Capabilities

⚑ Lightning-Fast Point of Sale (POS)

  • Real-Time Barcode & SKU Scanning: Instant product search with zero debounce latency.
  • Dynamic Cart Management: Line-item discounts, custom VAT/tax calculation, and cash/due split billing.
  • Instant Thermal Invoicing: Print-ready 80mm/58mm thermal receipts and PDF generation.
  • Customer Due Tagging: Seamless checkout debt tagging linked to customer CRM profiles.

πŸ“¦ Live Inventory & Stock Movement Ledger

  • Automated Stock Tracking: Real-time decrement on checkout and increment on product returns/restocks.
  • Restock & Audit Logs: Detailed change-reason tracking (Restock, Damage Adjustment, Customer Return).
  • Low Stock & Expiry Alerts: Visual warning badges and threshold monitoring.

πŸ‘₯ Customer CRM & Due Recovery Ledger

  • Customer Profiles & History: Comprehensive customer purchase timelines and debt records.
  • 1-Click Due Repayment: Instant payment logging with automatic customer balance updates.
  • Customer Segmentation: Categorize customers into Regular, VIP, or Wholesale tiers.

πŸ“Š Business Analytics & Executive Reports

  • Real-Time Profitability: Gross profit, net margins, sales momentum, and expense distribution.
  • Export Engine: Export detailed financial summaries to Excel (.xlsx), PDF, or raw CSV.
  • Trend Grouping: Granular aggregation by Day, Week, Month, or Custom Date Ranges.

πŸ›‘οΈ Role-Based Access Control (RBAC Matrix)

  • Granular Permission Controls: Independent View, Add, Edit, and Delete permissions per module.
  • Server-Side Route Security: Instant redirect for unauthorized page views.
  • API Guarding: Every backend endpoint verifies module permissions via assertPermission.

πŸ”’ Military-Grade Encrypted Backup & Restore

  • 1-Click Full Export: Full database snapshots encrypted with AES-256-GCM and SHA-256 Checksums.
  • Automated Safety Snapshot: Automatic pre-restore snapshot captured before any rollback.
  • 1-Click Rollback: Instant server snapshot restoration with ACID database transaction safety.

πŸ’» Technology Stack

Layer Technology Description
Frontend Framework Next.js 15 App Router, Server Components & React 19
Language TypeScript 5 Strict Type Safety & Compile-time validation
Styling TailwindCSS 3 Custom Enterprise Design System
State Management TanStack React Query + Zustand Server Cache Invalidation & Client State
Database MySQL 8.0+ / MariaDB Relational Database with Foreign Key Constraints
Database Driver mysql2 High-performance pooled connection driver
Authentication Jose JWT Access & Refresh Token Rotation
Encryption Node.js Crypto (aes-256-gcm) Cryptographic Key Derivation via scrypt
Validation Zod 3 Schema Validation on all API boundaries
Icons Lucide React Modern Feather-style SVG Icon Set

πŸ“‚ Directory Architecture

shoperp/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ (auth)/
β”‚   β”‚   └── login/                 # Authentication & Session Login Page
β”‚   β”œβ”€β”€ (dashboard)/
β”‚   β”‚   β”œβ”€β”€ dashboard/             # Executive Overview Dashboard
β”‚   β”‚   β”œβ”€β”€ pos/                   # Point of Sale Terminal
β”‚   β”‚   β”œβ”€β”€ products/              # Product Catalog Management
β”‚   β”‚   β”œβ”€β”€ stock/                 # Inventory & Stock Movement Ledger
β”‚   β”‚   β”œβ”€β”€ customers/             # Customer CRM & Due Debt Ledger
β”‚   β”‚   β”œβ”€β”€ sales/                 # Invoices & Transaction History
β”‚   β”‚   β”œβ”€β”€ expenses/              # Expense Tracker & Ledger
β”‚   β”‚   β”œβ”€β”€ reports/               # Financial Reports & Data Exports
β”‚   β”‚   β”œβ”€β”€ analytics/             # Business Performance Intelligence
β”‚   β”‚   β”œβ”€β”€ backup/                # AES-256-GCM Encrypted Backup & Restore
β”‚   β”‚   β”œβ”€β”€ audit/                 # Security Mutation Audit Trail
β”‚   β”‚   β”œβ”€β”€ permissions/           # Role-Based Permission Matrix (RBAC)
β”‚   β”‚   β”œβ”€β”€ users/                 # Staff User Accounts
β”‚   β”‚   β”œβ”€β”€ staff-summary/         # Staff Performance Summary
β”‚   β”‚   └── settings/              # Shop Branding & Currency Settings
β”‚   └── api/                       # Secured REST API Endpoints
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ common/                    # AppVersion, Badges, Brand Components
β”‚   β”œβ”€β”€ layout/                    # Sidebar, Topbar, DashboardShell
β”‚   └── ui/                        # Button, Card, Modal, StatCard, Badge
β”œβ”€β”€ database/
β”‚   β”œβ”€β”€ migrations/                # MySQL Schema Definitions (001_init.sql)
β”‚   └── seed.sql                   # Database Seeder Scripts
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ server/                    # DB Pool, Auth, Permissions, Backup Engine
β”‚   β”œβ”€β”€ utils.ts                   # Formatting & Utility Functions
β”‚   └── version.ts                 # Centralized Version Configuration
β”œβ”€β”€ storage/
β”‚   └── backups/                   # Encrypted .shoperp Snapshot Storage
└── package.json                   # Project Manifest & Scripts

🏁 Getting Started

Prerequisites

  • Node.js: v20.x or v22.x (LTS recommended)
  • MySQL: v8.0+ or MariaDB v10.5+
  • Package Manager: npm, pnpm, or yarn

Environment Setup

Clone the repository and copy the environment template:

git clone https://github.com/khan-masud/ShopERP.git
cd ShopERP
cp .env.example .env.local

Configure your .env.local with your MySQL credentials and JWT secrets:

NODE_ENV=development
APP_URL=http://localhost:3000

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=shoperp

# Connection Pool Settings
DB_POOL_LIMIT=10
DB_CONNECT_TIMEOUT_MS=10000

# JWT Security Secrets (Use min 32 characters in production)
JWT_ACCESS_SECRET=your-secure-access-token-secret-key-32-chars
JWT_REFRESH_SECRET=your-secure-refresh-token-secret-key-32-chars
ACCESS_TOKEN_TTL=30m
REFRESH_TOKEN_TTL=7d

Database Migration & Seed

Run the database setup script to create all 17 tables and seed the default admin account:

# 1. Install dependencies
npm install

# 2. Apply MySQL Schema
npm run db:apply

# 3. Seed Default Administrator & Initial Roles
npm run db:seed

# 4. (Optional) Seed 30 Realistic Demo Products across all categories
npm run db:demo-products

Development Server

Start the local Next.js development server:

npm run dev

Visit http://localhost:3000 in your browser.

  • Default Admin Email: admin@shop.com
  • Default Admin Password: Admin123456!

πŸ›‘οΈ Security Architecture

ShopERP is designed adhering to zero-trust principles:

  • HTTP-Only Cookies: JWT tokens are stored exclusively in secure, httpOnly, SameSite=Strict cookies.
  • Refresh Token Rotation: Each refresh token is hashed via SHA-256 and stored in the database. Token reuse triggers instant revocation of all active sessions.
  • Brute-Force Protection: IP-based and account-based rate limiting with automatic cooldown periods.
  • Idempotency Protection: Financial mutations accept an idempotency-key to prevent accidental double charges.
  • Immutable Audit Logging: Every CREATE, UPDATE, and DELETE operation records the actor ID, IP address, timestamp, and mutation diff.

πŸ” Backup & Disaster Recovery

ShopERP includes a built-in cryptographic disaster recovery vault:

  • Algorithm: AES-256-GCM with scrypt key derivation.
  • Tamper Verification: SHA-256 hash payload verification before decompression.
  • Safety Barrier: Automatic pre-restore snapshot (shoperp_backup_...shoperp) created before any table modification.
  • Restore Guard: Irreversible rollback confirmation modal requiring explicit typed verification.

πŸ”Œ API Endpoints Overview

Method Endpoint Description Permission
POST /api/auth/login Authenticate user & issue JWT cookies Public
POST /api/auth/logout Revoke session tokens & clear cookies Authenticated
GET /api/pos/products Retrieve active products with live inventory sales:view
POST /api/sales/checkout Process order, decrement stock & issue receipt sales:add
POST /api/sales/[id]/refund Process return and increment inventory sales:edit
POST /api/customers/due-payment Log debt collection & update balance customers:edit
GET /api/reports/overview Generate executive financial summary reports:view
GET /api/backup/export Download AES-256 encrypted database backup backup:add
POST /api/backup/restore Restore database from archive or snapshot backup:edit
PUT /api/permissions Update staff role permission matrix Admin Only

πŸ“„ License & Author

Developed with ❀️ by Abdullah Al Masud.

This project is licensed under the MIT License - see the LICENSE file for details.

Releases

Packages

Contributors

Languages