File size: 23,727 Bytes
4e00705
 
 
 
 
6bd9c66
 
 
4e00705
 
6bd9c66
 
 
4e00705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bd9c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e00705
 
 
 
 
 
6bd9c66
 
 
 
 
 
 
 
 
 
4e00705
6bd9c66
 
4e00705
 
 
 
 
 
6bd9c66
 
 
 
 
 
4e00705
b2dda13
4e00705
 
 
b2dda13
4e00705
 
 
 
 
 
 
 
 
6bd9c66
4e00705
 
 
6bd9c66
 
 
4e00705
 
 
 
 
 
 
 
6bd9c66
 
4e00705
 
 
6bd9c66
4e00705
 
6bd9c66
4e00705
6bd9c66
4e00705
 
6bd9c66
 
 
4e00705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bd9c66
 
4e00705
b2dda13
4e00705
 
 
b2dda13
4e00705
 
 
 
 
 
 
 
 
6bd9c66
4e00705
 
 
6bd9c66
 
 
4e00705
 
 
 
 
 
 
 
6bd9c66
4e00705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bd9c66
01810cf
6bd9c66
 
01810cf
6bd9c66
 
01810cf
 
6bd9c66
 
 
01810cf
6bd9c66
 
 
 
 
 
 
 
 
 
01810cf
 
 
 
 
 
 
 
6bd9c66
01810cf
 
6bd9c66
 
 
01810cf
 
 
6bd9c66
 
 
01810cf
6bd9c66
 
 
01810cf
 
6bd9c66
 
 
c854f83
c53a7af
c854f83
c53a7af
 
c854f83
 
 
 
 
 
 
 
 
 
 
 
 
c53a7af
c854f83
c53a7af
c854f83
c53a7af
c854f83
 
 
 
 
 
c53a7af
 
c854f83
 
c53a7af
 
 
 
 
 
 
 
 
 
 
 
c854f83
c53a7af
 
 
 
 
 
 
 
 
 
c854f83
 
 
 
 
c53a7af
c854f83
 
bc10bb3
 
 
 
c854f83
 
bc10bb3
c854f83
 
 
 
bc10bb3
 
 
 
c854f83
c53a7af
 
 
 
c854f83
c53a7af
 
c854f83
 
c53a7af
 
 
 
c854f83
 
c53a7af
c854f83
 
 
 
bc10bb3
6bd9c66
 
4e00705
b2dda13
 
4e00705
b2dda13
 
 
 
 
 
4e00705
b2dda13
 
 
 
6bd9c66
 
 
 
 
b2dda13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e00705
816121e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e00705
6bd9c66
4e00705
816121e
4e00705
 
 
816121e
4e00705
 
ada84bb
 
4e00705
816121e
 
4e00705
6bd9c66
 
 
 
cb92b93
 
6bd9c66
4e00705
816121e
6bd9c66
816121e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bd9c66
 
 
 
 
 
 
816121e
cb92b93
6bd9c66
cb92b93
6bd9c66
 
4e00705
 
 
 
 
b2dda13
 
4e00705
 
 
 
 
 
 
 
 
 
cb92b93
 
4e00705
 
816121e
 
b2dda13
816121e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2dda13
 
 
ada84bb
 
 
4e00705
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import os
import stripe
import requests
import logging
import pytz
import asyncio
import aiohttp
from fastapi import APIRouter, HTTPException, Header, Query, Depends
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from typing import Dict, Any, Optional, List, Tuple
from functools import lru_cache
from concurrent.futures import ThreadPoolExecutor

router = APIRouter()

# Configuração das chaves do Stripe e Supabase
stripe.api_key = os.getenv("STRIPE_KEY")
stripe.api_version = "2023-10-16"
SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
SUPABASE_KEY = os.getenv("SUPA_KEY")

if not stripe.api_key or not SUPABASE_KEY:
    raise ValueError("❌ STRIPE_KEY ou SUPA_KEY não foram definidos no ambiente!")

