# Backend Troubleshooting Guide

Quick solutions for common backend issues.

---

## 🔧 Module Not Found Error

**Error**: `Cannot find module ...`

**Fix**:
```bash
cd backend
npm install
pm2 restart chitfund-backend
```

---

## 🔐 PostgreSQL Authentication Issues

**Error**: `Peer authentication failed`

**Solution 1** (Easiest):
```bash
sudo -u postgres psql
```

**Solution 2**: Change auth method
```bash
sudo nano /etc/postgresql/*/main/pg_hba.conf
# Change: local all all peer
# To:     local all all md5
sudo systemctl restart postgresql
```

---

## 💾 Database Migration

### Apply Member Number Migration

**Option A** (Recommended):
```bash
node run-member-number-migration.js
```

**Option B**:
```bash
sudo cp migrations/20251106_add_member_number.sql /tmp/
sudo -u postgres psql -d luckychit -f /tmp/20251106_add_member_number.sql
```

---

## 🚫 Delete Group Issues

**Error**: "Cannot delete, has members"

**Cause**: Counting removed members

**Fix**: Already fixed! Just restart backend:
```bash
pm2 restart chitfund-backend
```

Now only counts active members.

---

## 🚫 Remove Member 404 Error

**Error**: 404 "Member not found in this group"

**Cause**: Using wrong ID

**Fix**: Use `member.userId` not `member.id`
```dart
// Correct
removeMemberFromGroup(groupId, member.userId);
```

---

## 🔌 Connection Issues

**Can't connect to database**:
```bash
# Check PostgreSQL is running
sudo systemctl status postgresql

# Start if stopped
sudo systemctl start postgresql

# Test connection
node test-db-connection.js
```

---

## 📊 Check Backend Status

```bash
# PM2 status
pm2 status

# View logs
pm2 logs chitfund-backend --lines 50

# Restart
pm2 restart chitfund-backend

# Stop
pm2 stop chitfund-backend

# Delete and restart fresh
pm2 delete chitfund-backend
pm2 start ecosystem.config.js
```

---

## 🔍 Verify Migration Applied

```bash
sudo -u postgres psql -d luckychit -c "SELECT member_number FROM group_members LIMIT 5;"
```

Should show numbers 1, 2, 3, etc.

---

## 🆘 Complete Reset

If everything is broken:

```bash
cd backend

# Stop backend
pm2 delete all

# Clean install
rm -rf node_modules package-lock.json
npm install

# Run migrations
node run-member-number-migration.js

# Start fresh
pm2 start ecosystem.config.js
pm2 save
```

---

## 📞 Still Having Issues?

Check:
1. PostgreSQL is running: `sudo systemctl status postgresql`
2. Database exists: `sudo -u postgres psql -l`
3. .env file is configured correctly
4. Port 3000 is not in use: `lsof -i :3000`
5. Node version is 14+: `node --version`

---

**Most issues are fixed by**: `npm install && pm2 restart chitfund-backend` 🚀

