habulaj commited on
Commit
903beee
·
verified ·
1 Parent(s): 03095fc

Update routes/stylist.py

Browse files
Files changed (1) hide show
  1. routes/stylist.py +91 -4
routes/stylist.py CHANGED
@@ -52,7 +52,8 @@ def verify_token(user_token: str) -> str:
52
  def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
53
  """
54
  Busca os valores recebidos nos últimos 6 meses para o account_id.
55
- Retorna uma lista com número do mês, nome do mês, indicador se é o mês atual e valor.
 
56
  """
57
  # Obter data atual no fuso horário de Nova York
58
  ny_timezone = pytz.timezone('America/New_York')
@@ -81,7 +82,8 @@ def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
81
  "month": month_num,
82
  "name": month_name,
83
  "current": is_current,
84
- "amount": 0
 
85
  }
86
 
87
  # Calcular o timestamp para 6 meses atrás
@@ -112,6 +114,20 @@ def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
112
  result = list(monthly_data.values())
113
  result.sort(key=lambda x: (current_month - x["month"]) % 12)
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  return result
116
 
117
  except Exception as e:
@@ -158,6 +174,66 @@ def get_account_balance(account_id: str) -> Dict[str, Any]:
158
  "currency": "BRL"
159
  }
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  @router.get("/dashboard")
162
  def get_dashboard(user_token: str = Header(None, alias="User-key")):
163
  try:
@@ -185,13 +261,22 @@ def get_dashboard(user_token: str = Header(None, alias="User-key")):
185
  user_data = response.json()[0]
186
  stripe_id = user_data.get("stripe_id")
187
 
 
 
 
 
 
 
 
188
  if not stripe_id:
189
  return {
190
  "stripe_id": None,
191
  "available_balance": 0,
192
  "pending_balance": 0,
193
  "currency": "BRL",
194
- "monthly_revenue": []
 
 
195
  }
196
 
197
  # Buscar saldo da conta
@@ -205,7 +290,9 @@ def get_dashboard(user_token: str = Header(None, alias="User-key")):
205
  "available_balance": balance_info["available_balance"],
206
  "pending_balance": balance_info["pending_balance"],
207
  "currency": balance_info["currency"],
208
- "monthly_revenue": monthly_revenue
 
 
209
  }
210
 
211
  except HTTPException as http_err:
 
52
  def get_monthly_revenue(account_id: str) -> List[Dict[str, Any]]:
53
  """
54
  Busca os valores recebidos nos últimos 6 meses para o account_id.
55
+ Retorna uma lista com número do mês, nome do mês, indicador se é o mês atual, valor
56
+ e porcentagem de crescimento/queda em relação ao mês anterior.
57
  """
58
  # Obter data atual no fuso horário de Nova York
59
  ny_timezone = pytz.timezone('America/New_York')
 
82
  "month": month_num,
83
  "name": month_name,
84
  "current": is_current,
85
+ "amount": 0,
86
+ "growth_percentage": None # Será calculado depois
87
  }
88
 
89
  # Calcular o timestamp para 6 meses atrás
 
114
  result = list(monthly_data.values())
115
  result.sort(key=lambda x: (current_month - x["month"]) % 12)
116
 
117
+ # Calcular a porcentagem de crescimento/queda para cada mês
118
+ for i in range(1, len(result)):
119
+ current_amount = result[i]["amount"]
120
+ previous_amount = result[i-1]["amount"]
121
+
122
+ if previous_amount > 0:
123
+ # Calcular a porcentagem de crescimento e arredondar para 1 casa decimal
124
+ growth = ((current_amount - previous_amount) / previous_amount) * 100
125
+ direction = "up" if growth >= 0 else "down"
126
+ result[i]["growth_percentage"] = {
127
+ "direction": direction,
128
+ "value": round(abs(growth), 1)
129
+ }
130
+
131
  return result
132
 
133
  except Exception as e:
 
174
  "currency": "BRL"
175
  }
176
 
177
+ def get_total_followers(user_id: str, user_token: str) -> int:
178
+ """
179
+ Busca o total de seguidores do usuário na tabela 'followers'.
180
+ """
181
+ try:
182
+ # Consulta para contar os seguidores onde following_id é o user_id
183
+ followers_url = f"{SUPABASE_URL}/rest/v1/followers?select=count&following_id=eq.{user_id}"
184
+
185
+ response = requests.get(
186
+ followers_url,
187
+ headers={
188
+ "Authorization": f"Bearer {user_token}",
189
+ "apikey": SUPABASE_KEY,
190
+ "Content-Type": "application/json",
191
+ "Prefer": "count=exact"
192
+ }
193
+ )
194
+
195
+ if response.status_code != 200:
196
+ logger.error(f"❌ Error getting followers count: {response.text}")
197
+ return 0
198
+
199
+ # Extrair contagem do cabeçalho de resposta
200
+ count = int(response.headers.get("Content-Range", "0-0/0").split("/")[-1])
201
+ return count
202
+
203
+ except Exception as e:
204
+ logger.error(f"❌ Error getting total followers: {str(e)}")
205
+ return 0
206
+
207
+ def get_total_subscribers(user_id: str, user_token: str) -> int:
208
+ """
209
+ Busca o total de inscritos ativos do usuário na tabela 'Subscriptions'.
210
+ """
211
+ try:
212
+ # Consulta para contar as inscrições ativas onde stylist_id é o user_id
213
+ subscribers_url = f"{SUPABASE_URL}/rest/v1/Subscriptions?select=count&stylist_id=eq.{user_id}&active=eq.true"
214
+
215
+ response = requests.get(
216
+ subscribers_url,
217
+ headers={
218
+ "Authorization": f"Bearer {user_token}",
219
+ "apikey": SUPABASE_KEY,
220
+ "Content-Type": "application/json",
221
+ "Prefer": "count=exact"
222
+ }
223
+ )
224
+
225
+ if response.status_code != 200:
226
+ logger.error(f"❌ Error getting subscribers count: {response.text}")
227
+ return 0
228
+
229
+ # Extrair contagem do cabeçalho de resposta
230
+ count = int(response.headers.get("Content-Range", "0-0/0").split("/")[-1])
231
+ return count
232
+
233
+ except Exception as e:
234
+ logger.error(f"❌ Error getting total subscribers: {str(e)}")
235
+ return 0
236
+
237
  @router.get("/dashboard")
238
  def get_dashboard(user_token: str = Header(None, alias="User-key")):
239
  try:
 
261
  user_data = response.json()[0]
262
  stripe_id = user_data.get("stripe_id")
263
 
264
+ # Buscar total de seguidores
265
+ total_followers = get_total_followers(user_id, user_token)
266
+
267
+ # Buscar total de inscritos ativos
268
+ total_subscribers = get_total_subscribers(user_id, user_token)
269
+
270
+ # Resposta padrão se não houver stripe_id
271
  if not stripe_id:
272
  return {
273
  "stripe_id": None,
274
  "available_balance": 0,
275
  "pending_balance": 0,
276
  "currency": "BRL",
277
+ "monthly_revenue": [],
278
+ "total_followers": total_followers,
279
+ "total_subscribers": total_subscribers
280
  }
281
 
282
  # Buscar saldo da conta
 
290
  "available_balance": balance_info["available_balance"],
291
  "pending_balance": balance_info["pending_balance"],
292
  "currency": balance_info["currency"],
293
+ "monthly_revenue": monthly_revenue,
294
+ "total_followers": total_followers,
295
+ "total_subscribers": total_subscribers
296
  }
297
 
298
  except HTTPException as http_err: