From a8c3386f4762c4e9147a3432ef29a431f4a6f2ec Mon Sep 17 00:00:00 2001 From: Deep Koluguri Date: Wed, 5 Nov 2025 18:19:04 -0500 Subject: [PATCH] fixed flutter theme issues --- DEPLOYMENT_README.md | 544 +++++++----------- DEPLOYMENT_TROUBLESHOOTING.md | 561 ++++++++++++++++++ FLUTTER_DEPLOYMENT_GUIDE.md | 653 +++++++++++++++++++++ PM2_PRODUCTION_GUIDE.md | 699 +++++++++++++++++++++++ PM2_QUICK_START.md | 180 ++++++ PRODUCTION_UPDATE_GUIDE.md | 395 +++++++++++++ backend/.gitignore | 2 +- backend/deploy.sh | 65 +++ backend/ecosystem.config.js | 49 ++ backend/fix-bcrypt.sh | 85 +++ luckychit/build-android.sh | 90 +++ luckychit/deploy-web-auto.sh | 111 ++++ luckychit/deploy-web.sh | 55 ++ luckychit/ecosystem.config.js | 27 + luckychit/lib/core/themes/app_theme.dart | 12 +- luckychit/web-server.js | 83 +++ 16 files changed, 3276 insertions(+), 335 deletions(-) create mode 100644 DEPLOYMENT_TROUBLESHOOTING.md create mode 100644 FLUTTER_DEPLOYMENT_GUIDE.md create mode 100644 PM2_PRODUCTION_GUIDE.md create mode 100644 PM2_QUICK_START.md create mode 100644 PRODUCTION_UPDATE_GUIDE.md create mode 100644 backend/deploy.sh create mode 100644 backend/ecosystem.config.js create mode 100644 backend/fix-bcrypt.sh create mode 100644 luckychit/build-android.sh create mode 100644 luckychit/deploy-web-auto.sh create mode 100644 luckychit/deploy-web.sh create mode 100644 luckychit/ecosystem.config.js create mode 100644 luckychit/web-server.js diff --git a/DEPLOYMENT_README.md b/DEPLOYMENT_README.md index 60cf22f..72a621e 100644 --- a/DEPLOYMENT_README.md +++ b/DEPLOYMENT_README.md @@ -1,382 +1,270 @@ -# πŸ“¦ LuckyChit Deployment Files +# πŸ“š LuckyChit Deployment Documentation -This directory contains everything you need to deploy your LuckyChit application on Proxmox LXC. - -## πŸ“š Documentation Files - -### 1. **PROXMOX_DEPLOYMENT_GUIDE.md** ⭐ Main Guide - - **Comprehensive step-by-step deployment guide** - - Covers everything from LXC creation to production deployment - - Includes troubleshooting, security checklist, and maintenance - - **Time Required:** 30-45 minutes - - **Recommended for:** First-time deployments - -### 2. **QUICK_DEPLOY.md** ⚑ Quick Reference - - **Quick command reference for experienced users** - - One-liner commands for common operations - - Useful paths and troubleshooting commands - - **Time Required:** 20-30 minutes - - **Recommended for:** Quick deployments or reference - -### 3. **deploy.sh** πŸ€– Automated Script - - **Automated deployment script** - - Installs all prerequisites automatically - - Sets up database, users, and configuration - - **Time Required:** 10-15 minutes + manual code deployment - - **Recommended for:** Fastest deployment +Complete guide to deploying and updating your LuckyChit application. --- -## πŸš€ Which Method Should You Use? +## πŸ“– Available Guides -### Option 1: Automated Script (Fastest) ⚑ +### 🎯 Quick Start +- **`PRODUCTION_UPDATE_GUIDE.md`** ⭐ **START HERE** - Quick reference for updates +- **`PM2_QUICK_START.md`** - Get backend running in 5 minutes -**Best for:** Quick setup, first-time Linux users +### πŸ“˜ Detailed Guides +- **`PM2_PRODUCTION_GUIDE.md`** - Complete PM2 backend deployment +- **`FLUTTER_DEPLOYMENT_GUIDE.md`** - Complete Flutter frontend deployment +- **`DEPLOYMENT_TROUBLESHOOTING.md`** - Common issues and solutions +--- + +## πŸš€ Quick Commands + +### Update Backend ```bash -# 1. Create Ubuntu 22.04 LXC on Proxmox -# 2. Enter the container -pct enter - -# 3. Download and run the script -curl -o deploy.sh https://raw.githubusercontent.com/YOUR_REPO/deploy.sh -chmod +x deploy.sh -sudo ./deploy.sh - -# 4. Upload your code and deploy -# Follow the on-screen instructions +# On production server +cd backend +git pull origin main +npm install +pm2 reload luckychit-api ``` -**Pros:** -- βœ… Fastest method -- βœ… Less room for error -- βœ… Automatically configures everything - -**Cons:** -- ❌ Less learning opportunity -- ❌ Requires internet connection - ---- - -### Option 2: Manual Deployment (Learning & Control) πŸ“– - -**Best for:** Understanding the system, custom configurations - +### Update Frontend (Web) ```bash -# Follow PROXMOX_DEPLOYMENT_GUIDE.md step-by-step +# On your machine +cd luckychit +./deploy-web.sh +# Then upload build/web/* to server ``` -**Pros:** -- βœ… Full control over every step -- βœ… Better understanding of the system -- βœ… Easy to customize -- βœ… Learn server administration - -**Cons:** -- ❌ Takes longer -- ❌ More typing - --- -### Option 3: Quick Commands (Experienced Users) ⚑ +## πŸ› οΈ Available Scripts -**Best for:** Experienced admins, subsequent deployments +### Backend Scripts (`backend/`) +- **`deploy.sh`** - Full backend deployment +- **`fix-bcrypt.sh`** - Fix native module issues +- **`ecosystem.config.js`** - PM2 configuration +### Frontend Scripts (`luckychit/`) +- **`deploy-web.sh`** - Build Flutter web (local) +- **`deploy-web-auto.sh`** - Build & upload to server +- **`build-android.sh`** - Build Android APK/AAB +- **`web-server.js`** - Express server for Flutter web +- **`ecosystem.config.js`** - PM2 configuration for web + +--- + +## πŸ“‹ Common Scenarios + +### Scenario 1: UI Changes Only ```bash -# Use QUICK_DEPLOY.md for rapid deployment -# Copy-paste command blocks +cd luckychit +flutter build web --release +# Upload to server ``` +**Time:** 2-3 minutes | **Downtime:** None -**Pros:** -- βœ… Fast for experienced users -- βœ… Good for reference -- βœ… Flexible +### Scenario 2: Backend Changes Only +```bash +cd backend +pm2 reload luckychit-api +``` +**Time:** 30 seconds | **Downtime:** None -**Cons:** -- ❌ Requires Linux experience -- ❌ Easy to miss steps if not careful +### Scenario 3: Both UI and Backend +1. Update backend first +2. Then update frontend +**Time:** 5 minutes | **Downtime:** None + +### Scenario 4: Database Changes +1. Backup database first +2. Update backend with migrations +3. Test thoroughly +**Time:** 10-15 minutes | **Downtime:** Possible --- -## πŸ—‚οΈ Project Structure After Deployment +## 🎯 First Time Setup +### Backend +```bash +# Install PM2 +npm install -g pm2 + +# Deploy backend +cd backend +./deploy.sh production +pm2 startup +pm2 save ``` -/home/luckychit/ -β”œβ”€β”€ apps/ -β”‚ └── chitfund/ -β”‚ β”œβ”€β”€ backend/ # Node.js backend -β”‚ β”‚ β”œβ”€β”€ src/ -β”‚ β”‚ β”œβ”€β”€ .env # Environment variables (KEEP SECURE!) -β”‚ β”‚ └── package.json -β”‚ └── luckychit/ # Flutter frontend -β”‚ β”œβ”€β”€ lib/ -β”‚ β”œβ”€β”€ build/web/ # Built web files -β”‚ └── pubspec.yaml -β”œβ”€β”€ logs/ # Application logs -β”œβ”€β”€ backups/ # Database backups -└── backup-db.sh # Backup script -/var/www/luckychit/ # Nginx web root (Flutter web) -/etc/nginx/sites-available/ # Nginx configuration -/var/log/nginx/ # Nginx logs +### Frontend Web +```bash +# Build +cd luckychit +flutter build web --release + +# Deploy to nginx +sudo cp -r build/web/* /var/www/luckychit/ + +# Or use PM2 +npm install express +pm2 start ecosystem.config.js --env production ``` --- -## πŸ“‹ Deployment Checklist +## ⚠️ Common Issues + +### Backend: bcrypt Error +```bash +cd backend +./fix-bcrypt.sh +``` + +### Frontend: Old UI Still Showing +- Hard refresh browser: Ctrl+Shift+R +- Clear browser cache +- Check files updated on server + +### PM2 Not Starting +```bash +pm2 logs luckychit-api --lines 100 +``` + +--- + +## πŸ“ž Getting Help + +1. Check relevant guide in the list above +2. Check `DEPLOYMENT_TROUBLESHOOTING.md` +3. View logs: `pm2 logs` +4. Check server logs: `/var/log/nginx/error.log` + +--- + +## πŸ“ File Structure + +``` +chitfund/ +β”œβ”€β”€ backend/ +β”‚ β”œβ”€β”€ deploy.sh # Backend deployment +β”‚ β”œβ”€β”€ fix-bcrypt.sh # Fix bcrypt issues +β”‚ β”œβ”€β”€ ecosystem.config.js # PM2 config +β”‚ └── server.js # Main server file +β”‚ +β”œβ”€β”€ luckychit/ +β”‚ β”œβ”€β”€ deploy-web.sh # Build web (local) +β”‚ β”œβ”€β”€ deploy-web-auto.sh # Build & upload +β”‚ β”œβ”€β”€ build-android.sh # Build Android +β”‚ β”œβ”€β”€ web-server.js # Express server +β”‚ β”œβ”€β”€ ecosystem.config.js # PM2 web config +β”‚ └── build/web/ # Build output +β”‚ +β”œβ”€β”€ PM2_PRODUCTION_GUIDE.md # Backend guide +β”œβ”€β”€ PM2_QUICK_START.md # Quick backend start +β”œβ”€β”€ FLUTTER_DEPLOYMENT_GUIDE.md # Frontend guide +β”œβ”€β”€ PRODUCTION_UPDATE_GUIDE.md # Update guide ⭐ +β”œβ”€β”€ DEPLOYMENT_TROUBLESHOOTING.md # Troubleshooting +└── DEPLOYMENT_README.md # This file +``` + +--- + +## βœ… Deployment Checklist ### Pre-Deployment -- [ ] Proxmox LXC container created (Ubuntu 22.04) -- [ ] Container has network access -- [ ] You have root/sudo access -- [ ] You have your code ready (Git repo or files to upload) +- [ ] Code tested locally +- [ ] Version updated (if applicable) +- [ ] Database backup (if DB changes) +- [ ] Environment variables checked -### During Deployment -- [ ] System updated -- [ ] Node.js installed (v20) -- [ ] PostgreSQL installed and configured -- [ ] Nginx installed -- [ ] PM2 installed -- [ ] Flutter installed (for web build) -- [ ] Firewall configured -- [ ] Database created with secure password -- [ ] Backend code deployed -- [ ] Frontend built and deployed -- [ ] PM2 configured to auto-start -- [ ] Nginx configured correctly +### Deployment +- [ ] Backend updated (if needed) +- [ ] Frontend rebuilt (if needed) +- [ ] Files uploaded to server +- [ ] Services restarted ### Post-Deployment -- [ ] Test health endpoint: `curl http://localhost:3000/health` -- [ ] Test frontend: Visit `http://YOUR_IP` -- [ ] Test API: Try login from frontend -- [ ] Check logs: `pm2 logs` -- [ ] Setup SSL certificate (Let's Encrypt) -- [ ] Configure automated backups -- [ ] Document your credentials (securely!) -- [ ] Test from external network +- [ ] App loads successfully +- [ ] No errors in logs +- [ ] Critical features tested +- [ ] Monitoring for 15 minutes --- -## πŸ” Important Security Notes +## πŸŽ“ Learn More -### Immediately After Deployment: +### PM2 (Backend) +- Official Docs: https://pm2.keymetrics.io/docs/ +- Commands: `PM2_PRODUCTION_GUIDE.md` β†’ PM2 Commands section -1. **Change Default Passwords** - ```bash - # PostgreSQL password - sudo -u postgres psql - ALTER USER luckychit WITH PASSWORD 'new_secure_password'; - - # Update .env file accordingly - nano /home/luckychit/apps/chitfund/backend/.env - ``` +### Flutter (Frontend) +- Official Docs: https://docs.flutter.dev/deployment +- Web Deploy: https://docs.flutter.dev/deployment/web -2. **Secure JWT Secret** - - Generate a strong random secret (32+ characters) - - Never commit .env to Git - - Use different secrets for dev/staging/production - -3. **Setup SSL/HTTPS** - ```bash - sudo apt install certbot python3-certbot-nginx - sudo certbot --nginx -d yourdomain.com - ``` - -4. **Enable Fail2Ban** (Optional but recommended) - ```bash - sudo apt install fail2ban - sudo systemctl enable fail2ban - sudo systemctl start fail2ban - ``` - -5. **Regular Updates** - ```bash - # Create update script - echo '#!/bin/bash' > ~/update-system.sh - echo 'apt update && apt upgrade -y' >> ~/update-system.sh - chmod +x ~/update-system.sh - - # Run weekly via crontab - # 0 3 * * 0 /root/update-system.sh - ``` +### nginx (Web Server) +- Official Docs: https://nginx.org/en/docs/ +- Configuration: `FLUTTER_DEPLOYMENT_GUIDE.md` β†’ nginx section --- -## πŸ› οΈ Common Post-Deployment Tasks +## πŸ” Security Notes -### Update Application Code +### Never Commit +- `.env` files (backend credentials) +- `node_modules/` (backend) +- `build/` directories (frontend) +- `*.jks`, `*.keystore` (Android signing keys) +- Database backups + +### Always Use +- Strong passwords in production +- SSL certificates (HTTPS) +- Firewall rules +- Regular backups +- Monitoring + +--- + +## πŸ“Š Version History + +Keep track of your deployments: ```bash -# Backend -cd /home/luckychit/apps/chitfund/backend -git pull -npm install --production +# Add to deployment.log +echo "$(date): v1.0.2 - Fixed payment UI bug" >> deployment.log +``` + +--- + +## πŸ’‘ Pro Tips + +1. **Test in staging first** if possible +2. **Deploy during low traffic** hours +3. **Keep deployments small** (easier to rollback) +4. **Monitor after deployment** for 15+ minutes +5. **Document changes** in deployment.log +6. **Have a rollback plan** ready +7. **Communicate with users** about updates + +--- + +## πŸ†˜ Emergency Contacts + +**For Production Issues:** +- PM2 Logs: `pm2 logs luckychit-api` +- nginx Logs: `sudo tail -f /var/log/nginx/error.log` +- Database Logs: `sudo tail -f /var/log/postgresql/postgresql-*.log` + +**Rollback:** +```bash +git checkout pm2 reload luckychit-api - -# Frontend -cd /home/luckychit/apps/chitfund/luckychit -git pull -flutter pub get -flutter build web --release -sudo cp -r build/web/* /var/www/luckychit/ -``` - -### View Logs - -```bash -# PM2 logs (backend) -pm2 logs luckychit-api - -# Nginx access logs -sudo tail -f /var/log/nginx/access.log - -# Nginx error logs -sudo tail -f /var/log/nginx/error.log - -# PostgreSQL logs -sudo tail -f /var/log/postgresql/postgresql-14-main.log -``` - -### Database Backup & Restore - -```bash -# Manual backup -pg_dump -U luckychit -h localhost luckychit > backup.sql - -# Restore -psql -U luckychit -h localhost luckychit < backup.sql - -# Automated backups are already setup (runs daily at 2 AM) -# Check /home/luckychit/backups/ -``` - -### Monitor Resources - -```bash -# System resources -htop - -# PM2 monitoring -pm2 monit - -# Disk space -df -h - -# Memory -free -h - -# Network connections -sudo netstat -tulpn ``` --- -## πŸ†˜ Troubleshooting Quick Guide - -### Backend Won't Start -```bash -pm2 logs luckychit-api # Check logs -node /home/luckychit/apps/chitfund/backend/test-db-connection.js # Test DB -cat /home/luckychit/apps/chitfund/backend/.env # Verify config -``` - -### Can't Access from Browser -```bash -sudo ufw status # Check firewall -sudo systemctl status nginx # Check Nginx -sudo nginx -t # Test Nginx config -curl http://localhost:3000/health # Test backend locally -``` - -### Database Connection Issues -```bash -sudo systemctl status postgresql # Check PostgreSQL -sudo -u postgres psql # Try connecting -# Inside psql: \l # List databases -# Inside psql: \du # List users -``` - -### Out of Disk Space -```bash -df -h # Check space -du -sh /home/luckychit/* | sort -h # Find large directories -pm2 flush # Clear PM2 logs -sudo journalctl --vacuum-time=3d # Clear system logs -``` - ---- - -## πŸ“ž Support Resources - -- **Full Guide:** `PROXMOX_DEPLOYMENT_GUIDE.md` -- **Quick Commands:** `QUICK_DEPLOY.md` -- **Automated Script:** `deploy.sh` - -### External Resources -- [Proxmox Documentation](https://pve.proxmox.com/wiki/Main_Page) -- [Node.js Documentation](https://nodejs.org/en/docs/) -- [Flutter Documentation](https://docs.flutter.dev/) -- [PostgreSQL Documentation](https://www.postgresql.org/docs/) -- [Nginx Documentation](https://nginx.org/en/docs/) -- [PM2 Documentation](https://pm2.keymetrics.io/) - ---- - -## 🎯 Success Criteria - -Your deployment is successful when: - -- βœ… Frontend loads in browser: `http://YOUR_IP` -- βœ… Health endpoint responds: `http://YOUR_IP/health` -- βœ… Can login and use the application -- βœ… PM2 shows app running: `pm2 status` -- βœ… Nginx is running: `sudo systemctl status nginx` -- βœ… Database is accessible: `psql -U luckychit -d luckychit -h localhost` -- βœ… Application survives reboot (test with `sudo reboot`) -- βœ… Firewall is enabled: `sudo ufw status` -- βœ… Automated backups are scheduled: `crontab -l` - ---- - -## πŸ“ˆ Next Steps After Deployment - -1. **Setup Monitoring** - - Install monitoring tools (Netdata, Prometheus, etc.) - - Setup uptime monitoring (UptimeRobot, etc.) - - Configure email alerts - -2. **Performance Optimization** - - Enable Nginx caching - - Configure database connection pooling - - Setup CDN for static assets - -3. **Backup Strategy** - - Test backup restoration - - Setup off-site backups - - Document recovery procedures - -4. **Documentation** - - Document your specific configuration - - Keep credentials in password manager - - Create runbook for common issues - -5. **Team Access** - - Create additional user accounts if needed - - Setup SSH key authentication - - Configure proper permissions - ---- - -## πŸŽ‰ You're All Set! - -Your LuckyChit application should now be running smoothly on Proxmox LXC. - -**Remember:** -- Keep your system updated -- Monitor logs regularly -- Test backups periodically -- Use HTTPS in production -- Document any custom changes - -Good luck! πŸš€ +**πŸŽ‰ Your deployment documentation is complete and production-ready!** +_Last updated: November 2025_ diff --git a/DEPLOYMENT_TROUBLESHOOTING.md b/DEPLOYMENT_TROUBLESHOOTING.md new file mode 100644 index 0000000..329ec3e --- /dev/null +++ b/DEPLOYMENT_TROUBLESHOOTING.md @@ -0,0 +1,561 @@ +# πŸ”§ Deployment Troubleshooting Guide - LuckyChit + +Common deployment issues and their solutions. + +--- + +## 🚨 Critical Issues + +### 1. bcrypt "invalid ELF header" Error + +**Error Message:** +``` +Error: /home/luckychit/apps/chitfund/backend/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header +code: 'ERR_DLOPEN_FAILED' +``` + +**Why This Happens:** +- You installed `node_modules` on Windows +- You deployed to a Linux server +- bcrypt has **native C++ bindings** that are platform-specific +- Windows binaries cannot run on Linux + +**βœ… Solution (Run on Production Server):** + +```bash +cd /home/luckychit/apps/chitfund/backend + +# Stop PM2 process +pm2 stop luckychit-api + +# Remove all node modules +rm -rf node_modules package-lock.json + +# Reinstall on Linux (this will compile native bindings for Linux) +npm install + +# Restart PM2 +pm2 restart luckychit-api + +# Check logs +pm2 logs luckychit-api +``` + +**βœ… Prevention:** + +1. **Never copy `node_modules/` between different operating systems** +2. **Add to your `.gitignore`** (already done): + ``` + node_modules/ + ``` +3. **Always run `npm install` on the target server** +4. **Use the deployment script** which handles this automatically: + ```bash + ./deploy.sh production + ``` + +**Alternative: Use bcryptjs (Pure JavaScript)** + +If you continue having issues, you can switch to `bcryptjs` (no native bindings): + +```bash +npm uninstall bcrypt +npm install bcryptjs +``` + +Then update your code: +```javascript +// Change this: +const bcrypt = require('bcrypt'); + +// To this: +const bcrypt = require('bcryptjs'); + +// The API is identical, no other changes needed! +``` + +--- + +## πŸ”₯ Other Native Module Issues + +**Similar errors with other packages:** +- `node-sass` +- `sharp` +- `sqlite3` +- `canvas` +- `node-gyp` related errors + +**Solution (Same as bcrypt):** +```bash +rm -rf node_modules package-lock.json +npm install +pm2 restart your-app +``` + +--- + +## πŸ“¦ Common PM2 Issues + +### App Won't Start - Crashes Immediately + +**Check logs first:** +```bash +pm2 logs luckychit-api --lines 200 +``` + +**Common causes:** + +#### 1. Missing `.env` File +```bash +# Check if .env exists +ls -la /home/luckychit/apps/chitfund/backend/.env + +# If not, create it +cp .env.example .env +nano .env # Edit with production credentials +``` + +#### 2. Database Connection Failed +```bash +# Check PostgreSQL is running +sudo systemctl status postgresql + +# Test connection +psql -U your_db_user -d chitfund_prod + +# Check .env has correct credentials +cat backend/.env | grep DB_ +``` + +#### 3. Port Already in Use +```bash +# Find what's using port 3000 +lsof -i :3000 +# or +sudo netstat -tulpn | grep 3000 + +# Kill the process +kill -9 + +# Or change port in .env +echo "PORT=3001" >> .env +``` + +#### 4. Missing Dependencies +```bash +cd backend +npm install +pm2 restart luckychit-api +``` + +--- + +### PM2 Shows "errored" Status + +```bash +# Check detailed error +pm2 describe luckychit-api + +# View recent logs +pm2 logs luckychit-api --lines 100 + +# Try manual start to see error +cd backend +node server.js +``` + +--- + +### App Keeps Restarting (Crash Loop) + +```bash +# Check restart count +pm2 list + +# View error logs +pm2 logs luckychit-api --err + +# Common causes: +# - Syntax error in code +# - Missing environment variable +# - Database not accessible +# - Port conflict +``` + +**Reset restart counter:** +```bash +pm2 reset luckychit-api +``` + +--- + +## πŸ—„οΈ Database Issues + +### Connection Refused + +**Symptoms:** +``` +Error: connect ECONNREFUSED 127.0.0.1:5432 +``` + +**Solutions:** + +1. **Check PostgreSQL is running:** + ```bash + sudo systemctl status postgresql + sudo systemctl start postgresql + ``` + +2. **Check PostgreSQL is listening:** + ```bash + sudo netstat -tulpn | grep 5432 + ``` + +3. **Check `pg_hba.conf` allows connection:** + ```bash + sudo nano /etc/postgresql/*/main/pg_hba.conf + + # Should have: + local all all md5 + host all all 127.0.0.1/32 md5 + ``` + +4. **Restart PostgreSQL:** + ```bash + sudo systemctl restart postgresql + ``` + +### Authentication Failed + +**Symptoms:** +``` +Error: password authentication failed for user "postgres" +``` + +**Solution:** +```bash +# Reset password +sudo -u postgres psql +ALTER USER your_db_user WITH PASSWORD 'new_password'; +\q + +# Update .env file +nano backend/.env +# Change DB_PASSWORD=new_password +``` + +### Database Does Not Exist + +**Symptoms:** +``` +Error: database "chitfund_prod" does not exist +``` + +**Solution:** +```bash +# Create database +sudo -u postgres psql +CREATE DATABASE chitfund_prod; +GRANT ALL PRIVILEGES ON DATABASE chitfund_prod TO your_db_user; +\q + +# Run migrations +cd backend +npm run migrate # If you have migrations +``` + +--- + +## 🌐 Network Issues + +### Cannot Access from External IP + +**Check firewall:** +```bash +# Allow port 3000 +sudo ufw allow 3000/tcp + +# Check status +sudo ufw status + +# Or disable temporarily for testing +sudo ufw disable +``` + +**Check if app is listening on 0.0.0.0:** +```bash +sudo netstat -tulpn | grep 3000 + +# Should show 0.0.0.0:3000 not 127.0.0.1:3000 +``` + +**Fix in code:** +```javascript +// In server.js, ensure: +app.listen(PORT, '0.0.0.0', () => { + console.log(`Server running on port ${PORT}`); +}); +``` + +### nginx 502 Bad Gateway + +**Symptoms:** +- nginx returns 502 error +- Backend is running but not accessible through nginx + +**Solutions:** + +1. **Check backend is running:** + ```bash + pm2 list + curl http://localhost:3000/api/health + ``` + +2. **Check nginx configuration:** + ```bash + sudo nginx -t + sudo systemctl restart nginx + ``` + +3. **Check nginx error logs:** + ```bash + sudo tail -f /var/log/nginx/error.log + ``` + +4. **Verify proxy_pass URL is correct:** + ```bash + sudo nano /etc/nginx/sites-available/luckychit + # Should have: proxy_pass http://localhost:3000; + ``` + +--- + +## πŸ’Ύ Permission Issues + +### EACCES: permission denied + +**Symptoms:** +``` +Error: EACCES: permission denied, open '/path/to/file' +``` + +**Solutions:** + +1. **Fix ownership:** + ```bash + sudo chown -R $USER:$USER /home/luckychit/apps/chitfund + ``` + +2. **Fix log directory permissions:** + ```bash + mkdir -p backend/logs + chmod 755 backend/logs + ``` + +3. **Run PM2 as correct user:** + ```bash + # Don't use sudo with PM2 unless necessary + pm2 kill + pm2 start ecosystem.config.js --env production + ``` + +--- + +## πŸ”„ Auto-Start Issues + +### PM2 Doesn't Start After Reboot + +**Check if startup is configured:** +```bash +pm2 startup +# Run the command it outputs + +pm2 save +``` + +**Verify startup script exists:** +```bash +# For systemd: +systemctl status pm2-$USER + +# Check logs: +journalctl -u pm2-$USER -n 50 +``` + +**Re-configure if needed:** +```bash +pm2 unstartup +pm2 startup +# Run the command it outputs +pm2 save +``` + +--- + +## πŸ“Š Performance Issues + +### High Memory Usage + +**Check memory:** +```bash +pm2 monit +# or +pm2 list +``` + +**Solutions:** + +1. **Reduce PM2 instances:** + ```bash + pm2 scale luckychit-api 2 # Reduce to 2 instances + ``` + +2. **Increase memory limit in ecosystem.config.js:** + ```javascript + max_memory_restart: '2G' // Increase from 1G + ``` + +3. **Check for memory leaks:** + ```bash + pm2 logs luckychit-api + # Look for memory warnings + ``` + +### High CPU Usage + +**Check CPU:** +```bash +top +# or +htop +``` + +**Solutions:** + +1. **Reduce instances:** + ```bash + pm2 scale luckychit-api 2 + ``` + +2. **Check for infinite loops in code** + +3. **Optimize database queries** + +--- + +## πŸ” Debugging Tips + +### Enable Debug Mode + +**Temporary debugging:** +```bash +pm2 stop luckychit-api +cd backend +NODE_ENV=production DEBUG=* node server.js +``` + +### Check All Logs + +```bash +# PM2 logs +pm2 logs --lines 500 + +# System logs +journalctl -xe + +# nginx logs (if using) +sudo tail -f /var/log/nginx/error.log +sudo tail -f /var/log/nginx/access.log + +# PostgreSQL logs +sudo tail -f /var/log/postgresql/postgresql-*.log +``` + +### Test API Manually + +```bash +# Test from server +curl http://localhost:3000/api/health + +# Test with verbose output +curl -v http://localhost:3000/api/auth/login \ + -H "Content-Type: application/json" \ + -d '{"mobile":"9999999999","password":"password123"}' +``` + +--- + +## πŸ†˜ Emergency Reset + +**If everything is broken, start fresh:** + +```bash +# Stop and remove all PM2 processes +pm2 kill + +# Remove node_modules +cd /home/luckychit/apps/chitfund/backend +rm -rf node_modules package-lock.json + +# Fresh install +npm install + +# Start fresh +pm2 start ecosystem.config.js --env production +pm2 save + +# Check status +pm2 list +pm2 logs +``` + +--- + +## πŸ“ž Getting Help + +When asking for help, provide: + +1. **Error logs:** + ```bash + pm2 logs luckychit-api --lines 200 > error.log + ``` + +2. **PM2 status:** + ```bash + pm2 list + pm2 describe luckychit-api + ``` + +3. **Environment info:** + ```bash + node --version + pm2 --version + cat /etc/os-release + ``` + +4. **Configuration:** + ```bash + cat backend/ecosystem.config.js + # (Don't share .env - contains secrets!) + ``` + +--- + +## βœ… Prevention Checklist + +- [ ] Never commit `node_modules/` to Git +- [ ] Always run `npm install` on production server +- [ ] Use `.env` for environment-specific config +- [ ] Keep `.env` out of Git (in `.gitignore`) +- [ ] Use PM2 startup for auto-restart +- [ ] Setup log rotation +- [ ] Monitor memory/CPU usage +- [ ] Setup database backups +- [ ] Test deployment in staging first +- [ ] Keep dependencies updated +- [ ] Document your deployment process + +--- + +**Most issues are solved by rebuilding native modules on the production server! 🎯** + diff --git a/FLUTTER_DEPLOYMENT_GUIDE.md b/FLUTTER_DEPLOYMENT_GUIDE.md new file mode 100644 index 0000000..61439d5 --- /dev/null +++ b/FLUTTER_DEPLOYMENT_GUIDE.md @@ -0,0 +1,653 @@ +# πŸ“± Flutter Frontend Deployment Guide - LuckyChit + +Complete guide to deploy and update your Flutter app UI changes in production. + +--- + +## πŸ“‹ Deployment Options + +Your Flutter app can be deployed as: +1. **Web App** (accessible via browser) +2. **Android App** (APK/AAB for Play Store) +3. **iOS App** (IPA for App Store) + +--- + +## 🌐 Option 1: Web Deployment (Recommended for Quick Updates) + +### Initial Setup + +#### Step 1: Build Flutter for Web + +```bash +cd luckychit + +# Clean previous builds +flutter clean + +# Get dependencies +flutter pub get + +# Build for production +flutter build web --release +``` + +This creates optimized files in `luckychit/build/web/` + +#### Step 2: Deploy Web Files + +**Method A: Using nginx (Recommended)** + +```bash +# Copy built files to web server directory +sudo mkdir -p /var/www/luckychit +sudo cp -r build/web/* /var/www/luckychit/ + +# Set permissions +sudo chown -R www-data:www-data /var/www/luckychit +sudo chmod -R 755 /var/www/luckychit +``` + +**Configure nginx:** + +Create/edit `/etc/nginx/sites-available/luckychit`: + +```nginx +server { + listen 80; + server_name your-domain.com; # or your-server-ip + + # Flutter Web App + location / { + root /var/www/luckychit; + index index.html; + try_files $uri $uri/ /index.html; + + # Disable cache for index.html (always get latest) + location = /index.html { + add_header Cache-Control "no-cache, no-store, must-revalidate"; + add_header Pragma "no-cache"; + add_header Expires 0; + } + + # Cache static assets for 1 year + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + } + } + + # Backend API (if on same server) + location /api { + proxy_pass http://localhost:3000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + } +} +``` + +Enable and restart nginx: + +```bash +sudo ln -s /etc/nginx/sites-available/luckychit /etc/nginx/sites-enabled/ +sudo nginx -t +sudo systemctl restart nginx +``` + +**Method B: Using PM2 + http-server** + +```bash +# Install http-server globally +npm install -g http-server + +# Start with PM2 +cd luckychit +pm2 start http-server --name "luckychit-web" -- -p 8080 -c-1 -d false build/web + +# Save +pm2 save +``` + +**Method C: Using PM2 + Express (Custom Server)** + +Create `luckychit/web-server.js`: + +```javascript +const express = require('express'); +const path = require('path'); +const app = express(); +const PORT = process.env.PORT || 8080; + +// Serve static files with proper cache headers +app.use(express.static(path.join(__dirname, 'build/web'), { + maxAge: '1y', + immutable: true, + setHeaders: (res, filePath) => { + // Don't cache index.html + if (filePath.endsWith('index.html')) { + res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); + } + } +})); + +// Handle Flutter routes (SPA) +app.get('*', (req, res) => { + res.sendFile(path.join(__dirname, 'build/web', 'index.html')); +}); + +app.listen(PORT, '0.0.0.0', () => { + console.log(`βœ… Flutter web app running on port ${PORT}`); +}); +``` + +Then: + +```bash +cd luckychit +npm install express +pm2 start web-server.js --name "luckychit-web" +pm2 save +``` + +--- + +## πŸ”„ Updating Web App (How to Push Changes) + +### Quick Update Script + +Create `luckychit/deploy-web.sh`: + +```bash +#!/bin/bash + +echo "πŸš€ Deploying Flutter Web Updates" +echo "=================================" +echo "" + +# Clean and build +echo "🧹 Cleaning previous build..." +flutter clean + +echo "πŸ“¦ Getting dependencies..." +flutter pub get + +echo "πŸ”¨ Building for web (production)..." +flutter build web --release + +if [ $? -eq 0 ]; then + echo "" + echo "βœ… Build successful!" + echo "" + + # Copy to nginx directory + echo "πŸ“€ Deploying to web server..." + sudo cp -r build/web/* /var/www/luckychit/ + + # Or restart PM2 if using PM2 + # pm2 restart luckychit-web + + echo "" + echo "βœ… Deployment complete!" + echo "🌐 Your app is now live with the latest changes!" +else + echo "" + echo "❌ Build failed. Please check errors above." + exit 1 +fi +``` + +**Use it:** + +```bash +cd luckychit +chmod +x deploy-web.sh +./deploy-web.sh +``` + +--- + +## πŸ“± Option 2: Android Deployment + +### Build Android APK + +**For Testing:** + +```bash +cd luckychit + +# Debug APK +flutter build apk --debug + +# Release APK +flutter build apk --release +``` + +APK location: `build/app/outputs/flutter-apk/app-release.apk` + +### Build Android App Bundle (For Play Store) + +```bash +cd luckychit + +# Build release bundle +flutter build appbundle --release +``` + +Bundle location: `build/app/outputs/bundle/release/app-release.aab` + +### Deploy to Users + +**Method 1: Direct Distribution** + +```bash +# Copy APK to server +scp build/app/outputs/flutter-apk/app-release.apk user@server:/var/www/downloads/ + +# Users download and install from: +# https://your-domain.com/downloads/app-release.apk +``` + +**Method 2: Google Play Store** + +1. Sign in to [Google Play Console](https://play.google.com/console) +2. Create app (if first time) +3. Go to **Release** β†’ **Production** +4. Click **Create new release** +5. Upload `app-release.aab` +6. Add release notes +7. Review and rollout + +### Signing Android App (Required for Play Store) + +**Create keystore (first time only):** + +```bash +cd luckychit/android + +keytool -genkey -v -keystore luckychit-key.jks \ + -keyalg RSA -keysize 2048 -validity 10000 \ + -alias luckychit +``` + +**Create `android/key.properties`:** + +```properties +storePassword=your_keystore_password +keyPassword=your_key_password +keyAlias=luckychit +storeFile=/path/to/luckychit-key.jks +``` + +**Update `android/app/build.gradle`:** + +```gradle +// Add before android block +def keystoreProperties = new Properties() +def keystorePropertiesFile = rootProject.file('key.properties') +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) +} + +android { + // ... existing config ... + + signingConfigs { + release { + keyAlias keystoreProperties['keyAlias'] + keyPassword keystoreProperties['keyPassword'] + storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null + storePassword keystoreProperties['storePassword'] + } + } + + buildTypes { + release { + signingConfig signingConfigs.release + } + } +} +``` + +Now build: + +```bash +flutter build appbundle --release +``` + +--- + +## 🍎 Option 3: iOS Deployment + +### Build iOS App + +```bash +cd luckychit + +# Build for iOS +flutter build ios --release +``` + +### Deploy to App Store + +1. Open Xcode: `open ios/Runner.xcworkspace` +2. Select **Product** β†’ **Archive** +3. Once archived, click **Distribute App** +4. Choose **App Store Connect** +5. Follow the upload wizard + +**Or use command line:** + +```bash +cd ios +fastlane deliver +``` + +--- + +## πŸš€ Production Update Workflow + +### For Web (Quickest) + +```bash +# On your development machine +cd luckychit +flutter build web --release + +# Upload to server +scp -r build/web/* user@server:/tmp/flutter-web/ + +# On server +ssh user@server +sudo cp -r /tmp/flutter-web/* /var/www/luckychit/ +# Or if using PM2: +# pm2 restart luckychit-web +``` + +### For Mobile Apps + +1. **Make changes** in your code +2. **Update version** in `pubspec.yaml`: + ```yaml + version: 1.0.1+2 # version+buildNumber + ``` +3. **Build:** + ```bash + # Android + flutter build appbundle --release + + # iOS + flutter build ios --release + ``` +4. **Upload to stores** + +--- + +## πŸ”§ Common Issues & Solutions + +### Web App Not Updating (Cache Issues) + +**Problem:** Users still see old version + +**Solution 1: Force reload** +- Chrome: Ctrl+Shift+R (Windows) or Cmd+Shift+R (Mac) +- Clear browser cache + +**Solution 2: Update index.html cache headers** + +Edit `luckychit/web/index.html` - add to ``: + +```html + + + +``` + +**Solution 3: Version your assets** + +Update `pubspec.yaml`: + +```yaml +version: 1.0.1+2 # Increment this +``` + +Rebuild: + +```bash +flutter clean +flutter pub get +flutter build web --release +``` + +### Android Build Fails + +**Common issues:** + +1. **Gradle version mismatch:** + ```bash + cd android + ./gradlew clean + cd .. + flutter clean + flutter build apk + ``` + +2. **Signing issues:** + - Check `key.properties` exists and paths are correct + - Verify keystore password + +3. **Memory issues:** + ```bash + export GRADLE_OPTS="-Xmx4096m" + flutter build apk --release + ``` + +### iOS Build Fails + +1. **Pod issues:** + ```bash + cd ios + rm Podfile.lock + pod install + cd .. + flutter build ios + ``` + +2. **Provisioning profile:** + - Update in Xcode β†’ Signing & Capabilities + +--- + +## πŸ“¦ Automated Deployment Scripts + +### Complete Web Deployment Script + +Create `flutter-deploy-full.sh`: + +```bash +#!/bin/bash + +# LuckyChit Flutter Web Deployment Script +# Run from project root + +SERVER_USER="your-user" +SERVER_HOST="your-server-ip" +WEB_DIR="/var/www/luckychit" + +echo "πŸš€ LuckyChit Flutter Web Deployment" +echo "====================================" +echo "" + +# Build +cd luckychit +echo "🧹 Cleaning..." +flutter clean + +echo "πŸ“¦ Getting dependencies..." +flutter pub get + +echo "πŸ”¨ Building for web..." +flutter build web --release + +if [ $? -ne 0 ]; then + echo "❌ Build failed!" + exit 1 +fi + +echo "βœ… Build successful!" +echo "" + +# Upload to server +echo "πŸ“€ Uploading to production server..." +rsync -avz --delete build/web/ $SERVER_USER@$SERVER_HOST:$WEB_DIR/ + +if [ $? -eq 0 ]; then + echo "" + echo "βœ… Deployment complete!" + echo "🌐 Your app is now live!" + echo "" + echo "Clear browser cache (Ctrl+Shift+R) to see changes" +else + echo "❌ Upload failed!" + exit 1 +fi +``` + +### Android Auto-Build Script + +Create `luckychit/build-android.sh`: + +```bash +#!/bin/bash + +echo "πŸ€– Building Android Release" +echo "============================" +echo "" + +# Clean +echo "🧹 Cleaning..." +flutter clean + +# Get dependencies +echo "πŸ“¦ Getting dependencies..." +flutter pub get + +# Build +echo "πŸ”¨ Building APK..." +flutter build apk --release + +echo "πŸ”¨ Building App Bundle..." +flutter build appbundle --release + +echo "" +echo "βœ… Build complete!" +echo "" +echo "πŸ“¦ APK: build/app/outputs/flutter-apk/app-release.apk" +echo "πŸ“¦ AAB: build/app/outputs/bundle/release/app-release.aab" +echo "" +echo "Upload AAB to Google Play Console" +``` + +--- + +## πŸ“Š Version Management + +### Update Version in pubspec.yaml + +```yaml +name: luckychit +description: Digital Chit Fund Management +version: 1.0.2+3 # Format: major.minor.patch+buildNumber + +# Increment for each release: +# - major: Breaking changes (2.0.0) +# - minor: New features (1.1.0) +# - patch: Bug fixes (1.0.1) +# - buildNumber: Each build (1.0.0+5) +``` + +### Check Current Version + +```bash +cd luckychit +grep "^version:" pubspec.yaml +``` + +--- + +## βœ… Deployment Checklist + +### Before Deploying + +- [ ] All changes tested locally +- [ ] Version incremented in `pubspec.yaml` +- [ ] Backend API URL updated (if changed) +- [ ] `flutter clean` executed +- [ ] `flutter pub get` executed +- [ ] Build completed successfully +- [ ] No errors in console + +### After Deploying + +- [ ] Web: Files copied to `/var/www/luckychit/` +- [ ] Web: nginx restarted (if needed) +- [ ] Test app in browser (hard refresh) +- [ ] Test on mobile device (if mobile build) +- [ ] Check all features work +- [ ] Monitor for errors + +--- + +## 🎯 Quick Reference + +```bash +# Clean build +flutter clean && flutter pub get + +# Web (production) +flutter build web --release + +# Android APK +flutter build apk --release + +# Android Bundle (Play Store) +flutter build appbundle --release + +# iOS +flutter build ios --release + +# Check version +grep "^version:" pubspec.yaml +``` + +--- + +## πŸ“± Testing Builds + +### Web +```bash +cd luckychit/build/web +python3 -m http.server 8000 +# Visit: http://localhost:8000 +``` + +### Android +```bash +# Install on connected device +flutter install + +# Or manually install APK +adb install build/app/outputs/flutter-apk/app-release.apk +``` + +--- + +**Your Flutter frontend is now ready to deploy and update! πŸŽ‰** + +For backend updates, see: `PM2_PRODUCTION_GUIDE.md` + diff --git a/PM2_PRODUCTION_GUIDE.md b/PM2_PRODUCTION_GUIDE.md new file mode 100644 index 0000000..bc37c4c --- /dev/null +++ b/PM2_PRODUCTION_GUIDE.md @@ -0,0 +1,699 @@ +# πŸš€ PM2 Production Deployment Guide - LuckyChit + +Complete guide to deploy and manage your LuckyChit application using PM2 in production. + +--- + +## πŸ“‹ Table of Contents + +1. [Prerequisites](#prerequisites) +2. [Initial Setup](#initial-setup) +3. [Backend Deployment](#backend-deployment) +4. [Flutter App Deployment](#flutter-app-deployment) +5. [PM2 Commands](#pm2-commands) +6. [Monitoring & Logs](#monitoring--logs) +7. [Auto-Start on Server Reboot](#auto-start-on-server-reboot) +8. [Production Best Practices](#production-best-practices) +9. [Troubleshooting](#troubleshooting) + +--- + +## Prerequisites + +### System Requirements +- Node.js 16+ installed +- PostgreSQL database running +- PM2 installed globally +- nginx (optional, for reverse proxy) + +### Install PM2 Globally + +```bash +npm install -g pm2 +``` + +Verify installation: +```bash +pm2 --version +``` + +--- + +## Initial Setup + +### 1. Clone Repository (if not already done) + +```bash +cd /var/www # or your preferred directory +git clone luckychit +cd luckychit +``` + +### 2. Setup Backend + +```bash +cd backend +npm install --production + +# Create .env file with production credentials +cp .env.example .env +nano .env # Edit with production values +``` + +**Important `.env` settings for production:** + +```env +NODE_ENV=production +PORT=3000 +DB_HOST=localhost +DB_PORT=5432 +DB_NAME=chitfund_prod +DB_USER=your_db_user +DB_PASSWORD=your_secure_password +JWT_SECRET=your_very_secure_random_string_min_32_chars +``` + +### 3. Create Logs Directory + +```bash +mkdir -p logs +``` + +### 4. Database Setup + +```bash +# Create production database +createdb chitfund_prod + +# Run migrations (if you have any) +# npm run migrate +``` + +--- + +## Backend Deployment + +### Option 1: Using ecosystem.config.js (Recommended) + +The `ecosystem.config.js` file is already configured in the backend directory. + +**Start in Production Mode:** + +```bash +cd backend +pm2 start ecosystem.config.js --env production +``` + +**Key Features Enabled:** +- βœ… Cluster mode (uses all CPU cores) +- βœ… Auto-restart on crashes +- βœ… Memory limit (1GB max) +- βœ… Log rotation +- βœ… Daily cron restart at 3 AM +- βœ… Error tracking with source maps + +### Option 2: Simple Start Command + +```bash +cd backend +pm2 start server.js --name "luckychit-backend" -i max --env production +``` + +### Verify Backend is Running + +```bash +pm2 list +pm2 logs luckychit-backend +``` + +You should see: +``` +βœ… Database models synchronized +⏰ Starting payment reminder scheduler... +πŸš€ Server running on port 3000 +``` + +--- + +## Flutter App Deployment + +### Option 1: Deploy as Web App + +**Build Flutter for Web:** + +```bash +cd luckychit +flutter build web --release +``` + +**Serve with PM2 using http-server:** + +```bash +# Install http-server globally +npm install -g http-server + +# Start with PM2 +pm2 start http-server --name "luckychit-web" -- -p 8080 -d false -c-1 build/web +``` + +**Or using a custom Node.js server:** + +Create `luckychit/server.js`: + +```javascript +const express = require('express'); +const path = require('path'); +const app = express(); +const PORT = process.env.PORT || 8080; + +app.use(express.static(path.join(__dirname, 'build/web'))); + +app.get('*', (req, res) => { + res.sendFile(path.join(__dirname, 'build/web', 'index.html')); +}); + +app.listen(PORT, () => { + console.log(`Flutter app running on port ${PORT}`); +}); +``` + +Then start with PM2: + +```bash +cd luckychit +npm install express +pm2 start server.js --name "luckychit-web" +``` + +### Option 2: Deploy as Mobile App + +For Android/iOS, build and deploy to app stores: + +```bash +# Android +cd luckychit +flutter build apk --release +flutter build appbundle --release + +# iOS +flutter build ipa --release +``` + +Upload to Google Play Store / Apple App Store. + +--- + +## PM2 Commands + +### Basic Commands + +```bash +# List all processes +pm2 list +pm2 ls + +# Show detailed info +pm2 show luckychit-backend + +# Monitor in real-time +pm2 monit + +# Stop application +pm2 stop luckychit-backend + +# Restart application +pm2 restart luckychit-backend + +# Reload (zero-downtime restart) +pm2 reload luckychit-backend + +# Delete from PM2 +pm2 delete luckychit-backend + +# Stop all +pm2 stop all + +# Restart all +pm2 restart all +``` + +### Advanced Commands + +```bash +# Restart with different env +pm2 restart luckychit-backend --env production + +# Scale to 4 instances +pm2 scale luckychit-backend 4 + +# Reset restart counter +pm2 reset luckychit-backend + +# Update PM2 +pm2 update +``` + +--- + +## Monitoring & Logs + +### View Logs + +```bash +# View all logs (live) +pm2 logs + +# View specific app logs +pm2 logs luckychit-backend + +# View only errors +pm2 logs luckychit-backend --err + +# View last 200 lines +pm2 logs luckychit-backend --lines 200 + +# Clear logs +pm2 flush +``` + +### Log Files Location + +Logs are stored in: +``` +backend/logs/ +β”œβ”€β”€ err.log # Error logs +β”œβ”€β”€ out.log # Output logs +└── combined.log # Combined logs +``` + +### Real-time Monitoring + +```bash +# CPU and Memory monitoring +pm2 monit + +# Web-based monitoring (PM2 Plus - optional) +pm2 plus +``` + +### Install PM2 Log Rotate (Recommended) + +```bash +pm2 install pm2-logrotate + +# Configure log rotation +pm2 set pm2-logrotate:max_size 10M +pm2 set pm2-logrotate:retain 30 +pm2 set pm2-logrotate:compress true +``` + +--- + +## Auto-Start on Server Reboot + +### Generate Startup Script + +```bash +# Generate startup script +pm2 startup + +# This will output a command like: +# sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u youruser --hp /home/youruser + +# Copy and run the command it outputs +``` + +### Save Current Process List + +```bash +pm2 save +``` + +Now PM2 will automatically restart your apps after server reboot! + +### Test Auto-Start + +```bash +# Reboot server +sudo reboot + +# After reboot, check if apps are running +pm2 list +``` + +--- + +## Production Best Practices + +### 1. Environment Variables + +βœ… **DO:** +- Use `.env` file for sensitive data +- Set `NODE_ENV=production` +- Use strong JWT secrets (min 32 characters) +- Use different credentials for production + +❌ **DON'T:** +- Commit `.env` to Git +- Use development credentials in production +- Use weak or default passwords + +### 2. Security + +```bash +# Create limited user for PM2 +sudo adduser pm2user +sudo -u pm2user pm2 start ecosystem.config.js + +# Setup firewall +sudo ufw allow 3000/tcp # Backend port +sudo ufw allow 80/tcp # HTTP +sudo ufw allow 443/tcp # HTTPS +sudo ufw enable +``` + +### 3. Reverse Proxy with nginx (Recommended) + +**Install nginx:** + +```bash +sudo apt update +sudo apt install nginx +``` + +**Configure nginx:** + +Create `/etc/nginx/sites-available/luckychit`: + +```nginx +server { + listen 80; + server_name your-domain.com; + + # Backend API + location /api { + proxy_pass http://localhost:3000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_cache_bypass $http_upgrade; + } + + # Flutter Web App + location / { + proxy_pass http://localhost:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_cache_bypass $http_upgrade; + } +} +``` + +**Enable site:** + +```bash +sudo ln -s /etc/nginx/sites-available/luckychit /etc/nginx/sites-enabled/ +sudo nginx -t +sudo systemctl restart nginx +``` + +### 4. SSL Certificate (Let's Encrypt) + +```bash +# Install certbot +sudo apt install certbot python3-certbot-nginx + +# Get certificate +sudo certbot --nginx -d your-domain.com + +# Auto-renewal is setup automatically +sudo certbot renew --dry-run +``` + +### 5. Database Backups + +**Automated daily backup script:** + +Create `backup.sh`: + +```bash +#!/bin/bash +BACKUP_DIR="/var/backups/postgres" +DATE=$(date +%Y%m%d_%H%M%S) +mkdir -p $BACKUP_DIR + +pg_dump -U your_db_user chitfund_prod > $BACKUP_DIR/backup_$DATE.sql + +# Keep only last 7 days +find $BACKUP_DIR -name "backup_*.sql" -mtime +7 -delete +``` + +**Schedule with cron:** + +```bash +crontab -e + +# Add this line (runs daily at 2 AM): +0 2 * * * /path/to/backup.sh +``` + +### 6. Health Checks + +Add health check endpoint in your backend: + +```javascript +// In backend/server.js or routes +app.get('/health', (req, res) => { + res.status(200).json({ + status: 'ok', + timestamp: new Date().toISOString(), + uptime: process.uptime() + }); +}); +``` + +Monitor with: + +```bash +curl http://localhost:3000/health +``` + +--- + +## Troubleshooting + +### ⚠️ CRITICAL: bcrypt "invalid ELF header" Error + +**Symptoms:** +``` +Error: /path/to/bcrypt_lib.node: invalid ELF header +code: 'ERR_DLOPEN_FAILED' +``` + +**Cause:** bcrypt was installed on Windows but running on Linux (native bindings are platform-specific) + +**Solution:** +```bash +cd backend + +# Remove all modules and rebuild for Linux +rm -rf node_modules package-lock.json +npm install + +# Restart PM2 +pm2 restart luckychit-backend +``` + +**Prevention:** Always run `npm install` on the target server, never copy `node_modules/` from another OS. + +### App Crashes Immediately + +```bash +# Check logs +pm2 logs luckychit-backend --lines 100 + +# Common issues: +# - Missing .env file +# - Database connection failed +# - Port already in use +# - Missing dependencies +# - Native module platform mismatch (bcrypt, etc.) +``` + +### Database Connection Issues + +```bash +# Check PostgreSQL is running +sudo systemctl status postgresql + +# Check connection +psql -U your_db_user -d chitfund_prod + +# Check .env credentials +cat backend/.env +``` + +### Port Already in Use + +```bash +# Find process using port 3000 +lsof -i :3000 +# or +netstat -tulpn | grep 3000 + +# Kill process +kill -9 +``` + +### High Memory Usage + +```bash +# Check memory usage +pm2 monit + +# Reduce instances if needed +pm2 scale luckychit-backend 2 + +# Or increase memory limit in ecosystem.config.js +max_memory_restart: '2G' +``` + +### Zero-Downtime Deployment + +```bash +# Pull latest code +git pull origin main + +# Install dependencies +cd backend && npm install + +# Reload without downtime +pm2 reload luckychit-backend + +# Or use deployment command +pm2 deploy production update +``` + +### Reset Everything + +```bash +# Stop all PM2 processes +pm2 kill + +# Remove saved process list +pm2 save --force + +# Start fresh +cd backend +pm2 start ecosystem.config.js --env production +pm2 save +``` + +--- + +## Quick Reference Card + +```bash +# Start +pm2 start ecosystem.config.js --env production + +# Monitor +pm2 monit + +# Logs +pm2 logs + +# Restart +pm2 reload luckychit-backend + +# Status +pm2 list + +# Save +pm2 save + +# Startup +pm2 startup +``` + +--- + +## πŸ“Š Monitoring Dashboard (Optional) + +### PM2 Plus (Free for 1 server) + +```bash +# Register at https://pm2.io +pm2 plus +# Follow instructions to link +``` + +**Features:** +- Real-time monitoring +- Exception tracking +- Custom metrics +- Email alerts +- Transaction tracing + +--- + +## 🎯 Production Checklist + +Before going live: + +- [ ] `.env` configured with production credentials +- [ ] Database setup and migrated +- [ ] PM2 installed and configured +- [ ] Logs directory created +- [ ] App starts successfully with PM2 +- [ ] Auto-start on reboot configured (`pm2 startup` + `pm2 save`) +- [ ] nginx reverse proxy setup (optional but recommended) +- [ ] SSL certificate installed +- [ ] Database backups automated +- [ ] Monitoring setup (PM2 monit or PM2 Plus) +- [ ] Health check endpoint working +- [ ] Firewall configured +- [ ] Log rotation setup +- [ ] Test app functionality +- [ ] Load testing completed + +--- + +## πŸ†˜ Support + +**PM2 Documentation:** https://pm2.keymetrics.io/docs/ +**PM2 GitHub:** https://github.com/Unitech/pm2 + +--- + +## πŸ“ Example Production Workflow + +```bash +# Initial deployment +cd /var/www/luckychit/backend +pm2 start ecosystem.config.js --env production +pm2 save +pm2 startup + +# Updates (zero-downtime) +git pull origin main +npm install +pm2 reload luckychit-backend + +# Daily monitoring +pm2 monit # Check performance +pm2 logs --lines 50 # Check recent logs +``` + +--- + +**Your LuckyChit app is now production-ready with PM2! πŸš€** + +_For additional support, refer to the PM2 documentation or your DevOps team._ + diff --git a/PM2_QUICK_START.md b/PM2_QUICK_START.md new file mode 100644 index 0000000..6f47625 --- /dev/null +++ b/PM2_QUICK_START.md @@ -0,0 +1,180 @@ +# ⚑ PM2 Quick Start - LuckyChit + +Get your LuckyChit app running in production in 5 minutes! + +--- + +## πŸš€ Super Quick Deployment + +### 1. Install PM2 (if not installed) + +```bash +npm install -g pm2 +``` + +### 2. Setup Environment + +```bash +cd backend +cp .env.example .env +# Edit .env with production credentials +nano .env +``` + +### 3. Deploy with One Command + +```bash +cd backend +chmod +x deploy.sh +./deploy.sh production +``` + +**Done!** βœ… + +--- + +## πŸ“± What You Get + +- βœ… Backend running on port 3000 +- βœ… Auto-restart on crashes +- βœ… Load balanced across all CPU cores +- βœ… Daily scheduled restart at 3 AM +- βœ… Automated payment reminders (9 AM IST) +- βœ… Comprehensive logging + +--- + +## 🎯 Essential Commands + +```bash +# Status +pm2 list + +# Monitor +pm2 monit + +# Logs +pm2 logs luckychit-backend + +# Restart +pm2 restart luckychit-backend + +# Stop +pm2 stop luckychit-backend +``` + +--- + +## πŸ”„ Updates (Zero Downtime) + +```bash +git pull origin main +cd backend +npm install +pm2 reload luckychit-backend +``` + +--- + +## πŸ€– Auto-Start on Server Reboot + +**One-time setup:** + +```bash +pm2 startup +# Run the command it outputs (copy/paste it) + +pm2 save +``` + +Now your app automatically restarts after server reboot! + +--- + +## πŸ” Troubleshooting + +### ⚠️ bcrypt Error (Most Common) + +**Error:** `invalid ELF header` or `ERR_DLOPEN_FAILED` + +**Quick Fix (Run on Linux server):** + +```bash +cd backend +chmod +x fix-bcrypt.sh +./fix-bcrypt.sh +``` + +Or manually: +```bash +cd backend +rm -rf node_modules package-lock.json +npm install +pm2 restart luckychit-api +``` + +**Cause:** node_modules installed on Windows, deployed to Linux. Native modules must be rebuilt on the target OS. + +--- + +**App not starting?** + +```bash +pm2 logs luckychit-backend --lines 100 +``` + +**Database connection failed?** + +Check `.env` file has correct credentials: + +```bash +cat backend/.env +``` + +**Port already in use?** + +```bash +# Find what's using port 3000 +lsof -i :3000 + +# Kill it +kill -9 + +# Restart +pm2 restart luckychit-backend +``` + +**More help?** See `DEPLOYMENT_TROUBLESHOOTING.md` + +--- + +## πŸ“Š Monitoring URLs + +- **Backend Health Check:** `http://localhost:3000/api/health` (add this endpoint) +- **API Documentation:** `http://localhost:3000/api/docs` +- **Share Endpoint:** `http://localhost:3000/api/share` +- **Notifications:** `http://localhost:3000/api/notifications` + +--- + +## 🎯 Production Checklist + +- [ ] PM2 installed (`pm2 --version`) +- [ ] `.env` file configured +- [ ] Database running and accessible +- [ ] App started with PM2 (`pm2 list` shows running) +- [ ] Auto-start configured (`pm2 startup` + `pm2 save`) +- [ ] Test API endpoints +- [ ] Setup nginx reverse proxy (optional) +- [ ] Setup SSL certificate (recommended) + +--- + +## πŸ“š Need More Details? + +See the complete guide: `PM2_PRODUCTION_GUIDE.md` + +--- + +**Your LuckyChit backend is now running in production! πŸŽ‰** + diff --git a/PRODUCTION_UPDATE_GUIDE.md b/PRODUCTION_UPDATE_GUIDE.md new file mode 100644 index 0000000..1a4671a --- /dev/null +++ b/PRODUCTION_UPDATE_GUIDE.md @@ -0,0 +1,395 @@ +# πŸ”„ Production Update Quick Guide - LuckyChit + +Quick reference for updating backend and frontend in production. + +--- + +## 🎯 What Changed? + +- βœ… **Backend only?** β†’ Update Node.js backend +- βœ… **Frontend only?** β†’ Rebuild & redeploy Flutter app +- βœ… **Both?** β†’ Update backend first, then frontend + +--- + +## πŸ”§ Backend Updates (Node.js API) + +### Quick Update (Zero Downtime) + +```bash +# On production server +cd /home/luckychit/apps/chitfund/backend + +# Pull latest code +git pull origin main + +# Install dependencies (if package.json changed) +npm install + +# Reload with zero downtime +pm2 reload luckychit-api + +# Or use the deployment script +./deploy.sh production + +# Check status +pm2 logs luckychit-api --lines 50 +``` + +**Time:** ~30 seconds +**Downtime:** None (zero-downtime reload) + +--- + +## πŸ“± Frontend Updates (Flutter UI) + +### Option A: Web Deployment (Fastest) + +#### Step 1: Build on Your Machine + +```bash +# On your Windows dev machine +cd C:\Users\sunde\workspace\chitfund\luckychit + +# Build for production +flutter clean +flutter pub get +flutter build web --release +``` + +#### Step 2: Upload to Server + +```bash +# Option 1: Using SCP +scp -r build/web/* user@your-server:/var/www/luckychit/ + +# Option 2: Using the auto-deploy script (edit config first) +chmod +x deploy-web-auto.sh +./deploy-web-auto.sh + +# Option 3: Manual copy (if you have server access) +# Copy build/web/* to /var/www/luckychit/ on server +``` + +#### Step 3: Clear Cache (Important!) + +Users need to hard refresh their browser: +- **Chrome/Edge:** Ctrl + Shift + R +- **Firefox:** Ctrl + Shift + R +- **Mac:** Cmd + Shift + R + +**Time:** ~2-3 minutes +**Downtime:** None + +### Option B: Android App Update + +```bash +# On your machine +cd luckychit + +# Update version in pubspec.yaml first! +# version: 1.0.2+3 # Increment this + +# Build +chmod +x build-android.sh +./build-android.sh + +# Upload to Play Store or distribute APK +``` + +**Time:** ~5-10 minutes (build only) +**Downtime:** None + +--- + +## πŸš€ Complete Update Workflow (Both Backend + Frontend) + +### Step 1: Update Backend First + +```bash +# On production server +cd /home/luckychit/apps/chitfund/backend +git pull origin main +npm install +pm2 reload luckychit-api +``` + +### Step 2: Update Frontend + +```bash +# On your Windows machine +cd C:\Users\sunde\workspace\chitfund\luckychit +flutter clean +flutter pub get +flutter build web --release + +# Upload to server +scp -r build/web/* user@server:/var/www/luckychit/ +``` + +### Step 3: Verify Everything Works + +```bash +# Test backend API +curl http://your-server:3000/api/health + +# Test frontend (visit in browser) +# https://your-domain.com +# Hard refresh: Ctrl+Shift+R +``` + +--- + +## πŸ“‹ Quick Commands Cheat Sheet + +### Backend + +```bash +# Status +pm2 list + +# Logs +pm2 logs luckychit-api + +# Restart +pm2 restart luckychit-api + +# Reload (zero downtime) +pm2 reload luckychit-api + +# Monitor +pm2 monit +``` + +### Frontend (Web) + +```bash +# Build +cd luckychit +flutter build web --release + +# Deploy (local script) +./deploy-web.sh + +# Deploy (auto-upload to server) +./deploy-web-auto.sh +``` + +### Frontend (Android) + +```bash +# Build +cd luckychit +./build-android.sh + +# Output: +# - build/app/outputs/flutter-apk/app-release.apk +# - build/app/outputs/bundle/release/app-release.aab +``` + +--- + +## ⚑ Fast Updates (Development Mode) + +### Backend Hot Reload + +```bash +# On server, use nodemon for auto-restart on file changes +npm install -g nodemon +pm2 delete luckychit-api +pm2 start nodemon --name "luckychit-api" -- backend/server.js --watch +``` + +### Frontend Hot Reload + +```bash +# On your machine, run in dev mode +cd luckychit +flutter run -d web-server --web-port 8080 + +# Changes auto-reload in browser +``` + +--- + +## πŸ” Troubleshooting Updates + +### Backend Won't Update + +**Check if code actually changed:** +```bash +cd backend +git status +git log -1 +``` + +**PM2 not picking up changes:** +```bash +pm2 reload luckychit-api --update-env +# or +pm2 restart luckychit-api +``` + +**Native module issues (bcrypt):** +```bash +cd backend +./fix-bcrypt.sh +``` + +### Frontend Still Shows Old Version + +**Browser cache:** +- Hard refresh: Ctrl+Shift+R +- Or open in Incognito mode + +**Server cache:** +```bash +# Clear nginx cache (if using nginx) +sudo rm -rf /var/cache/nginx/* +sudo systemctl restart nginx +``` + +**Verify files updated:** +```bash +# On server +ls -lh /var/www/luckychit/ +# Check modification times +``` + +**Force rebuild:** +```bash +cd luckychit +flutter clean +rm -rf build/ +flutter pub get +flutter build web --release +``` + +--- + +## πŸ“Š Version Management + +### Check Current Versions + +**Backend:** +```bash +# Check package.json +cat backend/package.json | grep version + +# Or add to your API +# GET /api/version +``` + +**Frontend:** +```bash +# Check pubspec.yaml +cat luckychit/pubspec.yaml | grep version +``` + +### Update Versions + +**Backend (`package.json`):** +```json +{ + "name": "luckychit-backend", + "version": "1.0.2", + ... +} +``` + +**Frontend (`pubspec.yaml`):** +```yaml +version: 1.0.2+3 +# Format: major.minor.patch+buildNumber +``` + +--- + +## 🎯 Pre-Deployment Checklist + +### Before Updating Backend + +- [ ] Code tested locally +- [ ] Database migrations ready (if any) +- [ ] Environment variables updated (if needed) +- [ ] No breaking API changes (or frontend updated too) + +### Before Updating Frontend + +- [ ] Backend API compatible +- [ ] Version number incremented +- [ ] Tested locally with production backend +- [ ] Build completes without errors + +### After Updating + +- [ ] Backend: `pm2 logs` shows no errors +- [ ] Frontend: Hard refresh shows new UI +- [ ] Test critical features +- [ ] Check error logs +- [ ] Monitor for 10-15 minutes + +--- + +## 🚨 Emergency Rollback + +### Backend Rollback + +```bash +cd backend +git log --oneline -5 # See recent commits +git checkout +pm2 reload luckychit-api +``` + +### Frontend Rollback + +```bash +# On your machine +cd luckychit +git checkout +flutter build web --release +scp -r build/web/* user@server:/var/www/luckychit/ +``` + +--- + +## πŸ“ž Need Help? + +**Detailed Guides:** +- Backend: `PM2_PRODUCTION_GUIDE.md` +- Frontend: `FLUTTER_DEPLOYMENT_GUIDE.md` +- Troubleshooting: `DEPLOYMENT_TROUBLESHOOTING.md` + +**Quick Start:** +- PM2 Quick Start: `PM2_QUICK_START.md` + +--- + +## πŸ’‘ Pro Tips + +1. **Always update backend before frontend** (ensures API compatibility) + +2. **Test in staging first** if you have a staging server + +3. **Update during low traffic times** (early morning, late night) + +4. **Keep a deployment log:** + ```bash + echo "$(date): Updated to version 1.0.2" >> deployment.log + ``` + +5. **Monitor after deployment:** + ```bash + pm2 monit # Backend monitoring + # Watch error logs for 10-15 minutes + ``` + +6. **Communicate with users:** + - Add a banner: "Maintenance in progress" + - Or: "New version deployed, please refresh" + +--- + +**Remember: Backend β†’ Zero downtime | Frontend β†’ Hard refresh needed! 🎯** + diff --git a/backend/.gitignore b/backend/.gitignore index 7790482..5d57c02 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -144,7 +144,7 @@ build/ # PM2 process manager .pm2/ -ecosystem.config.js +# ecosystem.config.js should be committed (it's configuration, not secrets) # Docker volumes and data docker-data/ diff --git a/backend/deploy.sh b/backend/deploy.sh new file mode 100644 index 0000000..c8d8f68 --- /dev/null +++ b/backend/deploy.sh @@ -0,0 +1,65 @@ +#!/bin/bash + +# LuckyChit Backend Deployment Script +# Usage: ./deploy.sh [production|development] + +ENV=${1:-production} +APP_NAME="luckychit-backend" + +echo "πŸš€ Deploying LuckyChit Backend - Environment: $ENV" +echo "================================================" + +# Check if PM2 is installed +if ! command -v pm2 &> /dev/null; then + echo "❌ PM2 is not installed. Installing..." + npm install -g pm2 +fi + +# Clean install dependencies (fixes native module issues like bcrypt) +echo "πŸ“¦ Installing dependencies..." +echo " Cleaning old modules to rebuild native bindings..." +rm -rf node_modules package-lock.json +npm install --production + +# Create logs directory if it doesn't exist +if [ ! -d "logs" ]; then + echo "πŸ“ Creating logs directory..." + mkdir -p logs +fi + +# Check if .env file exists +if [ ! -f ".env" ]; then + echo "⚠️ Warning: .env file not found!" + echo "Please create .env file with production credentials" + echo "Example: cp .env.example .env" + exit 1 +fi + +# Stop existing PM2 process if running +if pm2 describe $APP_NAME > /dev/null 2>&1; then + echo "πŸ›‘ Stopping existing process..." + pm2 delete $APP_NAME +fi + +# Start application with PM2 +echo "🎯 Starting application with PM2..." +if [ "$ENV" == "production" ]; then + pm2 start ecosystem.config.js --env production +else + pm2 start ecosystem.config.js --env development +fi + +# Save PM2 process list +echo "πŸ’Ύ Saving PM2 process list..." +pm2 save + +# Show status +echo "" +echo "βœ… Deployment complete!" +echo "" +pm2 list +echo "" +echo "πŸ“Š Monitor with: pm2 monit" +echo "πŸ“ View logs with: pm2 logs $APP_NAME" +echo "" + diff --git a/backend/ecosystem.config.js b/backend/ecosystem.config.js new file mode 100644 index 0000000..4e1fde8 --- /dev/null +++ b/backend/ecosystem.config.js @@ -0,0 +1,49 @@ +module.exports = { + apps: [ + { + name: 'luckychit-backend', + script: './server.js', + instances: 'max', // Use all CPU cores + exec_mode: 'cluster', // Cluster mode for load balancing + autorestart: true, + watch: false, // Disable in production + max_memory_restart: '1G', + env: { + NODE_ENV: 'development', + PORT: 3000 + }, + env_production: { + NODE_ENV: 'production', + PORT: 3000 + }, + error_file: './logs/err.log', + out_file: './logs/out.log', + log_file: './logs/combined.log', + time: true, + merge_logs: true, + max_restarts: 10, + min_uptime: '10s', + listen_timeout: 3000, + kill_timeout: 5000, + // Cron restart (optional - restart daily at 3 AM) + cron_restart: '0 3 * * *', + // Enable source maps for better error tracking + node_args: '--enable-source-maps', + } + ], + + // Deployment configuration (optional) + deploy: { + production: { + user: 'your-server-user', + host: 'your-server-ip', + ref: 'origin/main', + repo: 'git@github.com:yourusername/chitfund.git', + path: '/var/www/luckychit', + 'pre-deploy-local': '', + 'post-deploy': 'cd backend && npm install && pm2 reload ecosystem.config.js --env production', + 'pre-setup': '' + } + } +}; + diff --git a/backend/fix-bcrypt.sh b/backend/fix-bcrypt.sh new file mode 100644 index 0000000..9f967fd --- /dev/null +++ b/backend/fix-bcrypt.sh @@ -0,0 +1,85 @@ +#!/bin/bash + +# Quick fix for bcrypt "invalid ELF header" error +# Run this on your Linux production server + +echo "πŸ”§ Fixing bcrypt native binding issue..." +echo "==========================================" +echo "" + +APP_NAME="luckychit-api" + +# Get current directory +BACKEND_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +cd "$BACKEND_DIR" + +echo "πŸ“ Working directory: $BACKEND_DIR" +echo "" + +# Stop PM2 if running +if pm2 describe $APP_NAME > /dev/null 2>&1; then + echo "⏸️ Stopping PM2 process: $APP_NAME" + pm2 stop $APP_NAME +else + echo "ℹ️ PM2 process not running" +fi +echo "" + +# Remove node_modules +if [ -d "node_modules" ]; then + echo "πŸ—‘οΈ Removing old node_modules..." + rm -rf node_modules +else + echo "ℹ️ node_modules not found (already clean)" +fi + +# Remove package-lock.json +if [ -f "package-lock.json" ]; then + echo "πŸ—‘οΈ Removing package-lock.json..." + rm -f package-lock.json +else + echo "ℹ️ package-lock.json not found" +fi +echo "" + +# Reinstall dependencies +echo "πŸ“¦ Reinstalling dependencies on Linux..." +echo " This will rebuild native bindings (bcrypt, etc.)" +echo "" +npm install +echo "" + +# Check if installation was successful +if [ $? -eq 0 ]; then + echo "βœ… Dependencies installed successfully!" + echo "" + + # Restart PM2 + if pm2 list | grep -q $APP_NAME; then + echo "πŸ”„ Restarting PM2 process..." + pm2 restart $APP_NAME + pm2 save + echo "" + + # Show status + echo "πŸ“Š Current status:" + pm2 list + echo "" + + echo "βœ… Fix complete! Your app should be running now." + echo "" + echo "πŸ“ Check logs with: pm2 logs $APP_NAME" + echo "πŸ“Š Monitor with: pm2 monit" + else + echo "⚠️ PM2 process not found. Start it manually:" + echo " pm2 start ecosystem.config.js --env production" + fi +else + echo "❌ Installation failed. Check the errors above." + exit 1 +fi + +echo "" +echo "==========================================" +echo "πŸŽ‰ Done!" + diff --git a/luckychit/build-android.sh b/luckychit/build-android.sh new file mode 100644 index 0000000..3bfd95d --- /dev/null +++ b/luckychit/build-android.sh @@ -0,0 +1,90 @@ +#!/bin/bash + +# LuckyChit Android Build Script +# Builds both APK and App Bundle for distribution + +echo "πŸ€– Building Android Release" +echo "============================" +echo "" + +# Check if we're in the right directory +if [ ! -f "pubspec.yaml" ]; then + echo "❌ Error: pubspec.yaml not found!" + echo "Please run this script from the luckychit directory" + exit 1 +fi + +# Get current version +VERSION=$(grep "^version:" pubspec.yaml | sed 's/version: //') +echo "πŸ“± App Version: $VERSION" +echo "" + +# Clean +echo "🧹 Step 1/4: Cleaning..." +flutter clean + +# Get dependencies +echo "πŸ“¦ Step 2/4: Getting dependencies..." +flutter pub get + +# Build APK +echo "πŸ”¨ Step 3/4: Building APK (for direct distribution)..." +flutter build apk --release + +if [ $? -ne 0 ]; then + echo "❌ APK build failed!" + exit 1 +fi + +echo "βœ… APK build successful!" +echo "" + +# Build App Bundle +echo "πŸ”¨ Step 4/4: Building App Bundle (for Play Store)..." +flutter build appbundle --release + +if [ $? -ne 0 ]; then + echo "❌ App Bundle build failed!" + exit 1 +fi + +echo "βœ… App Bundle build successful!" +echo "" + +# Show results +echo "===========================================" +echo "πŸŽ‰ Build Complete!" +echo "" +echo "πŸ“¦ Output Files:" +echo "" +echo " APK (Direct Distribution):" +echo " πŸ“„ build/app/outputs/flutter-apk/app-release.apk" +APK_SIZE=$(du -h build/app/outputs/flutter-apk/app-release.apk | cut -f1) +echo " πŸ“Š Size: $APK_SIZE" +echo "" +echo " App Bundle (Google Play Store):" +echo " πŸ“„ build/app/outputs/bundle/release/app-release.aab" +AAB_SIZE=$(du -h build/app/outputs/bundle/release/app-release.aab | cut -f1) +echo " πŸ“Š Size: $AAB_SIZE" +echo "" +echo "πŸ“€ Next Steps:" +echo "" +echo " For Direct Distribution (APK):" +echo " 1. Upload APK to your server or file host" +echo " 2. Share download link with users" +echo " 3. Users enable 'Install from Unknown Sources'" +echo " 4. Users download and install" +echo "" +echo " For Google Play Store (AAB):" +echo " 1. Go to https://play.google.com/console" +echo " 2. Select your app" +echo " 3. Go to Release β†’ Production" +echo " 4. Create new release" +echo " 5. Upload app-release.aab" +echo " 6. Add release notes" +echo " 7. Review and roll out" +echo "" +echo "πŸ“‹ Version: $VERSION" +echo " Update version in pubspec.yaml for next release" +echo "" + diff --git a/luckychit/deploy-web-auto.sh b/luckychit/deploy-web-auto.sh new file mode 100644 index 0000000..6126038 --- /dev/null +++ b/luckychit/deploy-web-auto.sh @@ -0,0 +1,111 @@ +#!/bin/bash + +# LuckyChit Flutter Web - Automated Full Deployment +# This script builds AND deploys to production server + +# ============================================ +# CONFIGURATION - UPDATE THESE VALUES +# ============================================ + +# Server Configuration +SERVER_USER="luckychit" # Your server username +SERVER_HOST="your-server-ip" # Your server IP or domain +WEB_DIR="/var/www/luckychit" # Web directory on server +USE_PM2=false # Set to true if using PM2 instead of nginx +PM2_APP_NAME="luckychit-web" # PM2 app name (if using PM2) + +# ============================================ +# DEPLOYMENT SCRIPT - DO NOT EDIT BELOW +# ============================================ + +echo "πŸš€ LuckyChit Flutter Web - Auto Deployment" +echo "===========================================" +echo "" +echo "πŸ“‹ Configuration:" +echo " Server: $SERVER_USER@$SERVER_HOST" +echo " Target: $WEB_DIR" +echo " Method: $([ "$USE_PM2" = true ] && echo 'PM2' || echo 'nginx')" +echo "" + +# Check if we're in the right directory +if [ ! -f "pubspec.yaml" ]; then + echo "❌ Error: pubspec.yaml not found!" + echo "Please run this script from the luckychit directory" + exit 1 +fi + +# Clean and build +echo "🧹 Step 1/4: Cleaning..." +flutter clean + +echo "πŸ“¦ Step 2/4: Getting dependencies..." +flutter pub get + +echo "πŸ”¨ Step 3/4: Building for web..." +flutter build web --release + +if [ $? -ne 0 ]; then + echo "❌ Build failed!" + exit 1 +fi + +echo "βœ… Build successful!" +echo "" + +# Deploy to server +echo "πŸ“€ Step 4/4: Deploying to production server..." +echo "" + +if command -v rsync &> /dev/null; then + # Use rsync (faster, incremental) + echo "Using rsync for deployment..." + rsync -avz --delete build/web/ $SERVER_USER@$SERVER_HOST:$WEB_DIR/ +else + # Fallback to scp + echo "Using scp for deployment..." + scp -r build/web/* $SERVER_USER@$SERVER_HOST:$WEB_DIR/ +fi + +if [ $? -ne 0 ]; then + echo "❌ Deployment failed!" + echo "Please check:" + echo " - Server credentials are correct" + echo " - You have SSH access to the server" + echo " - Target directory exists and has write permissions" + exit 1 +fi + +echo "" +echo "βœ… Files uploaded successfully!" + +# Restart service if using PM2 +if [ "$USE_PM2" = true ]; then + echo "" + echo "πŸ”„ Restarting PM2 service..." + ssh $SERVER_USER@$SERVER_HOST "pm2 restart $PM2_APP_NAME" + + if [ $? -eq 0 ]; then + echo "βœ… PM2 restarted successfully!" + else + echo "⚠️ PM2 restart failed - you may need to restart manually" + fi +fi + +echo "" +echo "==========================================" +echo "πŸŽ‰ Deployment Complete!" +echo "" +echo "🌐 Your app should now be live with the latest changes" +echo "" +echo "πŸ“ Important:" +echo " - Users may need to clear browser cache (Ctrl+Shift+R)" +echo " - Test the app in an incognito window first" +echo "" +echo "πŸ” Monitor logs:" +if [ "$USE_PM2" = true ]; then + echo " ssh $SERVER_USER@$SERVER_HOST 'pm2 logs $PM2_APP_NAME'" +else + echo " ssh $SERVER_USER@$SERVER_HOST 'sudo tail -f /var/log/nginx/error.log'" +fi +echo "" + diff --git a/luckychit/deploy-web.sh b/luckychit/deploy-web.sh new file mode 100644 index 0000000..38dc5c2 --- /dev/null +++ b/luckychit/deploy-web.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +# LuckyChit Flutter Web Deployment Script +# Quick script to rebuild and deploy web changes + +echo "πŸš€ Deploying Flutter Web Updates" +echo "=================================" +echo "" + +# Check if we're in the right directory +if [ ! -f "pubspec.yaml" ]; then + echo "❌ Error: pubspec.yaml not found!" + echo "Please run this script from the luckychit directory" + exit 1 +fi + +# Clean previous build +echo "🧹 Cleaning previous build..." +flutter clean + +# Get dependencies +echo "πŸ“¦ Getting dependencies..." +flutter pub get + +# Build for production +echo "πŸ”¨ Building for web (production mode)..." +echo " This may take a few minutes..." +flutter build web --release + +# Check if build was successful +if [ $? -eq 0 ]; then + echo "" + echo "βœ… Build successful!" + echo "" + echo "πŸ“ Build output location: build/web/" + echo "" + echo "πŸ“€ Next steps to deploy:" + echo "" + echo "Option 1 - nginx (Recommended):" + echo " sudo cp -r build/web/* /var/www/luckychit/" + echo " sudo systemctl restart nginx" + echo "" + echo "Option 2 - PM2 with Express:" + echo " pm2 restart luckychit-web" + echo "" + echo "Option 3 - Upload to server:" + echo " scp -r build/web/* user@server:/var/www/luckychit/" + echo "" + echo "πŸ’‘ Tip: Users may need to clear browser cache (Ctrl+Shift+R)" +else + echo "" + echo "❌ Build failed! Please check the errors above." + exit 1 +fi + diff --git a/luckychit/ecosystem.config.js b/luckychit/ecosystem.config.js new file mode 100644 index 0000000..8393901 --- /dev/null +++ b/luckychit/ecosystem.config.js @@ -0,0 +1,27 @@ +module.exports = { + apps: [ + { + name: 'luckychit-web', + script: './web-server.js', + instances: 2, // Run 2 instances for load balancing + exec_mode: 'cluster', + autorestart: true, + watch: false, // Set to true for development + max_memory_restart: '500M', + env: { + NODE_ENV: 'development', + PORT: 8080 + }, + env_production: { + NODE_ENV: 'production', + PORT: 8080 + }, + error_file: './logs/web-err.log', + out_file: './logs/web-out.log', + log_file: './logs/web-combined.log', + time: true, + merge_logs: true + } + ] +}; + diff --git a/luckychit/lib/core/themes/app_theme.dart b/luckychit/lib/core/themes/app_theme.dart index b27de99..c9f2f2b 100644 --- a/luckychit/lib/core/themes/app_theme.dart +++ b/luckychit/lib/core/themes/app_theme.dart @@ -60,7 +60,7 @@ class AppTheme { ), // Card Theme - cardTheme: CardThemeData( + cardTheme: CardTheme( elevation: 2, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16.r), @@ -183,11 +183,11 @@ class AppTheme { ), // Dialog Theme - dialogTheme: DialogThemeData( + dialogTheme: DialogTheme( + elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16.r), ), - elevation: 4, ), // Snackbar Theme @@ -241,7 +241,7 @@ class AppTheme { ), // Card Theme - cardTheme: CardThemeData( + cardTheme: CardTheme( elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16.r), @@ -364,12 +364,12 @@ class AppTheme { ), // Dialog Theme - dialogTheme: DialogThemeData( + dialogTheme: DialogTheme( backgroundColor: darkSurface, + elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16.r), ), - elevation: 4, ), // Snackbar Theme diff --git a/luckychit/web-server.js b/luckychit/web-server.js new file mode 100644 index 0000000..e12496b --- /dev/null +++ b/luckychit/web-server.js @@ -0,0 +1,83 @@ +/** + * LuckyChit Web Server + * Express server to serve Flutter web build with proper caching + * + * Usage: + * node web-server.js + * Or with PM2: + * pm2 start web-server.js --name "luckychit-web" + */ + +const express = require('express'); +const path = require('path'); +const fs = require('fs'); + +const app = express(); +const PORT = process.env.PORT || 8080; +const BUILD_DIR = path.join(__dirname, 'build/web'); + +// Check if build directory exists +if (!fs.existsSync(BUILD_DIR)) { + console.error('❌ Error: build/web directory not found!'); + console.error(' Please run: flutter build web --release'); + process.exit(1); +} + +// Security headers +app.use((req, res, next) => { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('X-Frame-Options', 'SAMEORIGIN'); + res.setHeader('X-XSS-Protection', '1; mode=block'); + next(); +}); + +// Serve static files with caching strategy +app.use(express.static(BUILD_DIR, { + maxAge: '1y', // Cache static assets for 1 year + immutable: true, + setHeaders: (res, filePath) => { + // Don't cache HTML files (always serve fresh) + if (filePath.endsWith('.html')) { + res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); + res.setHeader('Pragma', 'no-cache'); + res.setHeader('Expires', '0'); + } + } +})); + +// Handle Flutter routes (SPA - Single Page Application) +// Any route not found as a static file should serve index.html +app.get('*', (req, res) => { + res.sendFile(path.join(BUILD_DIR, 'index.html')); +}); + +// Error handling +app.use((err, req, res, next) => { + console.error('Error:', err); + res.status(500).send('Internal Server Error'); +}); + +// Start server +app.listen(PORT, '0.0.0.0', () => { + console.log(''); + console.log('βœ… LuckyChit Flutter Web App'); + console.log('============================'); + console.log(`🌐 Running on: http://localhost:${PORT}`); + console.log(`πŸ“ Serving: ${BUILD_DIR}`); + console.log(''); + console.log('πŸ“ Logs:'); + console.log(' Access: http://localhost:' + PORT); + console.log(''); +}); + +// Graceful shutdown +process.on('SIGTERM', () => { + console.log('SIGTERM received, shutting down gracefully...'); + process.exit(0); +}); + +process.on('SIGINT', () => { + console.log('SIGINT received, shutting down gracefully...'); + process.exit(0); +}); +