# Complete Setup Guide - Nutshell Manufacturing Aggregator MVP ## Table of Contents 1. [Prerequisites](#prerequisites) 2. [Installation](#installation) 3. [Configuration](#configuration) 4. [Running the Application](#running-the-application) 5. [Database Management](#database-management) 6. [API Testing](#api-testing) 7. [Troubleshooting](#troubleshooting) 8. [Development Workflow](#development-workflow) --- ## Prerequisites ### Required Software - **Node.js**: v18 or higher - Download: https://nodejs.org/ - Verify: `node --version` && `npm --version` - **Docker & Docker Compose**: Latest version - Download: https://www.docker.com/products/docker-desktop - Verify: `docker --version` && `docker-compose --version` - **Git** (Optional but recommended) - Download: https://git-scm.com/ ### System Requirements - **RAM**: 4GB minimum (8GB recommended) - **Disk Space**: 2GB free - **OS**: Windows 10/11, macOS, or Linux --- ## Installation ### 1. Clone or Navigate to Project ```bash # If you haven't already cd D:\Nutshell\Site\ Aggreagator ``` ### 2. Install Backend Dependencies ```bash cd backend npm install cd .. ``` **What this does**: - Installs all Node.js packages listed in `backend/package.json` - Creates `backend/node_modules/` directory - Generates `backend/package-lock.json` for reproducible builds **Expected output**: ``` added 456 packages, and audited 457 packages in 2m ``` **If PowerShell fails with execution policy error**: ```bash cmd /c "cd backend && npm install" ``` ### 3. Install Frontend Dependencies ```bash cd frontend npm install cd .. ``` **Expected output**: Similar to backend ### 4. Install Python Dependencies (Optional, for Phase 2) ```bash pip install -r processing/requirements.txt ``` **Or with conda**: ```bash conda create -n nutshell-processing python=3.10 conda activate nutshell-processing pip install -r processing/requirements.txt ``` --- ## Configuration ### Backend Environment **File**: `backend/.env` Create or edit this file with your configuration: ```env # Server Configuration NODE_ENV=development # development | production PORT=3001 # API port # Database Configuration DATABASE_HOST=localhost # PostgreSQL host DATABASE_PORT=5432 # PostgreSQL port DATABASE_USER=nutshell # Database user DATABASE_PASSWORD=nutshell_dev_password # Database password DATABASE_NAME=nutshell_db # Database name # JWT Configuration JWT_SECRET=your_jwt_secret_key_change_in_production # Change in production! JWT_EXPIRATION=24h # Token expiration time # File Storage UPLOAD_DIR=/data/uploads # File storage directory # SMS Configuration SMS_PROVIDER=mock # mock | twilio | other TWILIO_ACCOUNT_SID= # Twilio account (if using Twilio) TWILIO_AUTH_TOKEN= # Twilio token TWILIO_PHONE_NUMBER= # Twilio sender number ``` **Important**: - Leave `SMS_PROVIDER=mock` for development (logs OTP to console) - Never commit `.env` file to Git (add to `.gitignore`) - Change `JWT_SECRET` before deploying to production ### Frontend Environment **File**: `frontend/.env` ```env VITE_API_URL=http://localhost:3001/api ``` This URL is used by the React frontend to connect to the backend API. ### Docker Compose Configuration **File**: `docker-compose.yml` This file is already configured. Key services: 1. **PostgreSQL Database** - Port: `5432` (accessible from host) - User: `nutshell` - Password: `nutshell_dev_password` - Database: `nutshell_db` 2. **File Storage (Nginx)** - Port: `8080` - Serves uploaded files at `http://localhost:8080` --- ## Running the Application ### Start Infrastructure (Docker) Open a terminal and run: ```bash docker-compose up -d ``` Verify all services started: ```bash docker-compose ps ``` Expected output: ``` NAME STATUS PORTS nutshell_postgres Up (healthy) 0.0.0.0:5432->5432/tcp nutshell_file_storage Up 0.0.0.0:8080->80/tcp ``` ### Start Backend API Open a new terminal: ```bash cd backend npm run dev ``` Expected output: ``` [10:30:45] ts-node version 10.9.1 ✓ Database connection established ✓ API server running on http://localhost:3001 ✓ Health check: http://localhost:3001/api/health ``` ### Start Frontend Open another terminal: ```bash cd frontend npm run dev ``` Expected output: ``` VITE v4.4.9 ready in 456 ms ➜ Local: http://localhost:3000/ ➜ press h to show help ``` ### Access the Application 1. **Frontend**: http://localhost:3000 2. **Backend API**: http://localhost:3001 3. **File Storage**: http://localhost:8080 4. **API Health**: http://localhost:3001/api/health --- ## Database Management ### Access PostgreSQL ```bash docker exec -it nutshell_postgres psql -U nutshell -d nutshell_db ``` Useful commands: ```sql -- List all tables \dt -- View table structure \d orders -- View all users SELECT * FROM users; -- View all orders SELECT * FROM orders; -- Count orders by status SELECT status, COUNT(*) FROM orders GROUP BY status; -- Exit \q ``` ### Backup Database ```bash docker exec nutshell_postgres pg_dump -U nutshell nutshell_db > backup.sql ``` ### Restore Database ```bash docker exec -i nutshell_postgres psql -U nutshell nutshell_db < backup.sql ``` ### Reset Database (Delete All Data) ```bash docker-compose down -v docker-compose up -d ``` ⚠️ **Warning**: This will delete all data in the database. --- ## API Testing ### 1. Health Check ```bash curl http://localhost:3001/api/health ``` Response: ```json { "success": true, "data": { "status": "ok", "timestamp": "2026-07-15T10:30:00Z" }, "errors": [], "timestamp": "2026-07-15T10:30:00Z" } ``` ### 2. Request OTP ```bash curl -X POST http://localhost:3001/api/auth/request-otp \ -H "Content-Type: application/json" \ -d '{"phone": "+7 999 123 45 67"}' ``` Response: ```json { "success": true, "data": { "message": "OTP sent successfully" }, "errors": [], "timestamp": "2026-07-15T10:30:00Z" } ``` **Check backend logs for OTP**: ``` [MOCK SMS] OTP for 79991234567: 123456 ``` ### 3. Verify OTP and Get Token ```bash curl -X POST http://localhost:3001/api/auth/verify-otp \ -H "Content-Type: application/json" \ -d '{"phone": "+7 999 123 45 67", "otp": "123456"}' ``` Response: ```json { "success": true, "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": "550e8400-e29b-41d4-a716-446655440000", "phone": "79991234567", "role": "customer", "email": null, "name": null } }, "errors": [], "timestamp": "2026-07-15T10:30:00Z" } ``` ### 4. Use Token for Authenticated Requests ```bash TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." curl -X GET http://localhost:3001/api/orders \ -H "Authorization: Bearer $TOKEN" ``` ### Using Postman 1. Open **Postman** 2. Create collection: `Nutshell MVP` 3. Add requests: - `POST /api/auth/request-otp` - `POST /api/auth/verify-otp` 4. In **Authorization** tab, set: - Type: `Bearer Token` - Token: Use value from verify-otp response --- ## Troubleshooting ### Issue: npm install hangs **Solution**: ```bash # Clear npm cache npm cache clean --force # Try again npm install # Or use npm ci for cleaner install npm ci ``` ### Issue: Port already in use **Check what's using port**: ```bash # Windows netstat -ano | findstr :3001 # macOS/Linux lsof -i :3001 ``` **Solution**: Change port in `.env` or kill process using it ### Issue: PostgreSQL connection refused **Check if running**: ```bash docker-compose ps postgres ``` **Restart PostgreSQL**: ```bash docker-compose restart postgres docker-compose logs postgres ``` ### Issue: CORS errors in frontend **Check backend CORS middleware** in `backend/src/app.ts`: ```typescript app.use(cors()); ``` Should be at top of middleware stack. **Check frontend API URL** in `frontend/.env`: ```env VITE_API_URL=http://localhost:3001/api ``` ### Issue: OTP not appearing in console **Verify SMS_PROVIDER setting**: ```bash # backend/.env SMS_PROVIDER=mock ``` Should see in backend logs: ``` [MOCK SMS] OTP for 79991234567: 123456 ``` ### Issue: Database migrations not running **Manually initialize**: ```bash cd backend npm run build # Compile TypeScript npm run dev # Auto-migrates on startup ``` --- ## Development Workflow ### Adding a New Route 1. **Create route handler** (`backend/src/routes/new-route.ts`): ```typescript import { Router } from 'express'; import { authMiddleware } from '../middleware/auth'; const router = Router(); router.get('/', authMiddleware, (req, res) => { res.json({ success: true, data: {} }); }); export default router; ``` 2. **Register in app** (`backend/src/app.ts`): ```typescript import newRoutes from './routes/new-route'; app.use('/api/new', newRoutes); ``` 3. **Restart backend**: ```bash npm run dev # ts-node auto-reloads ``` ### Adding Database Entity 1. **Create entity** (`backend/src/entities/NewEntity.ts`): ```typescript import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity('table_name') export class NewEntity { @PrimaryGeneratedColumn('uuid') id: string; @Column({ type: 'varchar', length: 255 }) name: string; } ``` 2. **TypeORM auto-creates schema** on next startup ### Running TypeScript Compilation ```bash cd backend npm run build # Compiles to dist/ npm start # Runs compiled code ``` ### Production Build **Frontend**: ```bash cd frontend npm run build # Creates optimized dist/ folder ``` **Backend**: ```bash cd backend npm run build # Compiles TypeScript node dist/app.js # Run compiled code ``` --- ## Environment Variables Summary | Variable | Backend | Frontend | Purpose | |----------|---------|----------|---------| | NODE_ENV | ✓ | - | development or production | | PORT | ✓ | - | API server port | | DATABASE_* | ✓ | - | PostgreSQL connection | | JWT_SECRET | ✓ | - | Token signing key | | UPLOAD_DIR | ✓ | - | File storage path | | VITE_API_URL | - | ✓ | Backend API endpoint | --- ## Directory Structure ``` backend/ ├── src/ │ ├── app.ts # Express server setup │ ├── database.ts # TypeORM configuration │ ├── entities/ # Database models │ ├── middleware/ # Custom middleware │ ├── routes/ # API route handlers │ └── services/ # Business logic ├── dist/ # Compiled output (created by npm run build) ├── node_modules/ # Dependencies ├── package.json ├── tsconfig.json └── .env # Environment variables (NOT in git) frontend/ ├── src/ │ ├── pages/ # Page components │ ├── components/ # Reusable React components │ ├── context/ # React context (auth, etc.) │ ├── i18n/ # Translations │ ├── utils/ # Helper functions │ ├── App.tsx # Main app component │ └── main.tsx # React entry point ├── index.html # HTML template ├── package.json ├── vite.config.ts # Vite configuration └── .env # Environment variables ``` --- ## Next Steps 1. Follow QUICK_START.md to get running in 5 minutes 2. Test API endpoints in API Testing section above 3. Explore database schema in PostgreSQL 4. Review Phase 1 code in `backend/src/` 5. Read README.md for full Phase breakdown Good luck! 🚀