Hindalco-Internship-Project

Hindalco Tool Tracking System - Complete Documentation

🏢 System Overview

The Hindalco Tool Tracking System is a comprehensive real-time web application designed for managing tools, users, and maintenance requests in an industrial environment. The system provides role-based access control, real-time notifications, and complete audit trails.

🎯 Key Features

Real-Time Functionality

User Management

Tool Management

Request Management

Maintenance Management

Data Management

🏗️ System Architecture

┌─────────────────────────────────────────────────────────┐
│                    Frontend (HTML/JS)                   │
├─────────────────────────────────────────────────────────┤
│  • User Dashboards (Employee/Manager/Admin)            │
│  • Real-time UI Updates (Socket.IO Client)             │
│  • Authentication & Authorization                       │
│  • API Communication                                    │
└─────────────────────────────────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────┐
│                Backend API (Node.js/Express)            │
├─────────────────────────────────────────────────────────┤
│  • RESTful API Endpoints                               │
│  • JWT Authentication                                  │
│  • Real-time Events (Socket.IO Server)                │
│  • Business Logic & Validation                        │
└─────────────────────────────────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────┐
│                 Database (MongoDB)                      │
├─────────────────────────────────────────────────────────┤
│  • Users Collection                                    │
│  • Tools Collection                                    │
│  • Tool Requests Collection                           │
│  • Maintenance Collection                             │
└─────────────────────────────────────────────────────────┘

📁 Project Structure

Internship_Project/
├── backend/                    # Backend API server
│   ├── models/                # Database models
│   │   ├── User.js            # User schema
│   │   ├── Tool.js            # Tool schema
│   │   ├── ToolRequest.js     # Tool request schema
│   │   └── Maintenance.js     # Maintenance schema
│   ├── routes/                # API route handlers
│   │   ├── auth.js            # Authentication routes
│   │   ├── users.js           # User management routes
│   │   ├── tools.js           # Tool management routes
│   │   ├── toolRequests.js    # Request management routes
│   │   ├── maintenance.js     # Maintenance routes
│   │   └── reports.js         # Export/backup routes
│   ├── middleware/            # Express middleware
│   │   └── auth.js            # JWT authentication middleware
│   ├── server.js              # Main server file
│   ├── package.json           # Backend dependencies
│   └── .env                   # Environment variables
├── frontend/                  # Frontend web application
│   ├── index.html             # Login page
│   ├── register.html          # Registration page
│   ├── user_new.html          # Employee dashboard
│   ├── manager_new.html       # Manager dashboard
│   ├── admin.html             # Admin dashboard
│   ├── profile.html           # User profile page
│   ├── api.js                 # API service layer
│   ├── login.js               # Authentication logic
│   ├── auth-utils.js          # Authentication utilities
│   ├── dashboard-utils.js     # Dashboard utilities
│   └── login.css              # Styling
├── start-system.bat           # Windows startup script
├── SETUP_GUIDE.md             # Setup instructions
├── START_SERVERS.md           # Server startup guide
└── SYSTEM_DOCUMENTATION.md    # This file

👥 User Roles & Permissions

Employee Role

Permissions:

Dashboard Features:

Manager Role

Permissions:

Dashboard Features:

Admin Role

Permissions:

Dashboard Features:

🔄 Real-Time Communication Flow

User Requests Tool Workflow

1. Employee submits tool request
   ↓
2. Backend saves request to database
   ↓
3. Socket.IO broadcasts to Manager/Admin rooms
   ↓
4. Managers receive real-time notification + audio alert
   ↓
5. Manager reviews and approves/rejects request
   ↓
6. Backend updates request status
   ↓
7. Socket.IO broadcasts update to all users
   ↓
8. Employee receives real-time status notification

Socket.IO Events

// Client-side events
socket.emit('join-role', userRole);           // Join role-based room
socket.emit('new-request', requestData);      // New request submitted
socket.emit('request-reviewed', reviewData);  // Request reviewed

// Server-side broadcasts
socket.to('Manager').emit('request-created', data);  // New request alert
socket.emit('request-updated', data);                // Status update
socket.emit('tool-assigned', data);                  // Tool assignment
socket.emit('maintenance-scheduled', data);          // Maintenance scheduled

🗄️ Database Schema

Users Collection

{
  _id: ObjectId,
  firstName: String,
  lastName: String,
  email: String (unique),
  password: String (hashed),
  role: String ['Admin', 'Manager', 'Employee'],
  department: String,
  employeeId: String (unique),
  phone: String,
  isActive: Boolean,
  lastLogin: Date,
  profileImage: String,
  createdAt: Date,
  updatedAt: Date
}

Tools Collection

{
  _id: ObjectId,
  name: String,
  description: String,
  category: String ['Hand Tools', 'Power Tools', 'Measuring Tools', 'Safety Equipment', 'Other'],
  brand: String,
  model: String,
  serialNumber: String (unique),
  location: String,
  status: String ['Available', 'In Use', 'Maintenance', 'Damaged', 'Lost'],
  condition: String ['Excellent', 'Good', 'Fair', 'Poor'],
  purchaseDate: Date,
  purchasePrice: Number,
  assignedTo: ObjectId (ref: User),
  assignedDate: Date,
  expectedReturnDate: Date,
  lastMaintenanceDate: Date,
  nextMaintenanceDate: Date,
  imageUrl: String,
  notes: String,
  createdBy: ObjectId (ref: User),
  createdAt: Date,
  updatedAt: Date
}

