habulaj commited on
Commit
4835bd1
·
verified ·
1 Parent(s): 253e11b

Update routes/stylist.py

Browse files
Files changed (1) hide show
  1. routes/stylist.py +61 -29
routes/stylist.py CHANGED
@@ -3,6 +3,8 @@ import stripe
3
  import requests
4
  import logging
5
  from fastapi import APIRouter, HTTPException, Header
 
 
6
 
7
  router = APIRouter()
8
 
@@ -45,6 +47,55 @@ def verify_token(user_token: str) -> str:
45
  else:
46
  raise HTTPException(status_code=401, detail="Invalid or expired token")
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  @router.get("/dashboard")
49
  def get_dashboard(user_token: str = Header(None, alias="User-key")):
50
  try:
@@ -72,38 +123,19 @@ def get_dashboard(user_token: str = Header(None, alias="User-key")):
72
  user_data = response.json()[0]
73
  stripe_id = user_data.get("stripe_id")
74
 
75
- # Obter saldo da conta connect do Stripe
76
- try:
77
- balance = stripe.Balance.retrieve(stripe_account=stripe_id)
78
-
79
- # Processar o saldo disponível
80
- available_balance = 0
81
- pending_balance = 0
82
-
83
- # Soma todos os valores disponíveis em BRL
84
- for available in balance.available:
85
- if available.currency.lower() == 'brl':
86
- available_balance += available.amount
87
-
88
- # Soma todos os valores pendentes em BRL
89
- for pending in balance.pending:
90
- if pending.currency.lower() == 'brl':
91
- pending_balance += pending.amount
92
-
93
- # Converter de centavos para reais
94
- available_balance = available_balance / 100
95
- pending_balance = pending_balance / 100
96
-
97
  return {
98
- "stripe_id": stripe_id,
99
- "available_balance": available_balance,
100
- "pending_balance": pending_balance,
101
- "currency": "BRL"
102
  }
103
 
104
- except stripe.error.StripeError as e:
105
- logger.error(f"❌ Stripe error: {str(e)}")
106
- raise HTTPException(status_code=500, detail=f"Erro ao obter saldo: {str(e)}")
 
 
 
 
107
 
108
  except HTTPException as http_err:
109
  raise http_err
 
3
  import requests
4
  import logging
5
  from fastapi import APIRouter, HTTPException, Header
6
+ from datetime import datetime, timedelta
7
+ from typing import List, Dict, Any
8
 
9
  router = APIRouter()
10
 
 
47
  else:
48
  raise HTTPException(status_code=401, detail="Invalid or expired token")
49
 
50
+ def get_weekly_revenue(account_id: str) -> List[Dict[str, Any]]:
51
+ """
52
+ Busca os valores recebidos nas últimas 6 semanas para o account_id.
53
+ Retorna uma lista com número da semana, data e valor.
54
+ """
55
+ # Calcular o timestamp para 6 semanas atrás
56
+ end_date = datetime.now()
57
+ start_date = end_date - timedelta(weeks=6)
58
+ start_timestamp = int(start_date.timestamp())
59
+
60
+ # Buscar transferências para a conta
61
+ try:
62
+ transfers = stripe.Transfer.list(
63
+ destination=account_id,
64
+ created={"gte": start_timestamp},
65
+ limit=100 # Limitando a 100 transferências mais recentes
66
+ )
67
+
68
+ # Preparar dicionário para agrupar por semana
69
+ weekly_data = {}
70
+
71
+ # Processar as transferências
72
+ for transfer in transfers.data:
73
+ transfer_date = datetime.fromtimestamp(transfer.created)
74
+ # Número da semana no ano (1-53)
75
+ week_number = transfer_date.isocalendar()[1]
76
+ week_start = transfer_date - timedelta(days=transfer_date.weekday())
77
+ week_start_str = week_start.strftime("%Y-%m-%d")
78
+
79
+ if week_number not in weekly_data:
80
+ weekly_data[week_number] = {
81
+ "week": week_number,
82
+ "date": week_start_str,
83
+ "amount": 0
84
+ }
85
+
86
+ # Adicionar o valor da transferência (em centavos)
87
+ weekly_data[week_number]["amount"] += transfer.amount
88
+
89
+ # Converter para lista e ordenar por semana
90
+ result = list(weekly_data.values())
91
+ result.sort(key=lambda x: x["week"])
92
+
93
+ return result
94
+
95
+ except Exception as e:
96
+ logger.error(f"❌ Error getting weekly revenue: {str(e)}")
97
+ return []
98
+
99
  @router.get("/dashboard")
100
  def get_dashboard(user_token: str = Header(None, alias="User-key")):
101
  try:
 
123
  user_data = response.json()[0]
124
  stripe_id = user_data.get("stripe_id")
125
 
126
+ if not stripe_id:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  return {
128
+ "stripe_id": None,
129
+ "weekly_revenue": []
 
 
130
  }
131
 
132
+ # Buscar valores recebidos nas últimas 6 semanas
133
+ weekly_revenue = get_weekly_revenue(stripe_id)
134
+
135
+ return {
136
+ "stripe_id": stripe_id,
137
+ "weekly_revenue": weekly_revenue
138
+ }
139
 
140
  except HTTPException as http_err:
141
  raise http_err