Spaces:
Running
Running
File size: 2,436 Bytes
6b3ee8d 5fc01f3 6b3ee8d 8f0180b 6b3ee8d 8f0180b 6b3ee8d 8f0180b 6b3ee8d 8f0180b 6b3ee8d 8f0180b 6b3ee8d 8f0180b 6b3ee8d 8f0180b 4b2e1ca 8f0180b 6b3ee8d 4b2e1ca 8f0180b 6b3ee8d 8f0180b 6b3ee8d | 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 | 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(email: str):
user_res = supabase.rpc("get_user_info", {"email_input": email}).execute()
if not user_res.data:
return None
user = user_res.data[0]
# 2. Fetch Stripe customer
cust_res = (
supabase.table("stripe.customers")
.select("*")
.eq("email", email)
.execute()
)
if not cust_res.data:
return {
"email": email,
"signed_up": user["created_at"],
"subscription": None
}
customer = cust_res.data[0]
# 3. Fetch subscriptions
sub_res = (
supabase.table("stripe.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"],
"subscription": None
}
subscriptions = []
for s in sub_res.data:
# Extract price_id from subscription item
price_id = (
s["items"]["data"][0]["price"]["id"]
if s.get("items") and s["items"].get("data")
else None
)
# 4. Fetch product info for this price
product_info = None
product_name = None
nickname = None
if price_id:
price_res = (
supabase.table("stripe.prices")
.select("id, nickname, product:product_id(name, description)")
.eq("id", price_id)
.execute()
)
if price_res.data:
product_info = price_res.data[0]
nickname = product_info.get("nickname")
if product_info.get("product"):
product_name = product_info["product"].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"],
"subscription": subscriptions
}
|