-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_subscription_system.py
More file actions
258 lines (206 loc) · 7.92 KB
/
Copy pathsetup_subscription_system.py
File metadata and controls
258 lines (206 loc) · 7.92 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env python3
"""
Setup script for subscription billing system
This script helps you set up and verify the subscription system configuration.
Usage:
python setup_subscription_system.py
"""
import os
import sys
from pathlib import Path
def check_python_version():
"""Check Python version"""
if sys.version_info < (3, 8):
print("❌ Python 3.8 or higher is required")
return False
print(f"✅ Python {sys.version_info.major}.{sys.version_info.minor} detected")
return True
def check_environment_file():
"""Check and help create .env file"""
env_file = Path(".env")
env_example = Path(".env.example")
if not env_file.exists():
if env_example.exists():
print("📝 Creating .env file from .env.example...")
with open(env_example) as src, open(env_file, 'w') as dst:
dst.write(src.read())
print("✅ .env file created")
else:
print("❌ .env.example file not found")
return False
else:
print("✅ .env file exists")
return True
def check_required_packages():
"""Check if required packages are installed"""
required_packages = [
"fastapi",
"uvicorn",
"motor",
"pymongo",
"pydantic",
"httpx",
"python-dotenv"
]
missing_packages = []
for package in required_packages:
try:
__import__(package.replace("-", "_"))
print(f"✅ {package} installed")
except ImportError:
missing_packages.append(package)
print(f"❌ {package} not installed")
if missing_packages:
print(f"\n📦 Install missing packages:")
print(f"pip install {' '.join(missing_packages)}")
return False
return True
def check_directory_structure():
"""Check if required directories exist"""
required_dirs = [
"app/billing",
"app/config",
"app/models",
"app/repositories",
"app/routes"
]
missing_dirs = []
for dir_path in required_dirs:
if os.path.exists(dir_path):
print(f"✅ {dir_path}/ exists")
else:
missing_dirs.append(dir_path)
print(f"❌ {dir_path}/ missing")
if missing_dirs:
print("\n📁 Some directories are missing. Make sure you've created all the files.")
return False
return True
def check_database_connection():
"""Check MongoDB connection"""
try:
from dotenv import load_dotenv
import motor.motor_asyncio
load_dotenv()
mongodb_url = os.getenv("MONGODB_URL")
if not mongodb_url:
print("❌ MONGODB_URL not set in .env file")
return False
print(f"✅ MONGODB_URL configured: {mongodb_url[:20]}...")
# Try to connect (this is basic - full test requires async)
print("💡 Database connection will be tested when server starts")
return True
except ImportError as e:
print(f"❌ Cannot import required modules: {e}")
return False
except Exception as e:
print(f"❌ Database check failed: {e}")
return False
def check_billing_configuration():
"""Check billing configuration"""
from dotenv import load_dotenv
load_dotenv()
billing_provider = os.getenv("BILLING_PROVIDER", "paypal")
print(f"✅ Billing provider: {billing_provider}")
if billing_provider.lower() == "paypal":
paypal_mode = os.getenv("PAYPAL_MODE", "sandbox")
paypal_client_id = os.getenv("PAYPAL_CLIENT_ID")
paypal_client_secret = os.getenv("PAYPAL_CLIENT_SECRET")
print(f"✅ PayPal mode: {paypal_mode}")
if paypal_client_id:
print(f"✅ PayPal Client ID configured: {paypal_client_id[:10]}...")
else:
print("⚠️ PayPal Client ID not configured (will fail on real transactions)")
if paypal_client_secret:
print(f"✅ PayPal Client Secret configured: {paypal_client_secret[:10]}...")
else:
print("⚠️ PayPal Client Secret not configured (will fail on real transactions)")
return True
def run_basic_import_test():
"""Test that subscription system modules can be imported"""
try:
print("\n🧪 Testing module imports...")
from app.config.subscription_plans import get_all_plans, validate_plan_code
from app.models.subscription import Subscription, SubscriptionStatus
from app.models.invoice import Invoice, InvoiceStatus
from app.billing.billing_service import billing_service
from app.billing.vm_lifecycle_hooks import vm_lifecycle_hooks
print("✅ All core modules import successfully")
# Test basic functionality
plans = get_all_plans()
print(f"✅ Found {len(plans)} subscription plans")
if validate_plan_code("PRO_4GB"):
print("✅ Plan validation working")
else:
print("❌ Plan validation failed")
return False
print("✅ Basic functionality tests passed")
return True
except ImportError as e:
print(f"❌ Import error: {e}")
return False
except Exception as e:
print(f"❌ Functionality test failed: {e}")
return False
def print_next_steps():
"""Print next steps for user"""
print("\n" + "="*60)
print("🚀 Setup Complete! Next Steps:")
print("="*60)
print("\n1. 📊 Start the server:")
print(" uvicorn app.app:app --reload --host 0.0.0.0 --port 8005")
print("\n2. 🧪 Run integration tests:")
print(" python test_subscription_integration.py")
print("\n3. 🔧 Manual API testing:")
print(" python manual_test_api.py")
print("\n4. 💳 Configure PayPal (for real transactions):")
print(" - Create PayPal Developer account")
print(" - Get sandbox Client ID and Secret")
print(" - Update .env file with credentials")
print(" - Set up webhook endpoint")
print("\n5. 🌐 Frontend testing:")
print(" cd frontend")
print(" npm install")
print(" npm run dev")
print("\n6. 📝 Database setup:")
print(" - Ensure MongoDB is running")
print(" - Collections will be created automatically")
print("\n💡 Documentation:")
print(" - Read SUBSCRIPTION_SYSTEM.md for detailed information")
print(" - Check tests/ directory for usage examples")
def main():
"""Main setup function"""
print("🔧 Subscription System Setup")
print("="*40)
checks = [
("Python Version", check_python_version),
("Environment File", check_environment_file),
("Required Packages", check_required_packages),
("Directory Structure", check_directory_structure),
("Database Configuration", check_database_connection),
("Billing Configuration", check_billing_configuration),
("Module Imports", run_basic_import_test),
]
all_passed = True
for check_name, check_func in checks:
print(f"\n🔍 Checking {check_name}...")
try:
if not check_func():
all_passed = False
except Exception as e:
print(f"❌ {check_name} check failed: {e}")
all_passed = False
print("\n" + "="*40)
if all_passed:
print("🎉 All checks passed!")
print_next_steps()
else:
print("❌ Some checks failed. Please fix the issues above.")
print("\n🔧 Common solutions:")
print("- Run: pip install -r requirements.txt")
print("- Check MongoDB is running")
print("- Verify .env file configuration")
print("- Make sure all files were created correctly")
return all_passed
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)