Skip to content

pranavchugh1/erp

Repository files navigation

Saree Manufacturing ERP System

A comprehensive mobile-first Progressive Web Application (PWA) designed for saree manufacturing businesses to manage their complete production workflow - from grey fabric procurement through mill processing, cutting, stitching, accessory management, and financial accounting.

📋 Table of Contents


✨ Features

Core Modules

  1. Authentication & User Management

    • Secure JWT-based authentication
    • Role-based access control (5 user roles)
    • User creation and management (Owner only)
  2. Dashboard (Owner Only)

    • Real-time business overview
    • Today's cutting statistics
    • Pending stitching counts
    • Grey fabric stock levels
    • Credit due tracking
    • Low stock alerts
    • Recent activity feed
  3. Mill Module

    • Grey Incoming: Track raw fabric procurement
    • Mill Incoming: Monitor processing at mills (dyeing, printing)
    • Shrinkage calculations
    • Bill and challan tracking
  4. Cutting Module

    • Fabric cutting reports
    • Auto-calculation of sarees from meters (~5.5m per saree)
    • Design code tracking
    • Lace and blouse consumption
    • Waste tracking
  5. Stitching Module

    • Tailor/unit work assignment
    • Payment tracking per saree
    • Progress monitoring (issued vs completed)
    • Auto-calculated total payments
  6. Accounts Module

    • Sales Entry: Invoice management with cash/bank/credit tracking
    • Expense Entry: Expense categorization and payment mode tracking
    • Payment status tracking
    • Due date reminders for credit sales
  7. Accessories Module

    • Incoming: Lace and blouse inventory tracking
    • Issue: Accessory issuance to production units
    • Stock level monitoring
    • Low stock alerts

🛠️ Tech Stack

Frontend

  • Next.js 14 - React framework with App Router
  • React 18 - UI library
  • TailwindCSS - Utility-first CSS framework
  • shadcn/ui - Accessible component library
  • Lucide React - Icon library
  • Sonner - Toast notifications
  • React Hook Form - Form management
  • Zod - Schema validation

Backend

  • Next.js API Routes - Serverless API endpoints
  • MongoDB - NoSQL database
  • JWT - Authentication tokens
  • bcryptjs - Password hashing

Development Tools

  • Yarn - Package manager
  • ESLint - Code linting
  • TypeScript - (Can be enabled)

📦 Prerequisites

Before you begin, ensure you have the following installed:

  1. Node.js (v18.0 or higher)

    node --version
  2. Yarn (v1.22 or higher)

    yarn --version
  3. MongoDB (v5.0 or higher)

    • Local installation OR
    • MongoDB Atlas account (cloud)
  4. Git (for cloning the repository)


🚀 Installation

Step 1: Clone the Repository

git clone <repository-url>
cd erp

Step 2: Install Dependencies

yarn install

This will install all required dependencies defined in package.json.


⚙️ Environment Setup

Create a .env file in the root directory with the following variables:

# MongoDB Configuration (REQUIRED)
MONGO_URL=mongodb://localhost:27017
# OR for MongoDB Atlas:
# MONGO_URL=mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority

# Database Name (Optional - defaults to 'saree_erp')
DB_NAME=saree_erp

# JWT Secret (REQUIRED for production - use a strong random string)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# CORS Origins (Optional - defaults to '*')
# For production, specify your domain:
# CORS_ORIGINS=https://yourdomain.com,https://www.yourdomain.com
CORS_ORIGINS=*

Generating a Secure JWT Secret

For production, generate a strong JWT secret:

On Linux/Mac:

openssl rand -base64 32

On Windows (PowerShell):

-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 32 | % {[char]$_})

Online Tool:


🏃 Running the Application

Development Mode

Start the development server:

yarn dev

The application will be available at:

The development server includes:

  • Hot module replacement (HMR)
  • Error overlay
  • Automatic code reloading

Production Build

Build the application for production:

yarn build

Start the production server:

yarn start

The production server will run on port 3000 (default).

Alternative Dev Commands

# Development without reload (faster for some systems)
yarn dev:no-reload

# Development with webpack (fallback option)
yarn dev:webpack

🔐 Default Credentials

The system automatically creates a default owner account on first run:

Email: owner@saree.com
Password: owner123

⚠️ IMPORTANT: Change this password immediately in production!

To change the password, you can:

  1. Delete the existing user from MongoDB
  2. Restart the application (a new default user will be created)
  3. Or implement a password change feature

👥 User Roles

The system supports 5 user roles with different access levels:

