habulaj commited on
Commit
6c06721
·
verified ·
1 Parent(s): 02a00fd

Update routes/users.py

Browse files
Files changed (1) hide show
  1. routes/users.py +24 -5
routes/users.py CHANGED
@@ -203,16 +203,18 @@ async def get_recent_users_endpoint(
203
  logger.error(f"❌ Erro ao obter usuários: {str(e)}")
204
  raise HTTPException(status_code=500, detail=str(e))
205
 
 
 
206
  @router.get("/admin/user-transfers")
207
  async def get_user_transfer_history(
208
  user_token: str = Header(None, alias="User-key"),
209
  user_id: str = Query(..., description="ID do usuário no Supabase")
210
  ):
211
  """
212
- Retorna os 10 últimos pagamentos do usuário com metadados e dados do stylist, além do total de cobranças.
213
  """
214
  try:
215
- # Verifica se o token é válido e tem permissão
216
  await verify_token_with_permissions(user_token, "view_users")
217
 
218
  # Buscar stripe_id do usuário
@@ -231,6 +233,14 @@ async def get_user_transfer_history(
231
  total_count = len(all_charges["data"])
232
  recent_charges = sorted(all_charges["data"], key=lambda c: c["created"], reverse=True)[:10]
233
 
 
 
 
 
 
 
 
 
234
  # Função auxiliar para buscar dados do stylist
235
  async def fetch_stylist(stylist_id: str) -> Optional[Dict[str, Any]]:
236
  url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{stylist_id}&select=name,email,avatar"
@@ -242,14 +252,13 @@ async def get_user_transfer_history(
242
  return data[0]
243
  return None
244
 
245
- # Reunir dados com stylists
246
  transfers = []
247
  tasks = []
248
 
249
  for charge in recent_charges:
250
  metadata = charge.get("metadata", {})
251
  stylist_id = metadata.get("stylist_id")
252
-
253
  task = fetch_stylist(stylist_id) if stylist_id else None
254
  tasks.append(task)
255
 
@@ -259,11 +268,21 @@ async def get_user_transfer_history(
259
  metadata = charge.get("metadata", {})
260
  stylist_info = stylist_data_list[i] if i < len(stylist_data_list) else None
261
 
 
 
 
 
 
 
262
  transfers.append({
263
  "id": charge["id"],
264
  "amount": charge["amount"] / 100,
265
  "currency": charge["currency"].upper(),
266
- "status": charge["status"],
 
 
 
 
267
  "created_at": datetime.fromtimestamp(charge["created"]).isoformat(),
268
  "description": charge.get("description"),
269
  "payment_method": charge.get("payment_method_details", {}).get("type"),
 
203
  logger.error(f"❌ Erro ao obter usuários: {str(e)}")
204
  raise HTTPException(status_code=500, detail=str(e))
205
 
206
+ from datetime import datetime
207
+
208
  @router.get("/admin/user-transfers")
209
  async def get_user_transfer_history(
210
  user_token: str = Header(None, alias="User-key"),
211
  user_id: str = Query(..., description="ID do usuário no Supabase")
212
  ):
213
  """
214
+ Retorna os 10 últimos pagamentos do usuário com metadados, dados do stylist e status formatado.
215
  """
216
  try:
217
+ # Verificar permissões
218
  await verify_token_with_permissions(user_token, "view_users")
219
 
220
  # Buscar stripe_id do usuário
 
233
  total_count = len(all_charges["data"])
234
  recent_charges = sorted(all_charges["data"], key=lambda c: c["created"], reverse=True)[:10]
235
 
236
+ # Mapeamento de status → label + cor
237
+ status_map = {
238
+ "succeeded": {"label": "Pago com sucesso", "color": "#22c55e"}, # Verde
239
+ "pending": {"label": "Pagamento pendente", "color": "#eab308"}, # Amarelo
240
+ "failed": {"label": "Pagamento falhou", "color": "#ef4444"}, # Vermelho
241
+ "canceled": {"label": "Pagamento cancelado", "color": "#6b7280"}, # Cinza
242
+ }
243
+
244
  # Função auxiliar para buscar dados do stylist
245
  async def fetch_stylist(stylist_id: str) -> Optional[Dict[str, Any]]:
246
  url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{stylist_id}&select=name,email,avatar"
 
252
  return data[0]
253
  return None
254
 
255
+ # Preparar tarefas para buscar stylists
256
  transfers = []
257
  tasks = []
258
 
259
  for charge in recent_charges:
260
  metadata = charge.get("metadata", {})
261
  stylist_id = metadata.get("stylist_id")
 
262
  task = fetch_stylist(stylist_id) if stylist_id else None
263
  tasks.append(task)
264
 
 
268
  metadata = charge.get("metadata", {})
269
  stylist_info = stylist_data_list[i] if i < len(stylist_data_list) else None
270
 
271
+ status_id = charge["status"]
272
+ status_info = status_map.get(status_id, {
273
+ "label": "Status desconhecido",
274
+ "color": "#9ca3af" # Cinza neutro
275
+ })
276
+
277
  transfers.append({
278
  "id": charge["id"],
279
  "amount": charge["amount"] / 100,
280
  "currency": charge["currency"].upper(),
281
+ "status_info": {
282
+ "id": status_id,
283
+ "label": status_info["label"],
284
+ "color": status_info["color"]
285
+ },
286
  "created_at": datetime.fromtimestamp(charge["created"]).isoformat(),
287
  "description": charge.get("description"),
288
  "payment_method": charge.get("payment_method_details", {}).get("type"),