SUPABASE_HEADERS = {
    "apikey": SUPABASE_KEY,
    "Authorization": f"Bearer {SUPABASE_KEY}",
    "Content-Type": "application/json"
}

# Configuração do logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Pool de threads para chamadas paralelas
thread_pool = ThreadPoolExecutor(max_workers=10)

# Cache para reduzir chamadas repetidas
@lru_cache(maxsize=128)
def get_cached_admin_status(user_id: str) -> bool:
    """Obtém e armazena em cache se um usuário é admin"""
    user_data_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
    response = requests.get(user_data_url, headers=SUPABASE_HEADERS)
    
    if response.status_code != 200 or not response.json():
        return False
    
    user_info = response.json()[0]
    return user_info.get("is_admin", False)

async def verify_admin_token(user_token: str) -> str:
    """Verifica se o token pertence a um administrador de forma assíncrona"""
    headers = {
        "Authorization": f"Bearer {user_token}",
        "apikey": SUPABASE_KEY,
        "Content-Type": "application/json"
    }
    
    async with aiohttp.ClientSession() as session:
        # Verificar se o token é válido
        async with session.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers) as response:
            if response.status != 200:
                raise HTTPException(status_code=401, detail="Token inválido ou expirado")
            
            user_data = await response.json()
            user_id = user_data.get("id")
            if not user_id:
                raise HTTPException(status_code=400, detail="ID do usuário não encontrado")
    
    # Usar cache para verificar se é admin
    is_admin = await asyncio.to_thread(get_cached_admin_status, user_id)
    
    if not is_admin:
        raise HTTPException(status_code=403, detail="Acesso negado: privilégios de administrador necessários")
    
    return user_id

async def fetch_stripe_data(fetch_func, **params):
    """Executa chamadas ao Stripe em thread separada para não bloquear"""
    return await asyncio.to_thread(fetch_func, **params)

async def get_total_platform_revenue(start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None) -> Dict[str, Any]:
    """Obtém o faturamento total da plataforma no Stripe de forma otimizada"""
    try:
        query_params = {"limit": 100}
        
        # Adicionar filtros de data se fornecidos
        if start_timestamp and end_timestamp:
            query_params["created"] = {"gte": start_timestamp, "lte": end_timestamp}
        elif start_timestamp:
            query_params["created"] = {"gte": start_timestamp}
        elif end_timestamp:
            query_params["created"] = {"lte": end_timestamp}
        
        payments = []
        has_more = True
        last_id = None
        
        # Usar batch para reduzir chamadas
        while has_more:
            if last_id:
                query_params["starting_after"] = last_id
            
            # Usar thread para não bloquear o evento loop
            payment_list = await fetch_stripe_data(stripe.Charge.list, **query_params)
            payments.extend(payment_list.data)
            
            has_more = payment_list.has_more
            if payment_list.data:
                last_id = payment_list.data[-1].id
            else:
                has_more = False
        
        # Calcular totais em uma única passagem
        totals = {"total": 0, "succeeded": 0, "failed": 0}
        
        for payment in payments:
            amount = payment.amount
            totals["total"] += amount
            
            if payment.status == 'succeeded':
                totals["succeeded"] += amount
            elif payment.status == 'failed':
                totals["failed"] += amount
        
        return {
            "total_revenue": totals["total"],
            "successful_revenue": totals["succeeded"],
            "failed_revenue": totals["failed"],
            "currency": "BRL",
            "payment_count": len(payments)
        }
        
    except Exception as e:
        logger.error(f"❌ Erro ao obter faturamento total: {str(e)}")
        return {
            "total_revenue": 0,
            "successful_revenue": 0,
            "failed_revenue": 0,
            "currency": "BRL",
            "payment_count": 0,
            "error": str(e)
        }

