# Database Deletion Scripts Guide

This guide documents the two deletion scripts created for cleaning up the Grazuri system.

---

## 📋 Available Scripts

### 1. `delete_all_loans_direct.py`
**Purpose:** Delete all loans and loan-related data while preserving users/clients

### 2. `delete_all_borrowers.py`
**Purpose:** Delete all users/borrowers from the system

---

## Script 1: Delete All Loans

### File: `delete_all_loans_direct.py`

### What Gets Deleted:
- ❌ All loans
- ❌ All loan applications
- ❌ All repayments
- ❌ All loan disbursements
- ❌ All loan fees
- ❌ All loan guarantors
- ❌ All loan statuses
- ❌ All rollover requests
- ❌ All M-Pesa transactions
- ❌ All receipts
- ❌ All loan statements
- ❌ All SMS logs
- ❌ All SasaPay transactions (if table exists)
- ❌ All unconfirmed payments
- ❌ All accounting entries for loans (if table exists)

### What Gets Preserved:
- ✅ All users/clients (borrowers)
- ✅ All expenses
- ✅ All loan products
- ✅ All branches
- ✅ System settings
- ✅ Chart of accounts

### How to Run:

```bash
# 1. Make sure you have a backup
mysqldump -u xygbfpsg_graz -p xygbfpsg_loans > backup_$(date +%Y%m%d_%H%M%S).sql

# 2. Run the script
python delete_all_loans_direct.py

# 3. Verify confirmation code matches
# The script will show a 3-second countdown before deletion
```

### When to Use:
- When you need to clean up loan data but keep all borrowers
- When starting fresh with loan entry but preserving client information
- When fixing data issues that require complete loan reset

---

## Script 2: Delete All Borrowers

### File: `delete_all_borrowers.py`

### What Gets Deleted:
- ❌ All users (borrowers)
- ❌ All staff users
- ❌ All admin users
- ❌ All authentication tokens
- ❌ All user sessions
- ❌ All user permissions
- ❌ All user group memberships

