Update routes/subscription.py
Browse files- routes/subscription.py +24 -11
routes/subscription.py
CHANGED
@@ -206,7 +206,7 @@ async def subscription_details(data: SubscriptionRequest):
|
|
206 |
stripe.Subscription.retrieve,
|
207 |
id=subscription_id,
|
208 |
expand=["items.data.price", "default_payment_method"]
|
209 |
-
)
|
210 |
|
211 |
if not subscription:
|
212 |
raise HTTPException(status_code=404, detail="Subscription not found")
|
@@ -354,6 +354,7 @@ async def stripe_webhook(request: Request):
|
|
354 |
amount_paid = invoice.get("amount_paid", 0)
|
355 |
currency = invoice.get("currency", "usd")
|
356 |
|
|
|
357 |
metadata = invoice.get("metadata", {})
|
358 |
subscription_metadata = invoice.get("subscription_details", {}).get("metadata", {})
|
359 |
line_items = invoice.get("lines", {}).get("data", [])
|
@@ -363,7 +364,13 @@ async def stripe_webhook(request: Request):
|
|
363 |
user_id = metadata.get("user_id") or subscription_metadata.get("user_id") or line_item_metadata.get("user_id")
|
364 |
price_id = metadata.get("price_id") or subscription_metadata.get("price_id") or line_item_metadata.get("price_id")
|
365 |
subscription_id = invoice.get("subscription")
|
366 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
367 |
|
368 |
stylist_amount = int(amount_paid * 0.8)
|
369 |
platform_amount = int(amount_paid * 0.2)
|
@@ -371,16 +378,20 @@ async def stripe_webhook(request: Request):
|
|
371 |
logger.info(f"✅ Pagamento bem-sucedido! Valor total: R$ {amount_paid / 100:.2f}")
|
372 |
logger.info(f"👤 Stylist ID: {stylist_id}")
|
373 |
logger.info(f"👥 User ID: {user_id}")
|
|
|
374 |
|
|
|
375 |
subscription_data = {
|
376 |
"stylist_id": stylist_id,
|
377 |
"customer_id": user_id,
|
378 |
"active": True,
|
379 |
"sub_id": subscription_id,
|
380 |
"price_id": price_id,
|
381 |
-
"consultations": consultations
|
382 |
}
|
383 |
|
|
|
|
|
384 |
response_subscription = requests.post(
|
385 |
f"{SUPABASE_URL}/rest/v1/Subscriptions",
|
386 |
headers=SUPABASE_HEADERS,
|
@@ -388,10 +399,11 @@ async def stripe_webhook(request: Request):
|
|
388 |
)
|
389 |
|
390 |
if response_subscription.status_code == 201:
|
391 |
-
logger.info(f"✅ Subscription
|
392 |
else:
|
393 |
-
logger.error(f"❌
|
394 |
|
|
|
395 |
check_chat_url = f"{SUPABASE_URL}/rest/v1/chats?stylist_id=eq.{stylist_id}&client_id=eq.{user_id}"
|
396 |
response_check_chat = requests.get(
|
397 |
check_chat_url,
|
@@ -403,7 +415,7 @@ async def stripe_webhook(request: Request):
|
|
403 |
existing_chats = response_check_chat.json()
|
404 |
if existing_chats:
|
405 |
chat_id = existing_chats[0]['id']
|
406 |
-
logger.info(f"ℹ️ Chat
|
407 |
else:
|
408 |
chat_data = {"stylist_id": stylist_id, "client_id": user_id}
|
409 |
create_chat_headers = SUPABASE_ROLE_HEADERS.copy()
|
@@ -416,10 +428,11 @@ async def stripe_webhook(request: Request):
|
|
416 |
if response_chat.status_code == 201:
|
417 |
new_chat_data = response_chat.json()
|
418 |
chat_id = new_chat_data[0]['id'] if isinstance(new_chat_data, list) else new_chat_data.get('id')
|
419 |
-
logger.info(f"✅ Chat
|
420 |
else:
|
421 |
-
logger.error(f"❌
|
422 |
|
|
|
423 |
if chat_id:
|
424 |
user_response = requests.get(
|
425 |
f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}&select=name",
|
@@ -437,7 +450,7 @@ async def stripe_webhook(request: Request):
|
|
437 |
message_data = {
|
438 |
"chat_id": chat_id,
|
439 |
"sender_id": user_id,
|
440 |
-
"content": f"{formatted_name}
|
441 |
"type": "warning"
|
442 |
}
|
443 |
|
@@ -450,9 +463,9 @@ async def stripe_webhook(request: Request):
|
|
450 |
)
|
451 |
|
452 |
if response_message.status_code == 201:
|
453 |
-
logger.info(f"✅
|
454 |
else:
|
455 |
-
logger.error(f"❌
|
456 |
|
457 |
return {
|
458 |
"status": "success",
|
|
|
206 |
stripe.Subscription.retrieve,
|
207 |
id=subscription_id,
|
208 |
expand=["items.data.price", "default_payment_method"]
|
209 |
+
)
|
210 |
|
211 |
if not subscription:
|
212 |
raise HTTPException(status_code=404, detail="Subscription not found")
|
|
|
354 |
amount_paid = invoice.get("amount_paid", 0)
|
355 |
currency = invoice.get("currency", "usd")
|
356 |
|
357 |
+
# 🔹 Extraindo metadados corretamente
|
358 |
metadata = invoice.get("metadata", {})
|
359 |
subscription_metadata = invoice.get("subscription_details", {}).get("metadata", {})
|
360 |
line_items = invoice.get("lines", {}).get("data", [])
|
|
|
364 |
user_id = metadata.get("user_id") or subscription_metadata.get("user_id") or line_item_metadata.get("user_id")
|
365 |
price_id = metadata.get("price_id") or subscription_metadata.get("price_id") or line_item_metadata.get("price_id")
|
366 |
subscription_id = invoice.get("subscription")
|
367 |
+
|
368 |
+
# 🔹 Pegando corretamente o número de consultas
|
369 |
+
consultations = (
|
370 |
+
int(metadata.get("consultations", 0)) or
|
371 |
+
int(subscription_metadata.get("consultations", 0)) or
|
372 |
+
int(line_item_metadata.get("consultations", 0))
|
373 |
+
)
|
374 |
|
375 |
stylist_amount = int(amount_paid * 0.8)
|
376 |
platform_amount = int(amount_paid * 0.2)
|
|
|
378 |
logger.info(f"✅ Pagamento bem-sucedido! Valor total: R$ {amount_paid / 100:.2f}")
|
379 |
logger.info(f"👤 Stylist ID: {stylist_id}")
|
380 |
logger.info(f"👥 User ID: {user_id}")
|
381 |
+
logger.info(f"📌 Número de consultas: {consultations}")
|
382 |
|
383 |
+
# 🔹 Atualiza a tabela Subscriptions no Supabase
|
384 |
subscription_data = {
|
385 |
"stylist_id": stylist_id,
|
386 |
"customer_id": user_id,
|
387 |
"active": True,
|
388 |
"sub_id": subscription_id,
|
389 |
"price_id": price_id,
|
390 |
+
"consultations": consultations # Certifique-se de que a coluna existe no Supabase
|
391 |
}
|
392 |
|
393 |
+
logger.info(f"📝 Enviando dados da assinatura ao Supabase: {subscription_data}")
|
394 |
+
|
395 |
response_subscription = requests.post(
|
396 |
f"{SUPABASE_URL}/rest/v1/Subscriptions",
|
397 |
headers=SUPABASE_HEADERS,
|
|
|
399 |
)
|
400 |
|
401 |
if response_subscription.status_code == 201:
|
402 |
+
logger.info(f"✅ Subscription adicionada com sucesso para o usuário {user_id}")
|
403 |
else:
|
404 |
+
logger.error(f"❌ Falha ao adicionar subscription: {response_subscription.status_code} - {response_subscription.text}")
|
405 |
|
406 |
+
# 🔹 Criar ou verificar chat existente
|
407 |
check_chat_url = f"{SUPABASE_URL}/rest/v1/chats?stylist_id=eq.{stylist_id}&client_id=eq.{user_id}"
|
408 |
response_check_chat = requests.get(
|
409 |
check_chat_url,
|
|
|
415 |
existing_chats = response_check_chat.json()
|
416 |
if existing_chats:
|
417 |
chat_id = existing_chats[0]['id']
|
418 |
+
logger.info(f"ℹ️ Chat já existe para stylist {stylist_id} e cliente {user_id}")
|
419 |
else:
|
420 |
chat_data = {"stylist_id": stylist_id, "client_id": user_id}
|
421 |
create_chat_headers = SUPABASE_ROLE_HEADERS.copy()
|
|
|
428 |
if response_chat.status_code == 201:
|
429 |
new_chat_data = response_chat.json()
|
430 |
chat_id = new_chat_data[0]['id'] if isinstance(new_chat_data, list) else new_chat_data.get('id')
|
431 |
+
logger.info(f"✅ Chat criado para stylist {stylist_id} e cliente {user_id}")
|
432 |
else:
|
433 |
+
logger.error(f"❌ Falha ao criar chat: {response_chat.status_code} - {response_chat.text}")
|
434 |
|
435 |
+
# 🔹 Enviar mensagem no chat
|
436 |
if chat_id:
|
437 |
user_response = requests.get(
|
438 |
f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}&select=name",
|
|
|
450 |
message_data = {
|
451 |
"chat_id": chat_id,
|
452 |
"sender_id": user_id,
|
453 |
+
"content": f"{formatted_name} assinou por 1 mês",
|
454 |
"type": "warning"
|
455 |
}
|
456 |
|
|
|
463 |
)
|
464 |
|
465 |
if response_message.status_code == 201:
|
466 |
+
logger.info(f"✅ Mensagem inicial criada para chat {chat_id}")
|
467 |
else:
|
468 |
+
logger.error(f"❌ Falha ao criar mensagem inicial: {response_message.status_code} - {response_message.text}")
|
469 |
|
470 |
return {
|
471 |
"status": "success",
|