# EduManage SMS — Deployment Guide
## Stack: Vercel (Frontend) + Render (Backend) + MongoDB Atlas

> **Deploying to cPanel instead?** See [`DEPLOYMENT_CPANEL.md`](./DEPLOYMENT_CPANEL.md).

---

## 1. MongoDB Atlas Setup

1. Go to [cloud.mongodb.com](https://cloud.mongodb.com) → Create free cluster
2. **Database Access** → Add user: `edumanage_user` / strong password
3. **Network Access** → Add IP: `0.0.0.0/0` (allows all — restrict in production)
4. **Connect** → Drivers → Copy connection string:
   ```
   mongodb+srv://edumanage_user:<password>@cluster0.xxxxx.mongodb.net/edumanage
   ```

---

## 2. Backend — Render.com

1. Push backend to GitHub repo
2. Go to [render.com](https://render.com) → **New Web Service**
3. Connect GitHub repo → select `school-management/backend`
4. Settings:
   ```
   Name:         edumanage-api
   Runtime:      Node
   Build Command: npm install
   Start Command: node server.js
   Plan:         Free (or Starter $7/mo for always-on)
   ```
5. **Environment Variables** (Add all from `.env.example`):
   ```
   NODE_ENV         = production
   PORT             = 10000
   MONGO_URI        = mongodb+srv://...
   JWT_SECRET       = <generate: openssl rand -base64 32>
   JWT_EXPIRE       = 7d
   JWT_REFRESH_SECRET = <generate: openssl rand -base64 32>
   JWT_REFRESH_EXPIRE = 30d
   CLIENT_URL       = https://your-app.vercel.app
   SMTP_HOST        = smtp.gmail.com
   SMTP_PORT        = 587
   SMTP_USER        = your@gmail.com
   SMTP_PASS        = your_app_password
   FROM_EMAIL       = noreply@yourschool.edu.np
   FROM_NAME        = EduManage SMS
   UPLOAD_PATH      = ./uploads
   ```
6. **Deploy** → note the URL: `https://edumanage-api.onrender.com`
7. Seed the database (once):
   ```bash
   # Set MONGO_URI locally in .env, then:
   cd backend && node utils/seeder.js
   ```

---

## 3. Frontend — Vercel

1. Push frontend to GitHub repo
2. Go to [vercel.com](https://vercel.com) → **New Project**
3. Connect GitHub → select `school-management/frontend`
4. Settings (this project uses **Create React App**, not Vite):
   ```
   Framework:      Create React App
   Root Directory: frontend
   Build Command:  npm run build
   Output Dir:     build
   ```
5. **Environment Variables**:
   ```
   REACT_APP_API_URL = https://edumanage-api.onrender.com/api
   ```
6. Click **Deploy** → your app is live at `https://your-app.vercel.app`

---

## 4. Custom Domain (Optional)

### Vercel
- Project Settings → Domains → Add `sms.yourschool.edu.np`
- Update DNS CNAME: `sms` → `cname.vercel-dns.com`

### Render
- Service Settings → Custom Domain → Add `api.yourschool.edu.np`

---

## 5. File Uploads — AWS S3 (Production Recommendation)

For production, replace local `multer` storage with S3:

```bash
npm install @aws-sdk/client-s3 multer-s3
```

```js
// controllers/upload.controller.js — replace storage config
const { S3Client } = require('@aws-sdk/client-s3');
const multerS3 = require('multer-s3');

const s3 = new S3Client({ region: process.env.AWS_REGION });

const storage = multerS3({
  s3,
  bucket: process.env.S3_BUCKET,
  acl: 'public-read',
  key: (req, file, cb) => {
    cb(null, `uploads/${req.user.school}/${Date.now()}-${file.originalname}`);
  },
});
```

Add env vars: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, `S3_BUCKET`

---

## 6. Local Development

```bash
# Clone
git clone https://github.com/yourorg/school-management
cd school-management

# Backend
cd backend
npm install
cp .env.example .env    # Fill in your values
node utils/seeder.js    # Seed demo data
npm run dev             # http://localhost:5000

# Frontend (new terminal)
cd frontend
npm install
echo "REACT_APP_API_URL=http://localhost:5000/api" > .env.local
npm start                # http://localhost:3000
```

### Demo Login Credentials
```
Admin:   admin@janajyoti.edu.np    / Admin@1234
Teacher: ram.khatri@janajyoti.edu.np / Teacher@1234
Student: aarav.karmacharya0@student.janajyoti.edu.np / Student@1234
```
> **Note:** On first login, provide the School ID from seeder output in the login form.

---

## 7. Docker (Optional)

```dockerfile
# backend/Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN mkdir -p uploads
EXPOSE 5000
CMD ["node", "server.js"]
```

```yaml
# docker-compose.yml
version: '3.9'
services:
  api:
    build: ./backend
    ports: ["5000:5000"]
    env_file: ./backend/.env
    volumes: ["./backend/uploads:/app/uploads"]
  mongo:
    image: mongo:7
    ports: ["27017:27017"]
    volumes: ["mongo_data:/data/db"]
volumes:
  mongo_data:
```

```bash
docker-compose up -d
```

---

## 8. Security Checklist for Production

- [ ] Rotate all JWT secrets before go-live
- [ ] Set `NODE_ENV=production`
- [ ] Enable MongoDB Atlas IP whitelist (Render's static IPs or VPC peering)
- [ ] Enable HTTPS only (Vercel/Render do this by default)
- [ ] Set strong rate limits on auth routes
- [ ] Configure SMTP with app password (not main password)
- [ ] Set up MongoDB automated backups in Atlas
- [ ] Add Sentry or similar for error monitoring
- [ ] Restrict CORS `CLIENT_URL` to your exact domain

---

## 9. Architecture Overview

```
┌─────────────────────────────────────────────────┐
│                   Vercel CDN                    │
│           React + Tailwind (SPA)                │
│    Login → Dashboard → Students/Fees/Exams      │
└───────────────────┬─────────────────────────────┘
                    │ HTTPS REST API
                    ▼
┌─────────────────────────────────────────────────┐
│              Render.com (Node.js)               │
│                                                 │
│  Express → JWT Auth → RBAC Middleware           │
│  Routes: /auth /students /fees /attendance …    │
│  Rate limiting · Helmet · Compression           │
└───────────────────┬─────────────────────────────┘
                    │ mongoose
                    ▼
┌─────────────────────────────────────────────────┐
│            MongoDB Atlas (M0 Free)              │
│                                                 │
│  Collections: schools, users, students,         │
│  teachers, classes, subjects, attendance,       │
│  exams, results, feepayments, notices, files    │
└─────────────────────────────────────────────────┘
```

---

## 10. Multi-School SaaS Scaling

To onboard a new school:
1. POST `/api/schools` → creates School document + admin user
2. All subsequent requests include `x-school-id` header
3. Every query is scoped by `school: req.user.school`
4. Each school's data is logically isolated within the same DB
5. For hard isolation (enterprise): use separate MongoDB databases per school

---

*EduManage SMS v2.0 · Built for Nepal/India school context · MIT License*