async def get_platform_transfers(start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None) -> Dict[str, Any]:
    """Obtém o total transferido para estilistas de forma otimizada"""
    try:
        query_params = {"limit": 100}
        
        # Adicionar filtros de data se fornecidos
        if start_timestamp and end_timestamp:
            query_params["created"] = {"gte": start_timestamp, "lte": end_timestamp}
        elif start_timestamp:
            query_params["created"] = {"gte": start_timestamp}
        elif end_timestamp:
            query_params["created"] = {"lte": end_timestamp}
        
        transfers = []
        has_more = True
        last_id = None
        
        # Usar batch para reduzir chamadas
        while has_more:
            if last_id:
                query_params["starting_after"] = last_id
            
            # Usar thread para não bloquear o evento loop
            transfer_list = await fetch_stripe_data(stripe.Transfer.list, **query_params)
            transfers.extend(transfer_list.data)
            
            has_more = transfer_list.has_more
            if transfer_list.data:
                last_id = transfer_list.data[-1].id
            else:
                has_more = False
        
        # Cálculo otimizado
        total_transferred = sum(transfer.amount for transfer in transfers)
        
        return {
            "total_transferred_to_stylists": total_transferred,
            "currency": "BRL",
            "transfer_count": len(transfers)
        }
        
    except Exception as e:
        logger.error(f"❌ Erro ao obter transferências: {str(e)}")
        return {
            "total_transferred_to_stylists": 0,
            "currency": "BRL",
            "transfer_count": 0,
            "error": str(e)
        }

def get_app_revenue_share(total_revenue: int, total_transferred: int) -> Dict[str, Any]:
    """Calcula a parte do faturamento que ficou com o aplicativo"""
    app_revenue = total_revenue - total_transferred
    
    # Calcular percentuais
    if total_revenue > 0:
        app_percentage = (app_revenue / total_revenue) * 100
        stylists_percentage = (total_transferred / total_revenue) * 100
    else:
        app_percentage = 0
        stylists_percentage = 0
    
    return {
        "app_revenue": app_revenue,
        "app_percentage": round(app_percentage, 2),
        "stylists_percentage": round(stylists_percentage, 2),
        "currency": "BRL"
    }

async def get_platform_users() -> Dict[str, Any]:
    """Obtém informações sobre usuários, estilistas e assinaturas da plataforma de forma assíncrona"""
    try:
        async with aiohttp.ClientSession() as session:
            # Executar chamadas em paralelo para obter usuários, estilistas e assinaturas
            tasks = [
                session.get(f"{SUPABASE_URL}/rest/v1/User?select=id", headers=SUPABASE_HEADERS),
                session.get(f"{SUPABASE_URL}/rest/v1/User?role=eq.stylist&select=id", headers=SUPABASE_HEADERS),
                session.get(f"{SUPABASE_URL}/rest/v1/Subscriptions?select=id,active", headers=SUPABASE_HEADERS)
            ]
            
            responses = await asyncio.gather(*tasks)
            users_response, stylists_response, subscriptions_response = responses
            
            total_users = 0
            if users_response.status == 200:
                users_data = await users_response.json()
                total_users = len(users_data)
            
            total_stylists = 0
            if stylists_response.status == 200:
                stylists_data = await stylists_response.json()
                total_stylists = len(stylists_data)
                
            # Processar dados de assinaturas
            total_subscriptions = 0
            active_subscriptions = 0
            if subscriptions_response.status == 200:
                subscriptions_data = await subscriptions_response.json()
                total_subscriptions = len(subscriptions_data)
                active_subscriptions = sum(1 for sub in subscriptions_data if sub.get("active", False))
        
        logger.info(f"Total de usuários: {total_users}, Total de estilistas: {total_stylists}, " 
                   f"Assinaturas ativas: {active_subscriptions}, Total de assinaturas: {total_subscriptions}")
        
        return {
            "total_users": total_users,
            "total_stylists": total_stylists,
            "active_subscriptions": active_subscriptions,
            "total_subscriptions": total_subscriptions
        }
        
    except Exception as e:
        logger.error(f"❌ Erro ao obter informações de usuários e assinaturas: {str(e)}")
        return {
            "total_users": 0,
            "total_stylists": 0,
            "active_subscriptions": 0,
            "total_subscriptions": 0,
            "error": str(e)
        }