Role Access Level Accessible Pages
Owner Full Access All pages + Dashboard
Mill Person Department Mill, Accessories
Cutting Master Department Cutting
Stitching Master Department Stitching
Accountant Department Accounts

Users are automatically redirected to their assigned module after login.


🏭 Production Readiness

✅ Current Status: Development Ready / Basic Production Ready

✅ Implemented Features

  • ✅ Complete authentication system with JWT
  • ✅ Role-based access control
  • ✅ All core modules (8 pages)
  • ✅ Database indexing for performance
  • ✅ Input validation and sanitization
  • ✅ Error handling
  • ✅ Responsive mobile-first design
  • ✅ CORS configuration
  • ✅ Connection pooling (MongoDB)
  • ✅ Password hashing (bcrypt)

⚠️ Production Considerations

Before deploying to production, address the following:

🔒 Security

  1. JWT Secret (CRITICAL)

    • ✅ Currently uses environment variable
    • ⚠️ Default secret in code should be removed
    • ✅ Use strong random secret in production
  2. CORS Configuration

    • ⚠️ Currently allows all origins (*)
    • ✅ Should be restricted to specific domains in production
  3. Password Policy

    • ⚠️ No password strength requirements
    • ⚠️ No password change functionality
    • ⚠️ Default credentials should be changed
  4. Rate Limiting

    • ❌ Not implemented
    • ⚠️ Should be added to prevent abuse
  5. Input Validation

    • ✅ Basic validation implemented
    • ⚠️ Consider adding Zod schemas for all endpoints
  6. SQL Injection / NoSQL Injection

    • ✅ MongoDB driver handles most cases
    • ⚠️ Additional sanitization recommended
  7. File Upload

    • ❌ Not implemented (marked as optional in spec)
    • ⚠️ If needed, implement with file size limits and type validation

🚀 Performance

  1. Caching

    • ⚠️ No caching layer implemented
    • ⚠️ Consider Redis for session/query caching
  2. Database Optimization

    • ✅ Indexes are created
    • ⚠️ Consider query optimization for large datasets
    • ⚠️ Implement pagination for large lists
  3. API Response Times

    • ⚠️ No monitoring/logging implemented
    • ⚠️ Consider adding APM (Application Performance Monitoring)

📊 Monitoring & Logging

  1. Error Tracking

    • ❌ No error tracking service (Sentry, etc.)
    • ⚠️ Recommended for production
  2. Logging

    • ⚠️ Basic console logging
    • ⚠️ Should implement structured logging (Winston, Pino)
  3. Database Monitoring

    • ⚠️ No database monitoring
    • ⚠️ Consider MongoDB Atlas monitoring or similar

🔄 Backup & Recovery

  1. Database Backups

    • ❌ Not automated
    • ⚠️ Implement automated daily backups
    • ⚠️ Test restore procedures
  2. Disaster Recovery Plan

    • ❌ Not documented
    • ⚠️ Should be created

✅ Recommended Before Production

  1. Security Checklist

    • Change default JWT secret
    • Restrict CORS to specific domains
    • Change default admin password
    • Implement rate limiting
    • Add password strength requirements
    • Enable HTTPS (SSL/TLS)
    • Implement file upload security (if needed)
  2. Monitoring & Logging

    • Set up error tracking (Sentry)
    • Implement structured logging
    • Set up database monitoring
    • Configure uptime alerts
  3. Performance

    • Load testing (100+ concurrent users)
    • Database query optimization
    • Implement caching layer
    • Add pagination to list endpoints
  4. Backup & Recovery

    • Automated daily database backups
    • Test backup restore procedures
    • Document disaster recovery plan
  5. Testing

    • Unit tests for critical functions
    • Integration tests for API endpoints
    • E2E tests for critical user flows
    • Security testing (penetration testing)

🌐 Deployment

Vercel (Recommended for Next.js)

  1. Install Vercel CLI

    npm i -g vercel
  2. Deploy

    vercel
  3. Set Environment Variables

    • Go to Vercel Dashboard → Project → Settings → Environment Variables
    • Add all variables from .env
  4. Configure MongoDB

    • Use MongoDB Atlas for cloud database
    • Update MONGO_URL with Atlas connection string

Docker Deployment

Create a Dockerfile:

FROM node:18-alpine AS builder
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build

FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

EXPOSE 3000
ENV PORT 3000

CMD ["node", "server.js"]

Build and run:

docker build -t saree-erp .
docker run -p 3000:3000 --env-file .env saree-erp

