# 📚 LuckyChit Production Deployment - Master Guide

**Created**: November 5, 2025  
**Based on**: Your actual bash history and production setup

This guide documents your **real** production PM2 setup and provides everything you need to deploy and manage your LuckyChit application.

---

## 📖 Documentation Index

### 🎯 Start Here
1. **[QUICK_REFERENCE.md](QUICK_REFERENCE.md)** - Your daily command cheat sheet  
   *Start here for common tasks and quick fixes*

2. **[ACTUAL_PRODUCTION_SETUP.md](ACTUAL_PRODUCTION_SETUP.md)** - Your real production configuration  
   *Understanding what you currently have running*

### 📚 Detailed Guides
3. **[PM2_PRODUCTION_GUIDE.md](PM2_PRODUCTION_GUIDE.md)** - Best practices and recommendations  
   *Industry standard PM2 setup guide*

4. **[PRODUCTION_DIFFERENCES.md](PRODUCTION_DIFFERENCES.md)** - What's different and why  
   *Comparison between your setup and best practices*

5. **[PRODUCTION_UPDATE_GUIDE.md](PRODUCTION_UPDATE_GUIDE.md)** - Existing update guide  
   *Your previous deployment documentation*

---

## 🚀 Deployment Scripts

All scripts are ready to use on your production server at `/home/luckychit/apps/chitfund/`

### Main Deployment Scripts

| Script | Purpose | When to Use |
|--------|---------|-------------|
| `deploy-full.sh` | Deploy backend + frontend | Most code updates |
| `deploy-backend-only.sh` | Deploy backend only | API/backend changes only |
| `deploy-frontend-only.sh` | Deploy frontend only | UI/frontend changes only |

**Usage**:
```bash
ssh luckychit@192.168.8.148
cd /home/luckychit/apps/chitfund
./deploy-full.sh
```

### Database Management Scripts

| Script | Purpose | When to Use |
|--------|---------|-------------|
| `backup-database.sh` | Backup PostgreSQL database | Daily (automated via cron) |
| `restore-database.sh` | Restore from backup | Emergency recovery |

**Usage**:
```bash
# Backup
./backup-database.sh

# Restore
./restore-database.sh
# (Will show list of backups to choose from)
```

---

## ⚡ Quick Start Guide

### First Time Setup (Already Done!)

Your production is already set up with:
- ✅ PM2 running backend on port 3000
- ✅ PM2 serving frontend on port 8080
- ✅ Auto-start on server reboot configured
- ✅ Git repository at `/home/luckychit/apps/chitfund`

### Daily Deployment Workflow

```bash
# 1. On your dev machine: Commit and push changes
git add .
git commit -m "Your changes"
git push origin prodnew

# 2. SSH into production server
ssh luckychit@192.168.8.148

# 3. Navigate to project
cd /home/luckychit/apps/chitfund

# 4. Run deployment script
./deploy-full.sh

# 5. Verify
pm2 status
pm2 logs --lines 20

# 6. Test in browser
# Backend: http://192.168.8.148:3000/health
# Frontend: http://192.168.8.148:8080
```

---

## 📊 Current Production Setup

### Server Details
```
Server IP: 192.168.8.148
Domain: chitfund.deepteklabs.com
User: luckychit
Home: /home/luckychit
Project: /home/luckychit/apps/chitfund
Branch: prodnew
```

### Running Services (PM2)
```
┌─────────────────────┬─────┬────────┬─────────┐
│ App Name            │ PID │ Status │ Port    │
├─────────────────────┼─────┼────────┼─────────┤
│ luckychit-api       │ ... │ online │ 3000    │
│ luckychit-frontend  │ ... │ online │ 8080    │
└─────────────────────┴─────┴────────┴─────────┘
```

### Directory Structure
```
/home/luckychit/apps/chitfund/
├── backend/                    # Node.js Express API
│   ├── src/
│   │   └── server.js          # Entry point (started by PM2)
│   ├── ecosystem.config.js    # PM2 config (not currently used)
│   ├── .env                   # Environment variables
│   └── package.json
│
├── luckychit/                 # Flutter application
│   ├── lib/                   # Dart source code
│   ├── web/                   # Web-specific files
│   └── build/web/            # Built files (served by PM2)
│
├── deploy-full.sh            # Main deployment script
├── deploy-backend-only.sh    # Backend deployment
├── deploy-frontend-only.sh   # Frontend deployment
├── backup-database.sh        # Database backup
└── restore-database.sh       # Database restore
```

---

## 🎯 Most Common Tasks

### ✅ Deploy Code Update
```bash
cd /home/luckychit/apps/chitfund
./deploy-full.sh
```

### ✅ View Logs
```bash
pm2 logs                           # Live logs
pm2 logs luckychit-api --lines 50  # Backend logs
```

### ✅ Check Status
```bash
pm2 status
```

### ✅ Restart Services
```bash
pm2 restart all
```

### ✅ Backup Database
```bash
./backup-database.sh
```

---

## ⚠️ Common Issues & Solutions

### Issue: "invalid ELF header" (bcrypt error)

**Cause**: node_modules installed on Windows  
**Fix**:
```bash
cd /home/luckychit/apps/chitfund/backend
rm -rf node_modules package-lock.json
npm install
pm2 restart luckychit-api
```

### Issue: Frontend not updating