async def get_top_stylists(start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: int = 10) -> List[Dict[str, Any]]:
    """Obtém os estilistas com mais assinantes ativos e totais de forma otimizada"""
    try:
        # Obter todas as assinaturas
        base_url = f"{SUPABASE_URL}/rest/v1/Subscriptions?select=stylist_id,active,created_at"
        
        # Adicionar filtros de data se fornecidos
        if start_timestamp or end_timestamp:
            date_filters = []
            if start_timestamp:
                start_date = datetime.fromtimestamp(start_timestamp).strftime("%Y-%m-%d")
                date_filters.append(f"created_at=gte.{start_date}")
            if end_timestamp:
                end_date = datetime.fromtimestamp(end_timestamp).strftime("%Y-%m-%d")
                date_filters.append(f"created_at=lte.{end_date}")
            
            if date_filters:
                date_query = "&".join(date_filters)
                base_url = f"{base_url}&{date_query}"
        
        # Fazer a requisição para obter todas as assinaturas
        async with aiohttp.ClientSession() as session:
            async with session.get(base_url, headers=SUPABASE_HEADERS) as response:
                if response.status != 200:
                    logger.error(f"❌ Erro ao obter assinaturas: {response.status}")
                    return []
                
                subscriptions_data = await response.json()
        
        # Contadores para assinaturas ativas e totais por estilista
        stylists_stats = {}
        for subscription in subscriptions_data:
            stylist_id = subscription.get("stylist_id")
            is_active = subscription.get("active", False)
            
            if stylist_id not in stylists_stats:
                stylists_stats[stylist_id] = {
                    "active_count": 0, 
                    "total_count": 0
                }
            
            # Incrementar contadores
            stylists_stats[stylist_id]["total_count"] += 1
            if is_active:
                stylists_stats[stylist_id]["active_count"] += 1
        
        # Se não houver estilistas, retornar lista vazia
        if not stylists_stats:
            return []
        
        # Ordenar estilistas por número de assinaturas ativas (decrescente)
        top_stylist_ids = sorted(
            stylists_stats.keys(), 
            key=lambda x: stylists_stats[x]["active_count"], 
            reverse=True
        )[:limit]
        
        # Sem estilistas encontrados
        if not top_stylist_ids:
            return []
        
        # Obter detalhes dos estilistas em uma única chamada
        stylists_url = f"{SUPABASE_URL}/rest/v1/User?id=in.({','.join(top_stylist_ids)})&select=id,name,avatar"
        
        # Modificar os headers para garantir que a resposta seja tratada como UTF-8
        headers = SUPABASE_HEADERS.copy()
        headers["Accept"] = "application/json; charset=utf-8"
        
        # Obter detalhes dos estilistas
        async with aiohttp.ClientSession() as session:
            async with session.get(stylists_url, headers=headers) as response:
                if response.status != 200:
                    logger.error(f"❌ Erro ao obter detalhes dos estilistas: {response.status}")
                    return []
                
                # Forçar a decodificação como UTF-8
                text = await response.text(encoding='utf-8')
                import json
                stylists_data = json.loads(text)
        
        # Mapear os IDs para facilitar o acesso
        stylists_map = {stylist["id"]: stylist for stylist in stylists_data}
        
        # Combinar estatísticas com detalhes dos estilistas
        result = []
        for stylist_id in top_stylist_ids:
            if stylist_id in stylists_map:
                result.append({
                    "id": stylist_id,
                    "name": stylists_map[stylist_id].get("name", "Nome não disponível"),
                    "avatar": stylists_map[stylist_id].get("avatar", ""),
                    "active_subscriptions": stylists_stats[stylist_id]["active_count"],
                    "total_subscriptions": stylists_stats[stylist_id]["total_count"]
                })
        
        return result
        
    except Exception as e:
        logger.error(f"❌ Erro ao obter top estilistas: {str(e)}")
        return []
        