### What Gets Preserved:
- ✅ Loans (if you haven't deleted them)
- ✅ Expenses
- ✅ Products
- ✅ Branches
- ✅ System settings

### How to Run:

```bash
# 1. Make sure you have a backup
mysqldump -u xygbfpsg_graz -p xygbfpsg_loans > backup_users_$(date +%Y%m%d_%H%M%S).sql

# 2. Run the script
python delete_all_borrowers.py

# 3. Verify confirmation code matches
# The script will show a 5-second countdown before deletion

# 4. IMMEDIATELY create a new admin user
python manage.py createsuperuser
```

### ⚠️ CRITICAL WARNING:
**You will lose ALL access to the system!**

After running this script, you MUST immediately create a new admin user or you won't be able to log in.

### When to Use:
- When starting completely fresh with new borrowers
- When combining with loan deletion for a complete system reset
- When migrating to a new user structure

---

## 🔄 Common Workflows

### Workflow 1: Complete System Reset
**Goal:** Delete everything and start fresh

```bash
# Step 1: Backup everything
mysqldump -u xygbfpsg_graz -p xygbfpsg_loans > full_backup_$(date +%Y%m%d_%H%M%S).sql

# Step 2: Delete all loans first
python delete_all_loans_direct.py

# Step 3: Delete all borrowers
python delete_all_borrowers.py

# Step 4: Create new admin
python manage.py createsuperuser

# Step 5: Start adding borrowers and loans manually
```

### Workflow 2: Keep Borrowers, Reset Loans
**Goal:** Fix loan data issues while keeping client information

```bash
# Step 1: Backup
mysqldump -u xygbfpsg_graz -p xygbfpsg_loans > loans_backup_$(date +%Y%m%d_%H%M%S).sql

# Step 2: Delete loans only
python delete_all_loans_direct.py

# Step 3: Manually re-enter loans with correct data
# Borrowers are still in the system, just add new loans
```

### Workflow 3: Reset Users Only
**Goal:** Clean up user accounts but keep loan history

```bash
# Step 1: Backup
mysqldump -u xygbfpsg_graz -p xygbfpsg_loans > users_backup_$(date +%Y%m%d_%H%M%S).sql

# Step 2: Delete all users
python delete_all_borrowers.py

# Step 3: Create admin immediately
python manage.py createsuperuser

# Step 4: Re-add borrowers
# Note: Existing loans will be orphaned without users
```

---

## 🔒 Safety Features

Both scripts include:

1. **Hardcoded Confirmation Code**
   - Must match exactly to run
   - Prevents accidental execution

2. **Countdown Timer**
   - 3 seconds for loans
   - 5 seconds for borrowers
   - Press Ctrl+C to cancel

3. **Transaction Support**
   - All-or-nothing deletion
   - Automatic rollback on error

4. **Current Data Display**
   - Shows what will be deleted before proceeding
   - Lists row counts for each table

5. **Graceful Error Handling**
   - Skips tables that don't exist
   - Logs all errors clearly

---

## 🗄️ Database Connection

Both scripts use direct PyMySQL connection:

```python
DB = dict(
    host='localhost',
    port=3306,
    database='xygbfpsg_loans',
    user='xygbfpsg_graz',
    password='j.ez-xy6##y.rllB',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)
```

**No Django dependency required** - these scripts work standalone.

---

## 📊 Verification After Deletion

### Verify Loan Deletion:
```sql
-- Check if loans are gone
SELECT COUNT(*) FROM loans;  -- Should be 0

-- Check if borrowers remain (if you used delete_all_loans_direct.py)
SELECT COUNT(*) FROM users;  -- Should be > 0
```

### Verify Borrower Deletion:
```sql
-- Check if users are gone
SELECT COUNT(*) FROM users;  -- Should be 0

-- Check if you can log in
-- Try logging in at: https://grazuri.uzuriapps.xyz/accounts/login/
-- Should fail until you create a new admin
```

---

## 🔧 Troubleshooting

### Script Won't Run - Confirmation Error

**Problem:**
```
❌ ERROR: Confirmation code does not match!
```

**Solution:**
Edit the script and make sure `ENTERED_CODE` matches `CONFIRMATION_CODE`:

```python
CONFIRMATION_CODE = "DELETE_ALL_LOANS_NOW_2026"
ENTERED_CODE = "DELETE_ALL_LOANS_NOW_2026"  # ← Must match exactly
```

### Database Connection Failed

**Problem:**
```
❌ Failed to connect to database: Access denied
```

**Solution:**
1. Verify database credentials in the script
2. Check if MySQL server is running
3. Verify user has correct permissions

### Table Doesn't Exist

**Problem:**
```
⚠️  Table 'sasapay_transactions' doesn't exist - skipping
```

**Solution:**
This is normal! The script automatically skips tables that don't exist. No action needed.

### Can't Log In After Deleting Borrowers

**Problem:**
```
Invalid credentials
```

**Solution:**
You deleted all users including admins. Create a new superuser:

```bash
python manage.py createsuperuser
```

---

## 🎯 Best Practices

1. **Always backup before running**
   ```bash
   mysqldump -u xygbfpsg_graz -p xygbfpsg_loans > backup.sql
   ```

2. **Test on localhost first**
   - Run scripts on development environment
   - Verify behavior before production use

3. **Run during off-hours**
   - Avoid running during business hours
   - Prevent user disruption

4. **Document what you delete**
   - Keep track of when and why you deleted data
   - Note in your change log

5. **Verify after deletion**
   - Check the website to confirm data is gone
   - Test creating new records

---

## 📞 Support

If you encounter issues:

1. Check this guide first
2. Review script output for error messages
3. Check database logs
4. Verify backup was created successfully

---

## 📝 Change Log

| Date | Action | Script Used | Reason |
|------|--------|-------------|--------|
| 2026-11-11 | Scripts created | Both | Initial creation for data cleanup |
| - | - | - | Document future deletions here |

---

**Created:** November 11, 2026  
**Purpose:** Data cleanup and system reset during loan number format migration  
**Status:** Ready for production use
