200 lines
7.5 KiB
Python
200 lines
7.5 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Script to clean up all test data from the Product Tracker application.
|
|
This will delete all shopping events, products, and shops.
|
|
"""
|
|
|
|
import requests
|
|
import json
|
|
from typing import List, Dict, Any
|
|
|
|
BASE_URL = "http://localhost:8000"
|
|
|
|
def delete_all_shopping_events() -> int:
|
|
"""Delete all shopping events and return the count of deleted events."""
|
|
print("🛒 Deleting all shopping events...")
|
|
|
|
try:
|
|
# Get all shopping events
|
|
response = requests.get(f"{BASE_URL}/shopping-events/")
|
|
if response.status_code != 200:
|
|
print(f" ❌ Failed to fetch shopping events: {response.status_code}")
|
|
return 0
|
|
|
|
events = response.json()
|
|
deleted_count = 0
|
|
|
|
for event in events:
|
|
try:
|
|
delete_response = requests.delete(f"{BASE_URL}/shopping-events/{event['id']}")
|
|
if delete_response.status_code == 200:
|
|
deleted_count += 1
|
|
print(f" ✅ Deleted event #{event['id']} from {event['shop']['name']}")
|
|
else:
|
|
print(f" ❌ Failed to delete event #{event['id']}: {delete_response.status_code}")
|
|
except Exception as e:
|
|
print(f" ❌ Error deleting event #{event['id']}: {e}")
|
|
|
|
print(f" 📊 Deleted {deleted_count} shopping events total\n")
|
|
return deleted_count
|
|
|
|
except Exception as e:
|
|
print(f" ❌ Error fetching shopping events: {e}")
|
|
return 0
|
|
|
|
def delete_all_products() -> int:
|
|
"""Delete all products and return the count of deleted products."""
|
|
print("🥬 Deleting all products...")
|
|
|
|
try:
|
|
# Get all products
|
|
response = requests.get(f"{BASE_URL}/products/")
|
|
if response.status_code != 200:
|
|
print(f" ❌ Failed to fetch products: {response.status_code}")
|
|
return 0
|
|
|
|
products = response.json()
|
|
deleted_count = 0
|
|
|
|
for product in products:
|
|
try:
|
|
delete_response = requests.delete(f"{BASE_URL}/products/{product['id']}")
|
|
if delete_response.status_code == 200:
|
|
deleted_count += 1
|
|
organic_label = "🌱" if product['organic'] else "🌾"
|
|
print(f" ✅ Deleted product: {organic_label} {product['name']}")
|
|
else:
|
|
print(f" ❌ Failed to delete product {product['name']}: {delete_response.status_code}")
|
|
except Exception as e:
|
|
print(f" ❌ Error deleting product {product['name']}: {e}")
|
|
|
|
print(f" 📊 Deleted {deleted_count} products total\n")
|
|
return deleted_count
|
|
|
|
except Exception as e:
|
|
print(f" ❌ Error fetching products: {e}")
|
|
return 0
|
|
|
|
def delete_all_shops() -> int:
|
|
"""Delete all shops and return the count of deleted shops."""
|
|
print("🏪 Deleting all shops...")
|
|
|
|
try:
|
|
# Get all shops
|
|
response = requests.get(f"{BASE_URL}/shops/")
|
|
if response.status_code != 200:
|
|
print(f" ❌ Failed to fetch shops: {response.status_code}")
|
|
return 0
|
|
|
|
shops = response.json()
|
|
deleted_count = 0
|
|
|
|
for shop in shops:
|
|
try:
|
|
delete_response = requests.delete(f"{BASE_URL}/shops/{shop['id']}")
|
|
if delete_response.status_code == 200:
|
|
deleted_count += 1
|
|
print(f" ✅ Deleted shop: {shop['name']} ({shop['city']})")
|
|
else:
|
|
print(f" ❌ Failed to delete shop {shop['name']}: {delete_response.status_code}")
|
|
except Exception as e:
|
|
print(f" ❌ Error deleting shop {shop['name']}: {e}")
|
|
|
|
print(f" 📊 Deleted {deleted_count} shops total\n")
|
|
return deleted_count
|
|
|
|
except Exception as e:
|
|
print(f" ❌ Error fetching shops: {e}")
|
|
return 0
|
|
|
|
def get_current_data_summary():
|
|
"""Get a summary of current data in the database."""
|
|
print("📊 CURRENT DATA SUMMARY")
|
|
print("=" * 30)
|
|
|
|
try:
|
|
# Get counts
|
|
shops_response = requests.get(f"{BASE_URL}/shops/")
|
|
products_response = requests.get(f"{BASE_URL}/products/")
|
|
events_response = requests.get(f"{BASE_URL}/shopping-events/")
|
|
|
|
shops_count = len(shops_response.json()) if shops_response.status_code == 200 else 0
|
|
products_count = len(products_response.json()) if products_response.status_code == 200 else 0
|
|
events_count = len(events_response.json()) if events_response.status_code == 200 else 0
|
|
|
|
print(f"🏪 Shops: {shops_count}")
|
|
print(f"🥬 Products: {products_count}")
|
|
print(f"🛒 Shopping Events: {events_count}")
|
|
|
|
if events_count > 0 and events_response.status_code == 200:
|
|
events = events_response.json()
|
|
total_spent = sum(event.get('total_amount', 0) for event in events)
|
|
print(f"💰 Total spent: ${total_spent:.2f}")
|
|
|
|
print()
|
|
return shops_count, products_count, events_count
|
|
|
|
except Exception as e:
|
|
print(f"❌ Error getting data summary: {e}")
|
|
return 0, 0, 0
|
|
|
|
def main():
|
|
"""Main function to clean up all test data."""
|
|
print("🧹 PRODUCT TRACKER DATA CLEANUP")
|
|
print("=" * 40)
|
|
print("This script will delete ALL data from the Product Tracker app.")
|
|
print("Make sure the backend server is running on http://localhost:8000\n")
|
|
|
|
try:
|
|
# Test connection
|
|
response = requests.get(f"{BASE_URL}/")
|
|
if response.status_code != 200:
|
|
print("❌ Cannot connect to the API server. Make sure it's running!")
|
|
return
|
|
|
|
print("✅ Connected to API server\n")
|
|
|
|
# Show current data
|
|
shops_count, products_count, events_count = get_current_data_summary()
|
|
|
|
if shops_count == 0 and products_count == 0 and events_count == 0:
|
|
print("✅ Database is already empty. Nothing to clean up!")
|
|
return
|
|
|
|
# Confirm deletion
|
|
print("⚠️ WARNING: This will permanently delete all data!")
|
|
confirmation = input("Type 'DELETE' to confirm: ")
|
|
|
|
if confirmation != 'DELETE':
|
|
print("❌ Cleanup cancelled.")
|
|
return
|
|
|
|
print("\n🧹 Starting cleanup process...\n")
|
|
|
|
# Delete in order: events -> products -> shops
|
|
# (due to foreign key constraints)
|
|
deleted_events = delete_all_shopping_events()
|
|
deleted_products = delete_all_products()
|
|
deleted_shops = delete_all_shops()
|
|
|
|
# Final summary
|
|
print("📋 CLEANUP SUMMARY")
|
|
print("=" * 30)
|
|
print(f"🛒 Shopping Events deleted: {deleted_events}")
|
|
print(f"🥬 Products deleted: {deleted_products}")
|
|
print(f"🏪 Shops deleted: {deleted_shops}")
|
|
print(f"📊 Total items deleted: {deleted_events + deleted_products + deleted_shops}")
|
|
|
|
print("\n🎉 Cleanup completed successfully!")
|
|
print("The database is now empty and ready for fresh data.")
|
|
|
|
except requests.exceptions.ConnectionError:
|
|
print("❌ Could not connect to the API server.")
|
|
print(" Make sure the backend server is running on http://localhost:8000")
|
|
except KeyboardInterrupt:
|
|
print("\n❌ Cleanup cancelled by user.")
|
|
except Exception as e:
|
|
print(f"❌ Unexpected error: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
main() |