habulaj commited on
Commit
661c6fb
·
verified ·
1 Parent(s): bf16d6d

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +46 -82
routes/subscription.py CHANGED
@@ -351,38 +351,34 @@ async def stripe_webhook(request: Request):
351
  if event_type == "invoice.payment_succeeded":
352
  invoice = payload.get("data", {}).get("object", {})
353
 
354
- # 🔹 Capturar valores da fatura
355
  amount_paid = invoice.get("amount_paid", 0)
356
  currency = invoice.get("currency", "usd")
357
-
358
- # 🔹 Buscando metadados
359
  metadata = invoice.get("metadata", {})
360
  subscription_metadata = invoice.get("subscription_details", {}).get("metadata", {})
361
  line_items = invoice.get("lines", {}).get("data", [])
362
  line_item_metadata = line_items[0].get("metadata", {}) if line_items else {}
363
 
364
- # 🔹 Pegando os valores corretos
365
  stylist_id = metadata.get("stylist_id") or subscription_metadata.get("stylist_id") or line_item_metadata.get("stylist_id")
366
  user_id = metadata.get("user_id") or subscription_metadata.get("user_id") or line_item_metadata.get("user_id")
367
  price_id = metadata.get("price_id") or subscription_metadata.get("price_id") or line_item_metadata.get("price_id")
368
  subscription_id = invoice.get("subscription")
 
369
 
370
- # 🔹 Calculando a divisão do pagamento
371
  stylist_amount = int(amount_paid * 0.8)
372
  platform_amount = int(amount_paid * 0.2)
373
 
374
- # 🔹 Logando as informações
375
  logger.info(f"✅ Pagamento bem-sucedido! Valor total: R$ {amount_paid / 100:.2f}")
376
  logger.info(f"👤 Stylist ID: {stylist_id}")
377
  logger.info(f"👥 User ID: {user_id}")
378
 
379
- # 🔹 Inserir dados na tabela Subscriptions
380
  subscription_data = {
381
  "stylist_id": stylist_id,
382
  "customer_id": user_id,
383
  "active": True,
384
  "sub_id": subscription_id,
385
- "price_id": price_id
 
386
  }
387
 
388
  response_subscription = requests.post(
@@ -396,99 +392,67 @@ async def stripe_webhook(request: Request):
396
  else:
397
  logger.error(f"❌ Failed to add subscription: {response_subscription.status_code} - {response_subscription.text}")
398
 
399
- # 🔹 Verificar se já existe chat entre stylist e client
400
  check_chat_url = f"{SUPABASE_URL}/rest/v1/chats?stylist_id=eq.{stylist_id}&client_id=eq.{user_id}"
401
  response_check_chat = requests.get(
402
  check_chat_url,
403
  headers=SUPABASE_ROLE_HEADERS
404
  )
405
 
 
406
  if response_check_chat.status_code == 200:
407
  existing_chats = response_check_chat.json()
408
-
409
- # 🔹 Se não existir chat, criar novo e adicionar mensagem inicial
410
- if not existing_chats:
411
- chat_data = {
412
- "stylist_id": stylist_id,
413
- "client_id": user_id
414
- }
415
-
416
- # Criar novo chat com Prefer: return=representation header
417
  create_chat_headers = SUPABASE_ROLE_HEADERS.copy()
418
  create_chat_headers["Prefer"] = "return=representation"
419
-
420
  response_chat = requests.post(
421
  f"{SUPABASE_URL}/rest/v1/chats",
422
  headers=create_chat_headers,
423
  json=chat_data
424
  )
425
-
426
  if response_chat.status_code == 201:
427
- try:
428
- # Pegando o ID do chat recém-criado
429
- new_chat_data = response_chat.json()
430
- if isinstance(new_chat_data, list) and len(new_chat_data) > 0:
431
- chat_id = new_chat_data[0].get('id')
432
- else:
433
- chat_id = new_chat_data.get('id')
434
-
435
- logger.info(f"✅ Chat created for stylist {stylist_id} and client {user_id}")
436
- logger.info(f"📝 Chat ID: {chat_id}")
437
-
438
- if chat_id:
439
- # 🔹 Buscar nome do usuário
440
- user_response = requests.get(
441
- f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}&select=name",
442
- headers=SUPABASE_ROLE_HEADERS
443
- )
444
-
445
- formatted_name = "User" # Nome padrão caso não encontre
446
-
447
- if user_response.status_code == 200:
448
- user_data = user_response.json()
449
- if user_data and len(user_data) > 0:
450
- full_name = user_data[0].get('name', '').strip()
451
- name_parts = full_name.split()
452
-
453
- if len(name_parts) > 1:
454
- # Primeiro nome + primeira letra do segundo nome
455
- formatted_name = f"{name_parts[0]} {name_parts[1][0]}"
456
- else:
457
- # Apenas primeiro nome
458
- formatted_name = name_parts[0]
459
-
460
- # 🔹 Criando mensagem inicial com nome formatado
461
- message_data = {
462
- "chat_id": chat_id,
463
- "sender_id": user_id,
464
- "content": f"{formatted_name} subscribed for 1 month",
465
- "type": "warning"
466
- }
467
-
468
- # Criar mensagem com Prefer: return=representation header
469
- create_message_headers = SUPABASE_ROLE_HEADERS.copy()
470
- create_message_headers["Prefer"] = "return=representation"
471
-
472
- response_message = requests.post(
473
- f"{SUPABASE_URL}/rest/v1/messages",
474
- headers=create_message_headers,
475
- json=message_data
476
- )
477
-
478
- if response_message.status_code == 201:
479
- logger.info(f"✅ Initial message created for chat {chat_id}")
480
- logger.info(f"📝 Message: {formatted_name} subscribed for 1 month")
481
- else:
482
- logger.error(f"❌ Failed to create initial message: {response_message.status_code} - {response_message.text}")
483
- else:
484
- logger.error("❌ Failed to get chat_id from response")
485
- except Exception as e:
486
- logger.error(f"❌ Error processing chat creation response: {str(e)}")
487
- logger.error(f"Response content: {response_chat.text}")
488
  else:
