# Stock Management System (SMS)

## Project Overview
A comprehensive web-based Stock Management System developed for StockHub Ltd, Kigali, Rwanda. This system digitizes and automates stock movement tracking, inventory management, and report generation.

## Technology Stack

### Backend
- **Runtime**: Node.js
- **Framework**: Express.js
- **Database**: MongoDB
- **ODM**: Mongoose
- **Authentication**: JWT (JSON Web Tokens)
- **Password Hashing**: bcryptjs

### Frontend
- **Framework**: React.js 18
- **Routing**: React Router DOM v6
- **Styling**: Tailwind CSS
- **HTTP Client**: Axios
- **Build Tool**: React Scripts

## Features

### 1. Authentication System
- User registration and login
- JWT-based authentication
- Protected routes
- Session management

### 2. Product Management
- Add new products with details (code, name, category, quantity, price, supplier, date)
- View all products in a responsive table
- Real-time stock quantity tracking
- Low stock alerts (products with quantity < 10)

### 3. Warehouse Management
- Create warehouses with code, name, and location
- View all warehouses in a card-based layout
- Track warehouse information

### 4. Stock Transaction Management
- Record stock IN and stock OUT transactions
- Link transactions to products and warehouses
- Automatic inventory quantity updates
- Full CRUD operations (Create, Read, Update, Delete)
- Transaction validation (prevent negative stock)

### 5. Reports & Analytics
- **Dashboard**: Overview with key metrics, low stock alerts, recent transactions
- **Available Stock Report**: Current inventory with total values
- **Stock IN Report**: Filtered by daily, weekly, monthly, or custom date range
- **Stock OUT Report**: Filtered by daily, weekly, monthly, or custom date range
- Print-friendly report layouts
- Summary statistics (total quantity, total value, transaction count)

### 6. Responsive Design
- Mobile-friendly interface
- Adaptive layouts for all screen sizes
- Touch-friendly navigation

## Project Structure

```
├── backend-project/
│   ├── config/
│   │   ├── database.js          # Database connection
│   │   └── initDatabase.js      # Database initialization
│   ├── middleware/
│   │   └── auth.js              # JWT authentication middleware
│   ├── routes/
│   │   ├── auth.js              # Authentication routes
│   │   ├── products.js          # Product routes
│   │   ├── warehouses.js        # Warehouse routes
│   │   ├── transactions.js      # Transaction routes
│   │   └── reports.js           # Report routes
│   ├── .env                     # Environment variables
│   ├── package.json             # Backend dependencies
│   └── server.js                # Express server entry point
│
├── frontend-project/
│   ├── public/
│   │   └── index.html           # HTML template
│   ├── src/
│   │   ├── components/
│   │   │   ├── Auth/
│   │   │   │   ├── Login.js
│   │   │   │   └── Register.js
│   │   │   ├── Dashboard/
│   │   │   │   └── Dashboard.js
│   │   │   ├── Layout/
│   │   │   │   └── Layout.js
│   │   │   ├── Products/
│   │   │   │   └── Products.js
│   │   │   ├── Warehouses/
│   │   │   │   └── Warehouses.js
│   │   │   ├── Transactions/
│   │   │   │   └── Transactions.js
│   │   │   └── Reports/
│   │   │       └── Reports.js
│   │   ├── services/
│   │   │   └── api.js           # API service layer
│   │   ├── App.js               # Main app component
│   │   ├── index.js             # React entry point
│   │   └── index.css            # Global styles
│   ├── package.json             # Frontend dependencies
│   ├── tailwind.config.js       # Tailwind configuration
│   └── postcss.config.js        # PostCSS configuration
│
├── ERD_DESIGN.md                # Entity Relationship Diagram documentation
└── README.md                    # This file
```

## Database Schema

### Collections
1. **User**: User authentication
2. **Product**: Product inventory
3. **Warehouse**: Warehouse locations
4. **StockTransaction**: Stock movement records

See `ERD_DESIGN.md` for detailed schema and relationships.

## Installation & Setup

### Prerequisites
- Node.js (v14 or higher)
- MongoDB Server (v4.4 or higher)
- npm or yarn package manager