Traditional Server Deployment

  1. Build the application

    yarn build
  2. Start with PM2 (Process Manager)

    npm install -g pm2
    pm2 start yarn --name "saree-erp" -- start
    pm2 save
    pm2 startup
  3. Configure Nginx (Reverse Proxy)

    server {
        listen 80;
        server_name yourdomain.com;
    
        location / {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }

🔒 Security Considerations

Immediate Actions for Production

  1. Environment Variables

    • Never commit .env to version control
    • Use secure environment variable management in deployment platform
    • Rotate secrets regularly
  2. Database Security

    • Use MongoDB authentication (username/password)
    • Enable network IP whitelisting
    • Use SSL/TLS connections
    • Regular security updates
  3. Application Security

    • Enable HTTPS (SSL certificates)
    • Implement rate limiting
    • Add request size limits
    • Regular dependency updates
  4. Access Control

    • Change default credentials
    • Implement password policies
    • Regular user access audits
    • Implement session timeout

📁 Project Structure

erp/
├── app/                      # Next.js App Router
│   ├── api/                  # API routes
│   │   └── [[...path]]/      # Catch-all API route handler
│   ├── auth/                 # Authentication page
│   ├── users/                # User management (Owner only)
│   ├── mill/                 # Mill module
│   ├── cutting/              # Cutting module
│   ├── stitching/            # Stitching module
│   ├── accounts/             # Accounts module
│   ├── accessories/          # Accessories module
│   ├── page.js               # Dashboard (Owner)
│   ├── layout.js             # Root layout
│   └── globals.css           # Global styles
├── components/               # React components
│   ├── ui/                   # shadcn/ui components
│   ├── AuthContext.js        # Authentication context
│   ├── BottomNav.js          # Bottom navigation
│   └── PageHeader.js         # Page header component
├── lib/                      # Utility libraries
│   ├── store.js              # API client/store
│   ├── constants.js          # Application constants
│   └── utils.js              # Utility functions
├── hooks/                    # Custom React hooks
├── public/                   # Static assets
├── package.json              # Dependencies
├── next.config.js            # Next.js configuration
├── tailwind.config.js        # Tailwind CSS configuration
└── README.md                 # This file

📡 API Documentation

Authentication Endpoints

  • POST /api/auth/login - User login
  • GET /api/auth/verify - Verify JWT token

User Management (Owner Only)

  • GET /api/users - Get all users
  • POST /api/users - Create new user
  • PUT /api/users/:id - Update user role
  • DELETE /api/users/:id - Delete user

Module Endpoints

Each module has standard CRUD endpoints:

  • GET /api/[module] - Get all records
  • POST /api/[module] - Create new record

Available modules:

  • /api/grey-incoming
  • /api/mill-incoming
  • /api/cutting-reports
  • /api/stitching-reports
  • /api/sales-entries
  • /api/expense-entries
  • /api/accessory-incoming
  • /api/accessory-issue

Dashboard & Analytics

  • GET /api/dashboard/stats - Get dashboard statistics (Owner only)
  • GET /api/accessory-stock - Get accessory stock levels

Authentication

All endpoints (except /api/auth/login) require a JWT token in the Authorization header:

Authorization: Bearer <token>

🐛 Troubleshooting

MongoDB Connection Issues

Error: MongoDB connection error

Solutions:

  1. Verify MongoDB is running: mongod --version
  2. Check MONGO_URL in .env
  3. For MongoDB Atlas: Ensure IP is whitelisted
  4. Check firewall/network settings

Port Already in Use

Error: Port 3000 is already in use

Solutions:

# Find process using port 3000
# Windows:
netstat -ano | findstr :3000
# Linux/Mac:
lsof -i :3000

# Kill the process or use different port
# Edit package.json scripts to use different port

Build Errors

Error: Build fails with memory issues

Solutions:

# Increase Node.js memory limit
NODE_OPTIONS='--max-old-space-size=4096' yarn build

Authentication Issues

Error: Invalid or expired token

Solutions:

  1. Clear browser localStorage
  2. Login again
  3. Check JWT_SECRET matches between restarts

📝 License

[Specify your license here]

👨‍💻 Support

For issues, questions, or contributions, please open an issue or contact the development team.


🎯 Quick Start Summary

# 1. Install dependencies
yarn install

# 2. Create .env file
cat > .env << EOF
MONGO_URL=mongodb://localhost:27017
DB_NAME=saree_erp
JWT_SECRET=your-secret-key-here
CORS_ORIGINS=*
EOF

# 3. Start MongoDB (if local)
# MongoDB should be running

# 4. Start development server
yarn dev

# 5. Open browser
# Navigate to http://localhost:3000
# Login with: owner@saree.com / owner123

Built with ❤️ for Saree Manufacturing Businesses

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published