Update routes/stylist.py
Browse files- routes/stylist.py +55 -32
routes/stylist.py
CHANGED
@@ -2,8 +2,10 @@ import os
|
|
2 |
import stripe
|
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()
|
@@ -47,14 +49,43 @@ def verify_token(user_token: str) -> str:
|
|
47 |
else:
|
48 |
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
49 |
|
50 |
-
def
|
51 |
"""
|
52 |
-
Busca os valores recebidos
|
53 |
-
Retorna uma lista com número
|
54 |
"""
|
55 |
-
#
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
start_timestamp = int(start_date.timestamp())
|
59 |
|
60 |
# Buscar transferências para a conta
|
@@ -65,36 +96,28 @@ def get_weekly_revenue(account_id: str) -> List[Dict[str, Any]]:
|
|
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 |
-
|
75 |
-
|
76 |
-
|
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 |
-
#
|
87 |
-
|
|
|
|
|
88 |
|
89 |
-
# Converter para lista e ordenar por
|
90 |
-
result = list(
|
91 |
-
result.sort(key=lambda x: x["
|
92 |
|
93 |
return result
|
94 |
|
95 |
except Exception as e:
|
96 |
-
logger.error(f"❌ Error getting
|
97 |
-
|
|
|
98 |
|
99 |
def get_account_balance(account_id: str) -> Dict[str, Any]:
|
100 |
"""
|
@@ -168,21 +191,21 @@ def get_dashboard(user_token: str = Header(None, alias="User-key")):
|
|
168 |
"available_balance": 0,
|
169 |
"pending_balance": 0,
|
170 |
"currency": "BRL",
|
171 |
-
"
|
172 |
}
|
173 |
|
174 |
# Buscar saldo da conta
|
175 |
balance_info = get_account_balance(stripe_id)
|
176 |
|
177 |
-
# Buscar valores recebidos
|
178 |
-
|
179 |
|
180 |
return {
|
181 |
"stripe_id": stripe_id,
|
182 |
"available_balance": balance_info["available_balance"],
|
183 |
"pending_balance": balance_info["pending_balance"],
|
184 |
"currency": balance_info["currency"],
|
185 |
-
"
|
186 |
}
|
187 |
|
188 |
except HTTPException as http_err:
|
|
|
2 |
import stripe
|
3 |
import requests
|
4 |
import logging
|
5 |
+
import pytz
|
6 |
from fastapi import APIRouter, HTTPException, Header
|
7 |
from datetime import datetime, timedelta
|
8 |
+
from dateutil.relativedelta import relativedelta
|
9 |
from typing import List, Dict, Any
|
10 |
|
11 |
router = APIRouter()
|
|
|
49 |
else:
|
50 |
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
51 |
|
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')
|
59 |
+
now_ny = datetime.now(ny_timezone)
|
60 |
+
current_month = now_ny.month
|
61 |
+
current_year = now_ny.year
|
62 |
+
|
63 |
+
# Preparar dicionário com os últimos 6 meses (incluindo o atual)
|
64 |
+
monthly_data = {}
|
65 |
+
|
66 |
+
# Criar entradas para os últimos 6 meses, mesmo sem dados
|
67 |
+
for i in range(6):
|
68 |
+
# Calcular o mês e ano para i meses atrás
|
69 |
+
target_date = now_ny - relativedelta(months=i)
|
70 |
+
month_num = target_date.month
|
71 |
+
month_name = target_date.strftime('%b') # Formato abreviado do mês (Jan, Feb, etc)
|
72 |
+
year = target_date.year
|
73 |
+
|
74 |
+
# Chave composta para garantir unicidade (ano-mês)
|
75 |
+
month_key = f"{year}-{month_num}"
|
76 |
+
|
77 |
+
# Verificar se é o mês atual
|
78 |
+
is_current = (month_num == current_month and year == current_year)
|
79 |
+
|
80 |
+
monthly_data[month_key] = {
|
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
|
88 |
+
start_date = now_ny - relativedelta(months=6)
|
89 |
start_timestamp = int(start_date.timestamp())
|
90 |
|
91 |
# Buscar transferências para a conta
|
|
|
96 |
limit=100 # Limitando a 100 transferências mais recentes
|
97 |
)
|
98 |
|
|
|
|
|
|
|
99 |
# Processar as transferências
|
100 |
for transfer in transfers.data:
|
101 |
+
transfer_date = datetime.fromtimestamp(transfer.created, ny_timezone)
|
102 |
+
month_num = transfer_date.month
|
103 |
+
year = transfer_date.year
|
104 |
+
month_key = f"{year}-{month_num}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
+
# Verificar se o mês está dentro dos últimos 6 meses
|
107 |
+
if month_key in monthly_data:
|
108 |
+
# Adicionar o valor da transferência (em centavos)
|
109 |
+
monthly_data[month_key]["amount"] += transfer.amount
|
110 |
|
111 |
+
# Converter para lista e ordenar por data (mais antigo primeiro)
|
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:
|
118 |
+
logger.error(f"❌ Error getting monthly revenue: {str(e)}")
|
119 |
+
# Retornar os meses mesmo sem transferências
|
120 |
+
return list(monthly_data.values())
|
121 |
|
122 |
def get_account_balance(account_id: str) -> Dict[str, Any]:
|
123 |
"""
|
|
|
191 |
"available_balance": 0,
|
192 |
"pending_balance": 0,
|
193 |
"currency": "BRL",
|
194 |
+
"monthly_revenue": []
|
195 |
}
|
196 |
|
197 |
# Buscar saldo da conta
|
198 |
balance_info = get_account_balance(stripe_id)
|
199 |
|
200 |
+
# Buscar valores recebidos nos últimos 6 meses
|
201 |
+
monthly_revenue = get_monthly_revenue(stripe_id)
|
202 |
|
203 |
return {
|
204 |
"stripe_id": stripe_id,
|
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:
|