habulaj commited on
Commit
0fac780
·
verified ·
1 Parent(s): 33b9207

Update routes/stylist.py

Browse files
Files changed (1) hide show
  1. routes/stylist.py +21 -13
routes/stylist.py CHANGED
@@ -361,6 +361,7 @@ def get_monthly_likes(user_id: str) -> Dict[str, Any]:
361
  ny_timezone = pytz.timezone('America/New_York')
362
  now_ny = datetime.now(ny_timezone)
363
  monthly_data = {}
 
364
 
365
  # Inicializar dados para os últimos 6 meses
366
  for i in range(6):
@@ -380,18 +381,21 @@ def get_monthly_likes(user_id: str) -> Dict[str, Any]:
380
  start_date = (now_ny - relativedelta(months=6)).strftime('%Y-%m-%d')
381
 
382
  try:
383
- # Primeiro precisamos obter os itens do feed deste usuário
384
- feed_url = f"{SUPABASE_URL}/rest/v1/feed?user_id=eq.{user_id}"
385
- feed_response = requests.get(feed_url, headers=SUPABASE_HEADERS)
386
 
387
- if feed_response.status_code == 200:
388
- feed_items = feed_response.json()
389
- feed_item_ids = [item.get("id") for item in feed_items]
390
 
391
- if feed_item_ids:
392
- # Agora buscar likes para esses itens de feed
393
- # Usando o operador "in" do Supabase para buscar múltiplos IDs
394
- likes_url = f"{SUPABASE_URL}/rest/v1/likes?feed_item_id=in.({','.join(map(str, feed_item_ids))})&created_at=gte.{start_date}"
 
 
 
395
  likes_response = requests.get(likes_url, headers=SUPABASE_HEADERS)
396
 
397
  if likes_response.status_code == 200:
@@ -406,20 +410,23 @@ def get_monthly_likes(user_id: str) -> Dict[str, Any]:
406
  month_key = f"{like_date.year}-{like_date.month}"
407
  if month_key in monthly_data:
408
  monthly_data[month_key]["likes_count"] += 1
 
409
 
410
  # Convertendo para lista e ordenando por mês (do mais recente para o mais antigo)
411
  result = list(monthly_data.values())
412
  result.sort(key=lambda x: (now_ny.year * 12 + now_ny.month - (x["month"])) % 12)
413
 
414
  return {
415
- "monthly_likes": result
 
416
  }
417
  except Exception as e:
418
  logger.error(f"❌ Error getting monthly likes: {str(e)}")
419
  return {
420
- "monthly_likes": list(monthly_data.values())
 
421
  }
422
-
423
  @router.post("/bank_account_dashboard_link")
424
  async def generate_bank_account_dashboard_link(data: UserIDRequest):
425
  try:
@@ -486,6 +493,7 @@ def get_dashboard(user_token: str = Header(None, alias="User-key"), page: int =
486
  "total_revenue_last_6_months": revenue_data["total_last_6_months"],
487
  "monthly_courtesy_consultations": courtesy_data["monthly_courtesy_consultations"],
488
  "monthly_likes": likes_data["monthly_likes"],
 
489
  "total_followers": get_total_followers(user_id),
490
  "total_subscribers": get_total_subscribers(user_id),
491
  "account_details": account_details,
 
361
  ny_timezone = pytz.timezone('America/New_York')
362
  now_ny = datetime.now(ny_timezone)
363
  monthly_data = {}
364
+ total_likes_last_6_months = 0
365
 
366
  # Inicializar dados para os últimos 6 meses
367
  for i in range(6):
 
381
  start_date = (now_ny - relativedelta(months=6)).strftime('%Y-%m-%d')
382
 
383
  try:
384
+ # Primeiro, obter todos os feed_items do usuário
385
+ feeds_url = f"{SUPABASE_URL}/rest/v1/Feeds?user_id=eq.{user_id}"
386
+ feeds_response = requests.get(feeds_url, headers=SUPABASE_HEADERS)
387
 
388
+ if feeds_response.status_code == 200:
389
+ feeds = feeds_response.json()
390
+ feed_ids = [feed.get("id") for feed in feeds]
391
 
392
+ if feed_ids:
393
+ # Construir a condição para os feed_ids
394
+ # (não podemos usar in.() diretamente por limitações da API, então vamos fazer uma string)
395
+ feed_ids_str = ','.join([str(id) for id in feed_ids])
396
+
397
+ # Obter likes para esses feeds no intervalo de tempo
398
+ likes_url = f"{SUPABASE_URL}/rest/v1/likes?feed_item_id=in.({feed_ids_str})&created_at=gte.{start_date}"
399
  likes_response = requests.get(likes_url, headers=SUPABASE_HEADERS)
400
 
401
  if likes_response.status_code == 200:
 
410
  month_key = f"{like_date.year}-{like_date.month}"
411
  if month_key in monthly_data:
412
  monthly_data[month_key]["likes_count"] += 1
413
+ total_likes_last_6_months += 1
414
 
415
  # Convertendo para lista e ordenando por mês (do mais recente para o mais antigo)
416
  result = list(monthly_data.values())
417
  result.sort(key=lambda x: (now_ny.year * 12 + now_ny.month - (x["month"])) % 12)
418
 
419
  return {
420
+ "monthly_likes": result,
421
+ "total_likes_last_6_months": total_likes_last_6_months
422
  }
423
  except Exception as e:
424
  logger.error(f"❌ Error getting monthly likes: {str(e)}")
425
  return {
426
+ "monthly_likes": list(monthly_data.values()),
427
+ "total_likes_last_6_months": 0
428
  }
429
+
430
  @router.post("/bank_account_dashboard_link")
431
  async def generate_bank_account_dashboard_link(data: UserIDRequest):
432
  try:
 
493
  "total_revenue_last_6_months": revenue_data["total_last_6_months"],
494
  "monthly_courtesy_consultations": courtesy_data["monthly_courtesy_consultations"],
495
  "monthly_likes": likes_data["monthly_likes"],
496
+ "total_likes_last_6_months": likes_data["total_likes_last_6_months"],
497
  "total_followers": get_total_followers(user_id),
498
  "total_subscribers": get_total_subscribers(user_id),
499
  "account_details": account_details,