Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI | |
| import requests | |
| import os | |
| app = FastAPI() | |
| SUPABASE_URL = os.getenv("SUPABASE_URL", "").strip() | |
| SUPABASE_API_KEY = os.getenv("SUPABASE_API_KEY", "").strip() | |
| def reset_expired_plans(): | |
| print("📣 Starting plan reset task...") | |
| print(f"✅ Using Supabase URL: {SUPABASE_URL}") | |
| headers = { | |
| "apikey": SUPABASE_API_KEY, | |
| "Authorization": f"Bearer {SUPABASE_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| url = f"{SUPABASE_URL}/rest/v1/users?select=id,plan,days_remaining" | |
| print("📡 Fetching users with basic or premium plans...") | |
| try: | |
| r = requests.get(url, headers=headers) | |
| if r.status_code != 200: | |
| print(f"❌ Failed to fetch users: {r.text}") | |
| return {"status": "error", "detail": r.text} | |
| except Exception as e: | |
| print(f"🚨 Exception while fetching users: {e}") | |
| return {"status": "error", "exception": str(e)} | |
| users = r.json() | |
| print(f"🔍 Found {len(users)} users") | |
| reset_count = 0 | |
| updated_count = 0 | |
| for user in users: | |
| uid = user["id"] | |
| plan = user.get("plan", "free") | |
| days = user.get("days_remaining", 0) | |
| print(f"👤 User {uid} - Plan: {plan}, Days Remaining: {days}") | |
| if days <= 0 and plan in ("basic", "premium"): | |
| print(f"➡️ Resetting user {uid} to free") | |
| res = requests.patch( | |
| f"{SUPABASE_URL}/rest/v1/users?id=eq.{uid}", | |
| headers=headers, | |
| json={"plan": "free", "days_remaining": 0} | |
| ) | |
| if res.status_code == 204: | |
| reset_count += 1 | |
| else: | |
| print(f"❗ Failed to reset user {uid}: {res.text}") | |
| elif days > 0 and plan in ("basic", "premium"): | |
| print(f"📉 Decrementing days for user {uid} to {days - 1}") | |
| res = requests.patch( | |
| f"{SUPABASE_URL}/rest/v1/users?id=eq.{uid}", | |
| headers=headers, | |
| json={"days_remaining": days - 1} | |
| ) | |
| if res.status_code == 204: | |
| updated_count += 1 | |
| else: | |
| print(f"❗ Failed to decrement days for user {uid}: {res.text}") | |
| else: | |
| print(f"✅ No action needed for user {uid}") | |
| return { | |
| "status": "success", | |
| "reset_to_free": reset_count, | |
| "decremented_days": updated_count | |
| } | |