**Fix**:
```bash
cd /home/luckychit/apps/chitfund/luckychit
flutter clean
rm -rf .dart_tool build
flutter pub get
flutter build web --release
pm2 restart luckychit-frontend
```

### Issue: Git pull conflicts

**Fix**:
```bash
git stash
git pull origin prodnew
```

### Issue: PM2 not running after reboot

**Fix**:
```bash
pm2 resurrect
# or
pm2 startup
pm2 save
```

---

## 🔧 Maintenance Tasks

### Daily
- ✅ Check `pm2 status` for any crashed processes
- ✅ Review `pm2 logs` for errors
- ✅ Monitor disk space: `df -h`

### Weekly
- ✅ Backup database manually: `./backup-database.sh`
- ✅ Review backup retention: `ls -lh /home/luckychit/backups/`
- ✅ Check log sizes: `du -h backend/logs/`

### Monthly
- ✅ Update dependencies: `npm update` (test first!)
- ✅ Review PM2 configuration
- ✅ Test disaster recovery with a restore

---

## 🚨 Emergency Procedures

### Complete PM2 Reset
```bash
pm2 kill
pm2 save --force

# Restart from scratch
cd /home/luckychit/apps/chitfund/backend
pm2 start src/server.js --name luckychit-api

cd ../luckychit
pm2 serve build/web 8080 --name luckychit-frontend --spa

pm2 save
pm2 status
```

### Database Recovery
```bash
./restore-database.sh
# Follow prompts to select backup
```

### Server Won't Start
```bash
# Check logs
pm2 logs --lines 200

# Check database
psql -U luckychit -h localhost -d luckychit

# Check ports
netstat -tulpn | grep -E '(3000|8080)'

# Check environment
cd /home/luckychit/apps/chitfund/backend
cat .env
```

---

## 📈 Performance Optimization (Optional Upgrade)

Your current setup works but could be improved. See [PRODUCTION_DIFFERENCES.md](PRODUCTION_DIFFERENCES.md) for:

1. **Use ecosystem.config.js** - Enable cluster mode for better performance
2. **Enable nginx** - Add SSL and reverse proxy
3. **Setup log rotation** - Prevent disk space issues
4. **Automated backups** - Schedule daily database backups
5. **Memory limits** - Prevent crashes from memory leaks

**To upgrade**:
```bash
cd /home/luckychit/apps/chitfund/backend
pm2 delete luckychit-api
pm2 start ecosystem.config.js --env production
pm2 save
```

---

## 📞 Support Resources

### Documentation Files
- `QUICK_REFERENCE.md` - Command cheat sheet
- `ACTUAL_PRODUCTION_SETUP.md` - Current setup details
- `PM2_PRODUCTION_GUIDE.md` - Best practices
- `PRODUCTION_DIFFERENCES.md` - Comparison guide

### External Resources
- PM2 Docs: https://pm2.keymetrics.io/docs/
- Flutter Deployment: https://docs.flutter.dev/deployment/web
- PostgreSQL Backup: https://www.postgresql.org/docs/current/backup.html

### Quick Help Commands
```bash
# PM2 help
pm2 --help
pm2 start --help

# Check versions
pm2 --version
node --version
flutter --version

# Check system resources
pm2 monit
htop
df -h
```

---

## 📋 Pre-Flight Checklist

Before any deployment, verify:

- [ ] Changes tested locally
- [ ] Committed to `prodnew` branch
- [ ] Pushed to remote repository
- [ ] SSH access to production server
- [ ] No one else is deploying
- [ ] Database backup is recent (< 24 hours)

After deployment, verify:

- [ ] `pm2 status` shows all processes online
- [ ] No errors in `pm2 logs`
- [ ] Backend health check responds: `curl http://localhost:3000/health`
- [ ] Frontend loads: `curl http://localhost:8080`
- [ ] Test critical user flows (login, etc.)

---

## 🎓 Understanding Your Setup

### How PM2 Was Set Up (From Your History)

**Line 173**: Started backend
```bash
pm2 start src/server.js --name luckychit-api
```

**Lines 174-175**: Configured auto-restart on server reboot
```bash
pm2 startup systemd -u luckychit --hp /home/luckychit
pm2 save
```

**Lines 244-250**: Built and deployed frontend
```bash
flutter build web --release
pm2 serve /home/luckychit/apps/chitfund/luckychit/build/web 8080 --name luckychit-frontend --spa
pm2 save
```

### Your Typical Update Pattern (Lines 369-388)
1. Navigate to project root
2. `git pull origin prodnew`
3. Backend: `cd backend && npm install && pm2 restart luckychit-api`
4. Frontend: `cd luckychit && flutter pub get && flutter build web --release && pm2 restart luckychit-frontend`
5. Verify with `pm2 status` and `pm2 logs`

---

## 🎉 You're All Set!

Your production environment is documented and you have:

✅ **Deployment scripts** for easy updates  
✅ **Backup scripts** for database safety  
✅ **Quick reference** for daily commands  
✅ **Comprehensive guides** for troubleshooting  
✅ **Emergency procedures** for worst-case scenarios

**Next Steps**:

1. **Bookmark** `QUICK_REFERENCE.md` for daily use
2. **Set up** automated database backups (cron job)
3. **Consider** upgrading to ecosystem.config.js for better performance
4. **Test** the deployment scripts on your next update

---

**Need Help?** Start with `QUICK_REFERENCE.md` and work your way through the other guides as needed.

**Happy Deploying! 🚀**