Tool Requests Collection

{
  _id: ObjectId,
  requestedBy: ObjectId (ref: User),
  tool: ObjectId (ref: Tool),
  requestType: String ['borrow', 'return', 'maintenance', 'replacement'],
  reason: String,
  urgency: String ['low', 'medium', 'high', 'critical'],
  expectedDuration: Number, // days
  status: String ['pending', 'approved', 'rejected', 'cancelled'],
  reviewedBy: ObjectId (ref: User),
  reviewedAt: Date,
  reviewComments: String,
  metadata: Object,
  createdAt: Date,
  updatedAt: Date
}

Maintenance Collection

{
  _id: ObjectId,
  tool: ObjectId (ref: Tool),
  scheduledBy: ObjectId (ref: User),
  assignedTo: ObjectId (ref: User),
  maintenanceType: String ['preventive', 'corrective', 'emergency', 'inspection'],
  priority: String ['low', 'medium', 'high', 'critical'],
  scheduledDate: Date,
  estimatedDuration: Number, // hours
  description: String,
  status: String ['scheduled', 'in-progress', 'completed', 'cancelled', 'overdue'],
  actualStartDate: Date,
  actualEndDate: Date,
  actualDuration: Number,
  completionNotes: String,
  cost: Number,
  partsUsed: [{ partName: String, quantity: Number, cost: Number }],
  nextMaintenanceDate: Date,
  attachments: [{ filename: String, path: String, uploadedAt: Date }],
  createdAt: Date,
  updatedAt: Date
}

🔌 API Endpoints

Authentication Endpoints

User Management Endpoints

Tool Management Endpoints

Tool Request Endpoints

Maintenance Endpoints

Reports & Export Endpoints

🔐 Security Implementation

Authentication & Authorization

Data Protection

Security Headers

// Security middleware implementation
app.use(cors({
  origin: process.env.CORS_ORIGIN,
  credentials: true
}));

// JWT verification middleware
const authMiddleware = (req, res, next) => {
  const token = req.header('Authorization')?.replace('Bearer ', '');
  if (!token) return res.status(401).json({ message: 'Access denied' });
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (error) {
    res.status(401).json({ message: 'Invalid token' });
  }
};

📊 Performance Optimization

Frontend Optimization

Backend Optimization

Real-Time Optimization

🔧 Configuration

Environment Variables

# Server Configuration
PORT=5000
NODE_ENV=development

# Database Configuration
MONGODB_URI=mongodb://localhost:27017/tool-tracking

# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# CORS Configuration
CORS_ORIGIN=http://localhost:3000

MongoDB Configuration

const mongoConfig = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  maxPoolSize: 10,
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
};

🚀 Deployment Guide

Development Environment

  1. Install Node.js and MongoDB
  2. Clone the repository
  3. Install dependencies: npm install
  4. Configure environment variables
  5. Start MongoDB service
  6. Run: npm run dev or use start-system.bat

Production Environment

  1. Set up production MongoDB instance
  2. Configure environment variables for production
  3. Build frontend assets
  4. Set up reverse proxy (nginx)
  5. Configure SSL certificates
  6. Use PM2 for process management
  7. Set up monitoring and logging

Docker Deployment

# Example Dockerfile for backend
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 5000
CMD ["node", "server.js"]

📈 Monitoring & Analytics

System Metrics

Health Checks

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    timestamp: new Date(),
    uptime: process.uptime(),
    mongodb: mongoose.connection.readyState === 1 ? 'connected' : 'disconnected'
  });
});

🛠️ Maintenance & Updates

Regular Maintenance Tasks

Update Procedures

  1. Test updates in development environment
  2. Create database backup
  3. Deploy to staging environment
  4. Run automated tests
  5. Deploy to production with rollback plan
  6. Monitor system health post-deployment

🆘 Troubleshooting

Common Issues

1. MongoDB Connection Issues

# Check MongoDB status
mongod --version
mongo --eval "db.adminCommand('ping')"

# Restart MongoDB service
net start MongoDB

2. Socket.IO Connection Problems

// Debug Socket.IO connections
socket.on('connect_error', (error) => {
  console.error('Socket.IO connection error:', error);
});

3. Authentication Failures

// Check JWT token validity
const decoded = jwt.decode(token);
console.log('Token expiry:', new Date(decoded.exp * 1000));

Debug Mode

// Enable debug logging
localStorage.setItem('debug', 'true');

// Check system status
GET /api/health

📋 Testing

Manual Testing Checklist

Test Scenarios

  1. User Workflow: Employee requests tool → Manager approves → Tool assigned
  2. Real-Time: Multiple users simultaneously, verify instant updates
  3. Permissions: Test role-based access restrictions
  4. Data Integrity: CRUD operations across all entities
  5. Error Handling: Network failures, invalid inputs

📞 Support & Contact

Technical Support

System Administration

🎉 Success Criteria

The system is considered fully operational when:

This comprehensive system provides a robust, scalable, and user-friendly solution for tool tracking and management in industrial environments.