habulaj commited on
Commit
4511ea1
·
verified ·
1 Parent(s): 46c88e6

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +22 -19
routes/subscription.py CHANGED
@@ -556,12 +556,27 @@ async def check_subscription(
556
  "canceled_date": canceled_at_date
557
  }
558
 
559
- await async_request(
560
- f"{SUPABASE_URL}/rest/v1/Subscriptions",
561
- SUPABASE_HEADERS,
562
- json=subscription_data,
563
- method='POST'
564
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565
 
566
  # Retorna informações sobre a assinatura sincronizada
567
  return {
@@ -600,18 +615,6 @@ async def check_subscription(
600
  raise HTTPException(status_code=500, detail="Error checking subscription.")
601
 
602
 
603
- # Função assíncrona para fazer requisições de rede
604
- async def async_request(url, headers, json=None, method='GET'):
605
- method_func = requests.post if method == 'POST' else requests.get
606
- response = method_func(url, headers=headers, json=json)
607
- return response
608
-
609
- # Função assíncrona para chamar a Stripe API
610
- async def async_stripe_request(func, **kwargs):
611
- loop = asyncio.get_event_loop()
612
- response = await loop.run_in_executor(None, lambda: func(**kwargs))
613
- return response
614
-
615
  # Função assíncrona para atualizar o status de uma assinatura
616
  async def update_subscription_status(subscription_id, status):
617
  update_data = {
@@ -625,6 +628,6 @@ async def update_subscription_status(subscription_id, status):
625
  method='PATCH'
626
  )
627
  if update_response.status_code == 200:
628
- logger.info(f"✅ Subscription {subscription_id} deactivated successfully.")
629
  else:
630
- logger.error(f"❌ Failed to deactivate subscription {subscription_id}.")
 
556
  "canceled_date": canceled_at_date
557
  }
558
 
559
+ # Verifica se a assinatura no banco de dados já existe e está marcada como inactive
560
+ response_existing_sub = await async_request(
561
+ f"{SUPABASE_URL}/rest/v1/Subscriptions?customer_id=eq.{user_id}&stylist_id=eq.{data.stylist_id}&sub_id=eq.{subscription_id}",
562
+ SUPABASE_HEADERS
 
563
  )
564
+ if response_existing_sub.status_code == 200 and response_existing_sub.json():
565
+ db_subscription = response_existing_sub.json()[0]
566
+ db_active = db_subscription.get("active")
567
+
568
+ # Se o status no banco for False e no Stripe for True, atualiza para True
569
+ if not db_active and status == "active":
570
+ await update_subscription_status(db_subscription["id"], True)
571
+
572
+ # Se a assinatura não existir no banco, cria uma nova
573
+ if response_existing_sub.status_code != 200 or not response_existing_sub.json():
574
+ await async_request(
575
+ f"{SUPABASE_URL}/rest/v1/Subscriptions",
576
+ SUPABASE_HEADERS,
577
+ json=subscription_data,
578
+ method='POST'
579
+ )
580
 
581
  # Retorna informações sobre a assinatura sincronizada
582
  return {
 
615
  raise HTTPException(status_code=500, detail="Error checking subscription.")
616
 
617
 
 
 
 
 
 
 
 
 
 
 
 
 
618
  # Função assíncrona para atualizar o status de uma assinatura
619
  async def update_subscription_status(subscription_id, status):
620
  update_data = {
 
628
  method='PATCH'
629
  )
630
  if update_response.status_code == 200:
631
+ logger.info(f"✅ Subscription {subscription_id} updated to {'active' if status else 'inactive'} successfully.")
632
  else:
633
+ logger.error(f"❌ Failed to update subscription {subscription_id}.")