# Stock Management System (SMS) - Implementation Guide

## Project Overview
This is a Stock Management System web application for StockHub Ltd, built with Node.js, React.js, and MongoDB.

## Project Structure

```
Product/
├── backend-project/          # Node.js Express backend
│   ├── config/
│   │   └── db.js            # MongoDB connection (SMS database)
│   ├── models/
│   │   ├── User.js
│   │   ├── product.js       # Product entity
│   │   ├── Warehouse.js     # Warehouse entity (NEW)
│   │   ├── StockTransaction.js  # Stock transactions (NEW)
│   │   ├── sales.js         # Migrated to StockTransaction
│   │   └── Supplier.js
│   ├── controllers/
│   │   ├── authController.js
│   │   ├── productController.js  # Updated for new schema
│   │   ├── salesController.js    # Updated for stock transactions
│   │   ├── warehouseController.js # NEW
│   │   └── reportController.js   # NEW - Daily/Weekly/Monthly reports
│   ├── routes/
│   │   ├── authRoutes.js
│   │   ├── productRoutes.js
│   │   ├── salesRoutes.js   # Stock transactions
│   │   ├── warehouseRoutes.js # NEW
│   │   ├── reportRoutes.js   # NEW
│   │   └── SupplierRoutes.js
│   ├── middleware/
│   │   └── auth.js
│   ├── package.json
│   └── server.js
│
└── frontend-project/        # React.js frontend
    ├── src/
    │   ├── pages/
    │   │   ├── Login.jsx
    │   │   ├── Register.jsx
    │   │   ├── Profile.jsx
    │   │   ├── Product.jsx      # Updated - Insert only
    │   │   ├── Warehouse.jsx    # NEW
    │   │   ├── Sales.jsx        # Updated - Stock transactions (CRUD)
    │   │   └── Reports.jsx      # NEW - Daily/Weekly/Monthly
    │   ├── components/
    │   │   └── Dashboard.jsx    # Updated navigation
    │   ├── App.jsx              # Updated routing
    │   ├── main.jsx
    │   ├── index.css
    │   └── App.css
    ├── package.json
    ├── vite.config.js
    └── index.html
```

## Database Schema (MongoDB - SMS database)

### Product Collection
```javascript
{
  productCode: String (unique),
  productName: String,
  category: String,
  quantityInStock: Number,
  unitPrice: Number,
  supplierName: String,
  dateReceived: Date,
  timestamps: {createdAt, updatedAt}
}
```

### Warehouse Collection
```javascript
{
  warehouseCode: String,
  warehouseName: String,
  warehouseLocation: String,
  timestamps: {createdAt, updatedAt}
}
```

### StockTransaction Collection
```javascript
{
  transactionDate: Date,
  quantityMoved: Number,
  transactionType: Enum ['Stock In', 'Stock Out'],
  product: ObjectId (ref: Product),
  warehouse: ObjectId (ref: Warehouse),
  timestamps: {createdAt, updatedAt}
}
```

### User Collection
```javascript
{
  name: String,
  email: String (unique, lowercase),
  password: String (hashed),
  timestamps: {createdAt, updatedAt}
}
```

## API Endpoints

### Authentication
- `POST /api/auth/register` - Register new user
- `POST /api/auth/login` - Login user
- `GET /api/auth/me` - Get current user (protected)

### Products
- `POST /api/product/addproduct` - Add product (INSERT only)
- `GET /api/product/getproduct` - Retrieve all products
- `GET /api/product/getproductbyid/:id` - Retrieve product by ID
- `PUT /api/product/updateproduct/:id` - Update product
- `DELETE /api/product/deleteproduct/:id` - Delete product

### Warehouses
- `POST /api/warehouse/addwarehouse` - Add warehouse (INSERT)
- `GET /api/warehouse/getwarehouse` - Get all warehouses
- `GET /api/warehouse/getwarehousebyid/:id` - Get warehouse by ID
- `PUT /api/warehouse/updatewarehouse/:id` - Update warehouse
- `DELETE /api/warehouse/deletewarehouse/:id` - Delete warehouse