async def get_monthly_revenue_data(target_date) -> Dict[str, Any]:
    """Obtém o faturamento de um mês específico de forma otimizada"""
    ny_timezone = pytz.timezone('America/New_York')
    if not isinstance(target_date, datetime):
        target_date = datetime.now(ny_timezone)
    
    # Calcular início e fim do mês
    month_start = datetime(target_date.year, target_date.month, 1, tzinfo=ny_timezone)
    if target_date.month == 12:
        month_end = datetime(target_date.year + 1, 1, 1, tzinfo=ny_timezone) - timedelta(seconds=1)
    else:
        month_end = datetime(target_date.year, target_date.month + 1, 1, tzinfo=ny_timezone) - timedelta(seconds=1)
    
    # Converter para timestamps
    start_timestamp = int(month_start.timestamp())
    end_timestamp = int(month_end.timestamp())
    
    # Obter dados do mês em paralelo
    revenue_data, transfer_data = await asyncio.gather(
        get_total_platform_revenue(start_timestamp, end_timestamp),
        get_platform_transfers(start_timestamp, end_timestamp)
    )
    
    # Calcular divisão app/estilistas
    total_revenue = revenue_data["successful_revenue"]
    total_transferred = transfer_data["total_transferred_to_stylists"]
    app_revenue = total_revenue - total_transferred
    
    return {
        "year": target_date.year,
        "month": target_date.month,
        "name": target_date.strftime("%b"),
        "total_revenue": total_revenue,
        "app_revenue": app_revenue,
        "stylists_revenue": total_transferred,
        "payment_count": revenue_data["payment_count"],
        "transfer_count": transfer_data["transfer_count"]
    }

# Função auxiliar para lidar com os períodos específicos
def get_period_timestamps(period: str) -> Tuple[Optional[int], Optional[int]]:
    """Retorna timestamps inicial e final baseados no período especificado"""
    ny_timezone = pytz.timezone('America/New_York')
    now_ny = datetime.now(ny_timezone)
    current_year = now_ny.year
    
    # Inicializar timestamps
    start_timestamp = None
    end_timestamp = int(now_ny.timestamp())
    
    # Lidar com os meses específicos
    months = {
        'January': 1, 'February': 2, 'March': 3, 'April': 4,
        'May': 5, 'June': 6, 'July': 7, 'August': 8,
        'September': 9, 'October': 10, 'November': 11, 'December': 12
    }
    
    if period in months:
        # Período para um mês específico do ano atual
        month_num = months[period]
        
        # Se o mês solicitado ainda não chegou neste ano, use o ano anterior
        if month_num > now_ny.month:
            year = current_year - 1
        else:
            year = current_year
            
        # Definir início e fim do mês
        month_start = datetime(year, month_num, 1, tzinfo=ny_timezone)
        if month_num == 12:
            month_end = datetime(year + 1, 1, 1, tzinfo=ny_timezone) - timedelta(seconds=1)
        else:
            month_end = datetime(year, month_num + 1, 1, tzinfo=ny_timezone) - timedelta(seconds=1)
        
        start_timestamp = int(month_start.timestamp())
        end_timestamp = int(month_end.timestamp())
    
    elif period == "All Year":
        # Período para o ano atual inteiro
        year_start = datetime(current_year, 1, 1, tzinfo=ny_timezone)
        year_end = datetime(current_year + 1, 1, 1, tzinfo=ny_timezone) - timedelta(seconds=1)
        
        start_timestamp = int(year_start.timestamp())
        end_timestamp = int(year_end.timestamp())
        
        # Se estamos no início do ano, pode ser útil mostrar dados do ano anterior também
        if now_ny.month <= 2:
            year_start = datetime(current_year - 1, 1, 1, tzinfo=ny_timezone)
            start_timestamp = int(year_start.timestamp())
    
    # Períodos legados (manter para compatibilidade)
    elif period == "last_month":
        start_date = now_ny - relativedelta(months=1)
        start_timestamp = int(start_date.timestamp())
    elif period == "last_year":
        start_date = now_ny - relativedelta(years=1)
        start_timestamp = int(start_date.timestamp())
    
    return start_timestamp, end_timestamp

# Helper function to identify if we need specific month data
def is_specific_month(period: str) -> bool:
    """Verifica se o período solicitado é um mês específico"""
    months = [
        'January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'
    ]
    return period in months

