File size: 7,049 Bytes
36fe431
 
 
 
 
9b64783
 
 
 
 
 
36fe431
 
 
 
9b64783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36fe431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b64783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36fe431
 
9b64783
 
 
36fe431
 
 
9b64783
 
 
 
 
 
36fe431
9b64783
 
36fe431
 
 
9b64783
 
 
 
 
 
 
 
 
36fe431
 
9b64783
36fe431
 
 
 
 
 
 
 
 
 
 
 
9b64783
36fe431
 
9b64783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36fe431
 
 
9b64783
 
36fe431
 
9b64783
36fe431
 
9b64783
 
36fe431
9b64783
 
 
 
 
 
 
36fe431
 
9b64783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36fe431
9b64783
 
36fe431
 
9b64783
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python3
"""
Clear all transaction data from production database.
Run this script to start fresh while keeping categories, subcategories, 
payment methods, and users intact.

Usage:
    python clear_prod_data.py

Requirements:
    pip install psycopg2-binary python-dotenv
"""

import os
import sys

# Check dependencies
try:
    import psycopg2
    from dotenv import load_dotenv
except ImportError as e:
    print("="*60)
    print("MISSING DEPENDENCIES")
    print("="*60)
    print(f"\nError: {e}")
    print("\nPlease install required packages:")
    print("  pip install psycopg2-binary python-dotenv")
    print("\nOr activate your virtual environment:")
    print("  source .venv/bin/activate  # macOS/Linux")
    print("  .venv\\Scripts\\activate     # Windows")
    print("="*60)
    sys.exit(1)

# Load environment variables from .env.remote (production)
env_path = os.path.join(os.path.dirname(__file__), ".env.remote")
if os.path.exists(env_path):
    load_dotenv(env_path)
    print(f"Loaded environment from {env_path}")
else:
    load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))
    print("Loaded environment from .env")

database_url = os.getenv("DATABASE_URL")
if not database_url:
    print("ERROR: DATABASE_URL not set")
    sys.exit(1)

def parse_db_url(url):
    """Parse PostgreSQL URL into connection parameters."""
    # Handle postgres:// and postgresql://
    url = url.replace("postgres://", "postgresql://", 1)
    # Remove postgresql:// prefix
    url = url.replace("postgresql://", "")
    # Split user:password@host:port/dbname
    if "@" in url:
        creds, host_part = url.split("@", 1)
        user, password = creds.split(":", 1) if ":" in creds else (creds, "")
    else:
        user, password = "", ""
        host_part = url
    
    # Split host:port/dbname
    if "/" in host_part:
        host_port, dbname = host_part.split("/", 1)
        # Remove query params from dbname
        if "?" in dbname:
            dbname = dbname.split("?")[0]
    else:
        host_port = host_part
        dbname = "postgres"
    
    if ":" in host_port:
        host, port = host_port.rsplit(":", 1)
        port = int(port)
    else:
        host = host_port
        port = 5432
    
    return {
        "host": host,
        "port": port,
        "dbname": dbname,
        "user": user,
        "password": password
    }

print(f"\nConnecting to database...")
conn_params = parse_db_url(database_url)
print(f"Host: {conn_params['host']}")
print(f"Database: {conn_params['dbname']}\n")

def clear_data():
    """Clear all transaction data from the database."""
    conn = None
    try:
        conn = psycopg2.connect(**conn_params)
        conn.autocommit = False  # Use explicit transactions
        cur = conn.cursor()
        
        # Get counts before deletion
        cur.execute("SELECT COUNT(*) FROM transaction")
        tx_count = cur.fetchone()[0]
        
        print(f"Found {tx_count} transactions to delete")
        
        # Show sample transactions
        if tx_count > 0:
            cur.execute("SELECT id, amount, notes, date FROM transaction ORDER BY date DESC LIMIT 3")
            rows = cur.fetchall()
            print("\nSample transactions:")
            for r in rows:
                notes = r[2][:30] + "..." if r[2] and len(r[2]) > 30 else (r[2] or "(no notes)")
                print(f"  ID:{r[0]} ₪{r[1]} - {notes} - {r[3]}")
        
        if tx_count == 0:
            print("\nNo transactions found. Database is already clean.")
            conn.commit()
            return
        
        # Ask for confirmation
        print("\n" + "="*50)
        print("WARNING: This will PERMANENTLY DELETE all transactions!")
        print("Categories, subcategories, payment methods, and users")
        print("will be preserved.")
        print("="*50)
        
        confirm = input("\nType 'DELETE' to confirm: ")
        if confirm != "DELETE":
            print("\nAborted. No data was deleted.")
            conn.rollback()
            return
        
        # Delete transactions with verification loop
        max_attempts = 3
        total_deleted = 0
        
        for attempt in range(max_attempts):
            print(f"\nDeleting transactions (attempt {attempt + 1}/{max_attempts})...")
            cur.execute("DELETE FROM transaction")
            deleted = cur.rowcount
            total_deleted += deleted
            conn.commit()
            
            # Verify deletion
            cur.execute("SELECT COUNT(*) FROM transaction")
            remaining = cur.fetchone()[0]
            print(f"  Deleted: {deleted}, Remaining: {remaining}")
            
            if remaining == 0:
                break
            elif attempt < max_attempts - 1:
                print(f"  ⚠ New transaction appeared! Retrying...")
        
        # Optionally clear budget history (skip if table doesn't exist)
        try:
            cur.execute("SELECT COUNT(*) FROM budget_history")
            history_count = cur.fetchone()[0]
            
            if history_count > 0:
                print(f"\nFound {history_count} budget history records")
                confirm_history = input("Delete budget history too? (yes/no): ")
                if confirm_history.lower() == "yes":
                    cur.execute("DELETE FROM budget_history")
                    conn.commit()
                    print("Budget history cleared.")
        except psycopg2.errors.UndefinedTable:
            conn.rollback()  # Reset transaction after error
            print("(budget_history table not found - skipping)")
        
        # Final verification
        cur.execute("SELECT COUNT(*) FROM transaction")
        final_count = cur.fetchone()[0]
        
        print("\n" + "="*50)
        if final_count == 0:
            print(f"✓ SUCCESS: Deleted {total_deleted} transactions!")
            print("="*50)
            print("\nThe following data has been preserved:")
            print("  - Categories")
            print("  - SubCategories")  
            print("  - Payment Methods")
            print("  - Users")
            print("\n⚠ IMPORTANT: Close all browser tabs with the app open")
            print("   before refreshing, or the data may re-sync.")
        else:
            print(f"⚠ WARNING: {final_count} transactions still remain!")
            print("="*50)
            print("\nPossible causes:")
            print("  - An open browser/app is re-adding data")
            print("  - Multiple users are adding transactions")
            print("\nClose all app instances and run again.")
        
    except psycopg2.Error as e:
        if conn:
            conn.rollback()
        print(f"\nDatabase Error: {e}")
        sys.exit(1)
    except Exception as e:
        if conn:
            conn.rollback()
        print(f"\nERROR: {e}")
        sys.exit(1)
    finally:
        if conn:
            conn.close()
            print("\nDatabase connection closed.")

if __name__ == "__main__":
    clear_data()