### Stock Transactions
- `POST /api/sales/addsales` - Add stock transaction (INSERT)
- `GET /api/sales/getsales` - Get all transactions
- `GET /api/sales/getsalesbyid/:id` - Get transaction by ID
- `PUT /api/sales/updatesales/:id` - Update transaction (UPDATE)
- `DELETE /api/sales/deletesales/:id` - Delete transaction (DELETE)

### Reports
- `GET /api/reports/summary` - Get daily/weekly/monthly stock reports

## Frontend Pages & Navigation

### Dashboard
- Overview page with sidebar navigation
- User profile display and logout option
- Navigation menu:
  - Product (Insert and view)
  - Warehouse (Insert and view)
  - Transactions (Full CRUD)
  - Reports (Daily/Weekly/Monthly summaries)
  - Profile (View user info)

### Key Features

#### Product Page
- Form to add new products (Insert only)
- Display list of all products with their details
- Shows product code, name, category, unit price, quantity, supplier, date received

#### Warehouse Page
- Form to add new warehouses
- Display list of warehouses with code, name, and location

#### Transactions Page
- Full CRUD operations for stock movements
- Select product from dropdown (linked to products)
- Select warehouse from dropdown (linked to warehouses)
- Transaction types: Stock In / Stock Out
- Quantity moved tracked automatically
- Product stock levels updated on transaction

#### Reports Page
- Daily report: Stock In, Stock Out, Transaction count
- Weekly report: Aggregated metrics
- Monthly report: Long-term summary
- Available stock inventory display with supplier and date received info

## Setup & Installation

### Backend Setup
```bash
cd backend-project
npm install
npm run dev      # Start with nodemon
# or
npm start        # Production start
```

**Environment**: MongoDB must be running on `mongodb://localhost:27017/SMS`

### Frontend Setup
```bash
cd frontend-project
npm install
npm run dev      # Start Vite dev server
npm run build    # Production build
```

## Technologies Used

### Backend
- Node.js (Runtime)
- Express.js (Framework)
- MongoDB (Database)
- Mongoose (ODM)
- JWT (Authentication)
- bcrypt (Password hashing)
- CORS (Cross-origin support)

### Frontend
- React 19
- Vite (Build tool)
- React Router v7 (Navigation)
- Axios (HTTP client)
- Tailwind CSS 4 (UI styling)
- Tailwind CSS Vite plugin

## Authentication
- JWT-based authentication
- Tokens stored in localStorage
- Protected routes with auth middleware
- 7-day token expiration

## User Operations Mapping (Assignment Requirements)

✅ **Product**: INSERT only (No edit/delete on frontend)
✅ **Warehouse**: INSERT only (Can manage via API)
✅ **Transactions/Stock**: Full CRUD (Create, Read, Update, Delete)
✅ **Reports**: Read-only (Daily, Weekly, Monthly summaries)
✅ **User Account**: Username/Email + Password authentication

## Running the Application

1. **Start MongoDB**:
   ```bash
   mongod
   ```

2. **Start Backend** (Terminal 1):
   ```bash
   cd backend-project
   npm run dev
   ```

3. **Start Frontend** (Terminal 2):
   ```bash
   cd frontend-project
   npm run dev
   ```

4. **Access Application**:
   - Frontend: `http://localhost:5173` (or port shown by Vite)
   - Backend API: `http://localhost:5001`

5. **Login Flow**:
   - Register a new account with email and password
   - Login with credentials
   - Access dashboard and manage stock

## Notes

- All API endpoints (except auth) require JWT authentication via Bearer token
- Product stock quantities update automatically with transactions
- Reports are calculated dynamically from transaction data
- Database name is "SMS" in MongoDB
- All timestamps include createdAt and updatedAt fields
- Same code style and patterns used throughout for consistency