@router.get("/admin/dashboard")
async def get_admin_dashboard(
    user_token: str = Header(None, alias="User-key"),
    period: str = Query("All Year", description="Período: All Year, January, February, etc.")
):
    """
    Endpoint para dashboard administrativo com métricas de faturamento
    e divisão entre app e estilistas - versão otimizada com seleção de meses
    """
    try:
        # Verificar se é um administrador
        user_id = await verify_admin_token(user_token)
        
        # Obter timestamps baseados no período
        start_timestamp, end_timestamp = get_period_timestamps(period)
        
        # Executar todas as chamadas em paralelo
        tasks = [
            get_total_platform_revenue(start_timestamp, end_timestamp),
            get_platform_transfers(start_timestamp, end_timestamp),
            get_platform_users(),
            get_top_stylists(start_timestamp, end_timestamp, 10)
        ]
        
        # Adicionar task para dados mensais se for um mês específico
        monthly_task = None
        monthly_data = None
        
        if is_specific_month(period):
            # Obter dados mensais para o mês solicitado
            ny_timezone = pytz.timezone('America/New_York')
            now_ny = datetime.now(ny_timezone)
            current_year = now_ny.year
            
            # Obter número do mês
            months = {
                'January': 1, 'February': 2, 'March': 3, 'April': 4,
                'May': 5, 'June': 6, 'July': 7, 'August': 8,
                'September': 9, 'October': 10, 'November': 11, 'December': 12
            }
            month_num = months[period]
            
            # Se o mês ainda não chegou neste ano, use o ano anterior
            if month_num > now_ny.month:
                year = current_year - 1
            else:
                year = current_year
                
            target_date = datetime(year, month_num, 1, tzinfo=ny_timezone)
            monthly_task = get_monthly_revenue_data(target_date)
            tasks.append(monthly_task)
        
        # Esperar por todas as chamadas completarem
        results = await asyncio.gather(*tasks)
        
        # Extrair resultados
        if is_specific_month(period):
            revenue_data, transfer_data, user_data, top_stylists, monthly_data = results
        else:
            revenue_data, transfer_data, user_data, top_stylists = results
        
        # Calcular divisão de receita
        revenue_share = get_app_revenue_share(
            revenue_data["successful_revenue"],
            transfer_data["total_transferred_to_stylists"]
        )
        
        # Preparar resposta
        response = {
            "total_revenue": revenue_data["successful_revenue"],
            "failed_revenue": revenue_data["failed_revenue"],
            "total_transferred_to_stylists": transfer_data["total_transferred_to_stylists"],
            "app_revenue": revenue_share["app_revenue"],
            "app_revenue_percentage": revenue_share["app_percentage"],
            "stylists_revenue_percentage": revenue_share["stylists_percentage"],
            "payment_count": revenue_data["payment_count"],
            "transfer_count": transfer_data["transfer_count"],
            "currency": "BRL",
            "period": period,
            "users": user_data,
            "top_stylists": top_stylists
        }
        
        # Adicionar dados específicos de mês
        if is_specific_month(period) and monthly_data:
            response["monthly_data"] = monthly_data
            
        # Para "All Year", adicionar dados mensais para visualização
        if period == "All Year":
            # Obter dados para cada mês do ano atual
            ny_timezone = pytz.timezone('America/New_York')
            now_ny = datetime.now(ny_timezone)
            current_year = now_ny.year
            
            monthly_tasks = []
            for month in range(1, 13):
                # Só incluir meses que já passaram ou o mês atual
                if month <= now_ny.month:
                    target_date = datetime(current_year, month, 1, tzinfo=ny_timezone)
                    monthly_tasks.append(get_monthly_revenue_data(target_date))
            
            if monthly_tasks:
                monthly_results = await asyncio.gather(*monthly_tasks)
                response["year_data"] = monthly_results
        
        return response
        
    except HTTPException as he:
        raise he
        
    except Exception as e:
        logger.error(f"❌ Erro ao gerar dashboard administrativo: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))