489
  logger.error(f"❌ Failed to create chat: {response_chat.status_code} - {response_chat.text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
  else:
491
- logger.info(f"ℹ️ Chat already exists for stylist {stylist_id} and client {user_id}")
492
 
493
  return {
494
  "status": "success",
 
351
  if event_type == "invoice.payment_succeeded":
352
  invoice = payload.get("data", {}).get("object", {})
353
 
 
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", [])
360
  line_item_metadata = line_items[0].get("metadata", {}) if line_items else {}
361
 
 
362
  stylist_id = metadata.get("stylist_id") or subscription_metadata.get("stylist_id") or line_item_metadata.get("stylist_id")
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
+ consultations = int(metadata.get("consultations", 0))
367
 
 
368
  stylist_amount = int(amount_paid * 0.8)
369
  platform_amount = int(amount_paid * 0.2)
370
 
 
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(
 
392
  else:
393
  logger.error(f"❌ Failed to add subscription: {response_subscription.status_code} - {response_subscription.text}")
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,
398
  headers=SUPABASE_ROLE_HEADERS
399
  )
400
 
401
+ chat_id = None
402
  if response_check_chat.status_code == 200:
403
  existing_chats = response_check_chat.json()
404
+ if existing_chats:
405
+ chat_id = existing_chats[0]['id']
406
+ logger.info(f"ℹ️ Chat already exists for stylist {stylist_id} and client {user_id}")
407
+ else:
408
+ chat_data = {"stylist_id": stylist_id, "client_id": user_id}
 
 
 
 
409
  create_chat_headers = SUPABASE_ROLE_HEADERS.copy()
410
  create_chat_headers["Prefer"] = "return=representation"
 
411
  response_chat = requests.post(
412
  f"{SUPABASE_URL}/rest/v1/chats",
413
  headers=create_chat_headers,
414
  json=chat_data
415
  )
 
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 created for stylist {stylist_id} and client {user_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  else:
421
  logger.error(f"❌ Failed to create chat: {response_chat.status_code} - {response_chat.text}")
422
+
423
+ if chat_id:
424
+ user_response = requests.get(
425
+ f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}&select=name",
426
+ headers=SUPABASE_ROLE_HEADERS
427
+ )
428
+
429
+ formatted_name = "User"
430
+ if user_response.status_code == 200:
431
+ user_data = user_response.json()
432
+ if user_data:
433
+ full_name = user_data[0].get('name', '').strip()
434
+ name_parts = full_name.split()
435
+ formatted_name = f"{name_parts[0]} {name_parts[1][0]}" if len(name_parts) > 1 else name_parts[0]
436
+
437
+ message_data = {
438
+ "chat_id": chat_id,
439
+ "sender_id": user_id,
440
+ "content": f"{formatted_name} subscribed for 1 month",
441
+ "type": "warning"
442
+ }
443
+
444
+ create_message_headers = SUPABASE_ROLE_HEADERS.copy()
445
+ create_message_headers["Prefer"] = "return=representation"
446
+ response_message = requests.post(
447
+ f"{SUPABASE_URL}/rest/v1/messages",
448
+ headers=create_message_headers,
449
+ json=message_data
450
+ )
451
+
452
+ if response_message.status_code == 201:
453
+ logger.info(f"✅ Initial message created for chat {chat_id}")
454
  else:
455
+ logger.error(f" Failed to create initial message: {response_message.status_code} - {response_message.text}")
456
 
457
  return {
458
  "status": "success",