from supabase import create_client, Client import os SUPABASE_URL = os.getenv("SUPABASE_URL") SUPABASE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY") supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) async def fetch_subscription(jwt: str): auth_res = supabase.auth.get_user(jwt) if auth_res.user is None: return {"error": "Invalid or expired session"} user = auth_res.user email = user.email cust_res = ( supabase.schema("stripe").table("customers") .select("*") .eq("email", email) .execute() ) if not cust_res.data: return { "email": email, "signed_up": user.created_at.isoformat() if hasattr(user.created_at, "isoformat") else user.created_at, "subscription": None } customer = cust_res.data[0] # Fetch subscriptions sub_res = ( supabase.schema("stripe").table("subscriptions") .select("*") .eq("customer", customer["id"]) .in_("status", ["active", "trialing", "past_due"]) .execute() ) if not sub_res.data: return { "email": email, "signed_up": user.created_at.isoformat() if hasattr(user.created_at, "isoformat") else user.created_at, "subscription": None } subscriptions = [] for s in sub_res.data: price_id = ( s["items"]["data"][0]["price"]["id"] if s.get("items") and s["items"].get("data") else None ) product_name = None nickname = None if price_id: price_res = ( supabase.schema("stripe").table("prices") .select("*") .eq("id", price_id) .execute() ) if price_res.data: price_row = price_res.data[0] nickname = price_row.get("nickname") product_id = price_row.get("product") if product_id: product_res = ( supabase.schema("stripe").table("products") .select("*") .eq("id", product_id) .execute() ) if product_res.data: product_name = product_res.data[0].get("name") subscriptions.append({ "status": s["status"], "subscription_id": s["id"], "current_period_end": s["current_period_end"], "product_name": product_name, "nickname": nickname }) return { "email": email, "signed_up": user.created_at.isoformat() if hasattr(user.created_at, "isoformat") else user.created_at, "subscription": subscriptions }