### Backend Setup

1. Navigate to backend directory:
```bash
cd backend-project
```

2. Install dependencies:
```bash
npm install
```

3. Configure environment variables in `.env`:
```env
PORT=5000
MONGODB_URI=mongodb://localhost:27017/SMS
JWT_SECRET=your_secret_key
```

4. Start MongoDB server and ensure it's running

5. Start the backend server:
```bash
npm start
```

The backend will:
- Connect to MongoDB
- Create the SMS database if it doesn't exist
- Create all required collections automatically
- Start listening on port 5000

### Frontend Setup

1. Navigate to frontend directory:
```bash
cd frontend-project
```

2. Install dependencies:
```bash
npm install
```

3. Start the development server:
```bash
npm start
```

The frontend will open automatically at `http://localhost:3000`

## Usage Guide

### First Time Setup

1. **Register a User Account**
   - Navigate to the registration page
   - Create a username and password
   - Login with your credentials

2. **Add Warehouses**
   - Go to Warehouses page
   - Click "+ Add Warehouse"
   - Fill in warehouse details

3. **Add Products**
   - Go to Products page
   - Click "+ Add Product"
   - Enter product information

4. **Record Transactions**
   - Go to Transactions page
   - Click "+ Add Transaction"
   - Select product, warehouse, date, quantity, and type (IN/OUT)
   - Submit to update inventory

5. **View Reports**
   - Go to Reports page
   - Select report type
   - Apply filters for date ranges
   - Print reports as needed

## API Endpoints

### Authentication
- `POST /api/auth/register` - Register new user
- `POST /api/auth/login` - Login user

### Products
- `GET /api/products` - Get all products
- `GET /api/products/:productCode` - Get single product
- `POST /api/products` - Create product

### Warehouses
- `GET /api/warehouses` - Get all warehouses
- `GET /api/warehouses/:warehouseCode` - Get single warehouse
- `POST /api/warehouses` - Create warehouse

### Transactions
- `GET /api/transactions` - Get all transactions
- `GET /api/transactions/:id` - Get single transaction
- `POST /api/transactions` - Create transaction
- `PUT /api/transactions/:id` - Update transaction
- `DELETE /api/transactions/:id` - Delete transaction

### Reports
- `GET /api/reports/available-stock` - Available stock report
- `GET /api/reports/stock-in` - Stock IN report (with filters)
- `GET /api/reports/stock-out` - Stock OUT report (with filters)
- `GET /api/reports/dashboard` - Dashboard summary

## Security Features

- Password hashing with bcrypt
- JWT token-based authentication
- Protected API routes
- Input validation
- SQL injection prevention (parameterized queries)
- CORS enabled for frontend-backend communication

## Business Logic

### Stock Transaction Rules
1. **Stock IN**: Increases product quantity
2. **Stock OUT**: Decreases product quantity
3. **Validation**: Prevents negative stock levels
4. **Atomicity**: Uses database transactions for data consistency
5. **Cascade Delete**: Removing products/warehouses removes related transactions

## Future Enhancements

- User roles and permissions (Admin, Manager, Staff)
- Product categories management
- Barcode scanning integration
- Email notifications for low stock
- Advanced analytics and charts
- Export reports to PDF/Excel
- Multi-warehouse stock transfer
- Supplier management module
- Purchase order tracking

## Troubleshooting

### Backend Issues
- **Database connection error**: Check MongoDB is running and URI in `.env` is correct
- **Port already in use**: Change PORT in `.env` file
- **Module not found**: Run `npm install` in backend-project

### Frontend Issues
- **Cannot connect to API**: Ensure backend is running on port 5000
- **Module not found**: Run `npm install` in frontend-project
- **Tailwind styles not working**: Restart the development server

## Development Team

Developed as part of the Integrated Assessment Project for StockHub Ltd.

## License

This project is developed for educational purposes.

## Support

For issues or questions, please refer to the project documentation or contact the development team.

---

**Note**: This system successfully addresses StockHub Ltd's challenges by:
- Eliminating manual paper-based processes
- Reducing errors through automated calculations
- Providing real-time stock visibility
- Enabling quick report generation
- Improving operational efficiency
