# How to Delete All Loans for Manual Re-entry

## ⚠️ CRITICAL WARNING

This script will **PERMANENTLY DELETE ALL LOAN DATA**. This cannot be undone!

---

## What Gets Deleted

### ❌ Will Be 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 SasaPay transactions
- All receipts
- All loan statements
- All SMS logs
- All unconfirmed payments
- All accounting entries related to loans

### ✅ Will Be PRESERVED:
- All users/clients (borrowers)
- All expenses
- All loan products
- All branches
- System settings
- Chart of accounts
- Non-loan accounting entries

---

## Before Running

### 1. BACKUP YOUR DATABASE! 🚨

**THIS IS MANDATORY!**

```bash
# On production server
mysqldump -u root -p grazuri_database > backup_before_delete_$(date +%Y%m%d_%H%M%S).sql

# Verify backup was created
ls -lh backup_before_delete_*.sql
```

### 2. Verify Backup Works

```bash
# Test restore on a copy (optional but recommended)
mysql -u root -p test_database < backup_before_delete_YYYYMMDD_HHMMSS.sql
```

### 3. Inform Your Team

- ✅ Notify all staff that data will be deleted
- ✅ Make sure no one is entering loans during deletion
- ✅ Schedule a maintenance window

---

## How to Run

### Step 1: Open the Script

```bash
nano delete_all_loans_for_manual_entry.py
```

### Step 2: Verify Confirmation Code

Find this line in the script:
```python
ENTERED_CODE = "DELETE_ALL_LOANS_NOW_2026"
```

Make sure it matches:
```python
CONFIRMATION_CODE = "DELETE_ALL_LOANS_NOW_2026"
```

If they match, the script will run. If not, it will refuse to delete anything.

### Step 3: Run the Script

```bash
cd /path/to/grazuri
python delete_all_loans_for_manual_entry.py
```

### Step 4: What You'll See

```
================================================================================
 DELETE ALL LOANS FOR MANUAL RE-ENTRY
 ==============================================================================
 This script will permanently delete ALL loan data
================================================================================

⚠️  CRITICAL WARNING ⚠️

This script will DELETE ALL LOANS AND LOAN-RELATED DATA!

What will be DELETED:
  ❌ All loans
  ❌ All loan applications
  ❌ All repayments
  ...

What will be PRESERVED:
  ✅ All clients/users
  ✅ All expenses
  ...

================================================================================
 CONFIRMATION CHECK
================================================================================
✅ Confirmation code verified

================================================================================
 CURRENT DATABASE COUNTS
================================================================================
  ❌ Loans                                              123
  ❌ Loan Applications                                  145
  ❌ Repayments                                         567
  ...
  ✅ Users/Clients (WILL BE PRESERVED)                  234
  ✅ Expenses (WILL BE PRESERVED)                        89

================================================================================
 FINAL WARNING
================================================================================

The script will now DELETE ALL LOAN DATA in 3 seconds...

Press Ctrl+C NOW to cancel!
  Deleting in 3...
  Deleting in 2...
  Deleting in 1...

================================================================================
 DELETING ALL LOAN DATA
================================================================================

🔓 Disabling foreign key checks...

1️⃣  Deleting accounting journal entries...
   Deleted 456 accounting entries

2️⃣  Deleting SMS logs...
   Deleted 1,234 SMS logs

...

✅ All loan data deleted successfully!

================================================================================
 DELETION SUMMARY
================================================================================

Records deleted:
  ❌ accounting_entries                                    456
  ❌ sms_logs                                            1,234
  ❌ receipts                                              567
  ...

TOTAL RECORDS DELETED                                    5,678

================================================================================
 VERIFICATION
================================================================================
  ✅ loans                                                   0 records
  ✅ loan_applications                                       0 records
  ✅ repayments                                              0 records
  ...
  ✅ Users preserved                                       234 records
  ✅ Expenses preserved                                     89 records

✅ All loan data successfully deleted!
✅ Clients and expenses preserved!

================================================================================
 ✅ DELETION COMPLETE
================================================================================

✅ All loan data has been deleted!
✅ Database is ready for manual loan entry!

Next steps:
  1. Admin can now manually enter loans from scratch
  2. All clients are preserved and ready to use
  3. Loan products are still available
  4. Start creating loans in the system!

📄 Deletion log saved to: loans_deleted_20261111_203045.txt
```

---

## After Running

### 1. Verify Deletion

Check the database:
```sql
-- Check loans table
SELECT COUNT(*) FROM loans;
-- Should return: 0

-- Check clients still exist
SELECT COUNT(*) FROM users WHERE role='borrower';
-- Should return: same number as before

-- Check expenses still exist
SELECT COUNT(*) FROM expenses;
-- Should return: same number as before
```

### 2. Test the System

- ✅ Login to the admin panel
- ✅ Go to clients page - verify clients are there
- ✅ Go to loans page - verify it's empty
- ✅ Try creating a new loan
- ✅ Verify loan products still exist

### 3. Start Manual Entry

Now the admin can manually enter all loans from the beginning!

---

## If Something Goes Wrong

### Cancel Before It Runs

Press **Ctrl+C** during the 3-second countdown.

### Restore from Backup

If you need to restore:

```bash
# Stop the application
sudo systemctl stop gunicorn

# Restore database
mysql -u root -p grazuri_database < backup_before_delete_YYYYMMDD_HHMMSS.sql

# Restart application
sudo systemctl start gunicorn
```

---

## Security

The script has safety features:

1. ✅ **Confirmation code** - Must match exactly
2. ✅ **Database transaction** - All-or-nothing deletion
3. ✅ **Verification** - Checks what was deleted
4. ✅ **Preservation** - Users and expenses untouched
5. ✅ **Logging** - Creates deletion log file

---

## What Happens to Loan Numbers?

After deletion, new loans will start fresh with new numbers:

**Before deletion:**
- Loans exist: 11112026-000001, 11112026-000002, etc.

**After deletion:**
- All deleted
- Next loan created: Will get next available number
- Fresh start!

---

## FAQ

**Q: Can this be undone?**  
A: No! That's why you MUST backup first.

**Q: Will clients be deleted?**  
A: No! All clients/users are preserved.

**Q: Will expenses be deleted?**  
A: No! All expenses are preserved.

**Q: How long does it take?**  
A: Usually 30-60 seconds depending on data volume.

**Q: Can I run this on production?**  
A: Yes, but make sure you have a backup and inform your team first.

**Q: What if I only want to delete some loans?**  
A: This script deletes ALL loans. For selective deletion, use the admin panel.

---

## Checklist

Before running:
- [ ] Database backup created
- [ ] Backup verified
- [ ] Team informed
- [ ] Confirmation code set correctly
- [ ] Ready to delete ALL loans

After running:
- [ ] Deletion completed successfully
- [ ] Verification passed
- [ ] Clients still exist
- [ ] Expenses still exist
- [ ] Test loan creation works
- [ ] Ready for manual entry

---

## Summary

**Purpose:** Delete ALL loans to allow manual re-entry from scratch  
**Safety:** Confirmation code required  
**Backup:** MANDATORY before running  
**Preserves:** Clients, expenses, products, settings  
**Deletes:** Everything loan-related  
**Time:** ~1 minute  
**Reversible:** No (backup required)  

---

**Ready to proceed? Make sure you have that backup! 🚨**
