Update routes/users.py
Browse files- routes/users.py +32 -16
routes/users.py
CHANGED
@@ -209,13 +209,12 @@ async def get_user_transfer_history(
|
|
209 |
user_id: str = Query(..., description="ID do usuário no Supabase")
|
210 |
):
|
211 |
"""
|
212 |
-
Retorna
|
213 |
-
Apenas para administradores ou usuários com permissão 'view_users'.
|
214 |
"""
|
215 |
try:
|
216 |
-
#
|
217 |
await verify_token_with_permissions(user_token, "view_users")
|
218 |
-
|
219 |
# Buscar stripe_id do usuário
|
220 |
user_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}&select=stripe_id"
|
221 |
async with aiohttp.ClientSession() as session:
|
@@ -224,34 +223,51 @@ async def get_user_transfer_history(
|
|
224 |
raise HTTPException(status_code=404, detail="Usuário não encontrado")
|
225 |
data = await response.json()
|
226 |
if not data or not data[0].get("stripe_id"):
|
227 |
-
raise HTTPException(status_code=404, detail="Stripe ID não encontrado
|
228 |
stripe_id = data[0]["stripe_id"]
|
|
|
|
|
|
|
|
|
229 |
|
230 |
-
#
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
for charge in
|
235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
236 |
"id": charge["id"],
|
237 |
-
"amount": charge["amount"] / 100,
|
238 |
"currency": charge["currency"].upper(),
|
239 |
"status": charge["status"],
|
240 |
"created_at": datetime.fromtimestamp(charge["created"]).isoformat(),
|
241 |
"description": charge.get("description"),
|
242 |
"payment_method": charge.get("payment_method_details", {}).get("type"),
|
243 |
"receipt_url": charge.get("receipt_url"),
|
|
|
|
|
244 |
})
|
245 |
|
246 |
return {
|
247 |
"stripe_id": stripe_id,
|
248 |
-
"transfers":
|
249 |
-
"count":
|
250 |
}
|
251 |
-
|
252 |
except HTTPException as he:
|
253 |
raise he
|
254 |
-
|
255 |
except Exception as e:
|
256 |
logger.error(f"❌ Erro ao obter transferências: {str(e)}")
|
257 |
raise HTTPException(status_code=500, detail="Erro interno ao consultar o histórico de transferências.")
|
|
|
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 produto, além do total de cobranças.
|
|
|
213 |
"""
|
214 |
try:
|
215 |
+
# Verificar permissões
|
216 |
await verify_token_with_permissions(user_token, "view_users")
|
217 |
+
|
218 |
# Buscar stripe_id do usuário
|
219 |
user_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}&select=stripe_id"
|
220 |
async with aiohttp.ClientSession() as session:
|
|
|
223 |
raise HTTPException(status_code=404, detail="Usuário não encontrado")
|
224 |
data = await response.json()
|
225 |
if not data or not data[0].get("stripe_id"):
|
226 |
+
raise HTTPException(status_code=404, detail="Stripe ID não encontrado")
|
227 |
stripe_id = data[0]["stripe_id"]
|
228 |
+
|
229 |
+
# Buscar todas as cobranças (limite maior para contagem)
|
230 |
+
all_charges = stripe.Charge.list(customer=stripe_id, limit=100, expand=["data.invoice"])
|
231 |
+
total_count = len(all_charges["data"])
|
232 |
|
233 |
+
# Selecionar os 10 últimos
|
234 |
+
recent_charges = sorted(all_charges["data"], key=lambda c: c["created"], reverse=True)[:10]
|
235 |
+
|
236 |
+
transfers = []
|
237 |
+
for charge in recent_charges:
|
238 |
+
product_name = None
|
239 |
+
invoice_id = charge.get("invoice")
|
240 |
+
|
241 |
+
# Se houver fatura, tentar obter o nome do produto
|
242 |
+
if invoice_id and isinstance(invoice_id, str):
|
243 |
+
invoice = stripe.Invoice.retrieve(invoice_id, expand=["lines.data.price.product"])
|
244 |
+
if invoice and invoice["lines"]["data"]:
|
245 |
+
first_line = invoice["lines"]["data"][0]
|
246 |
+
product = first_line.get("price", {}).get("product")
|
247 |
+
if isinstance(product, dict):
|
248 |
+
product_name = product.get("name")
|
249 |
+
|
250 |
+
transfers.append({
|
251 |
"id": charge["id"],
|
252 |
+
"amount": charge["amount"] / 100,
|
253 |
"currency": charge["currency"].upper(),
|
254 |
"status": charge["status"],
|
255 |
"created_at": datetime.fromtimestamp(charge["created"]).isoformat(),
|
256 |
"description": charge.get("description"),
|
257 |
"payment_method": charge.get("payment_method_details", {}).get("type"),
|
258 |
"receipt_url": charge.get("receipt_url"),
|
259 |
+
"metadata": charge.get("metadata", {}),
|
260 |
+
"product_name": product_name
|
261 |
})
|
262 |
|
263 |
return {
|
264 |
"stripe_id": stripe_id,
|
265 |
+
"transfers": transfers,
|
266 |
+
"count": total_count
|
267 |
}
|
268 |
+
|
269 |
except HTTPException as he:
|
270 |
raise he
|
|
|
271 |
except Exception as e:
|
272 |
logger.error(f"❌ Erro ao obter transferências: {str(e)}")
|
273 |
raise HTTPException(status_code=500, detail="Erro interno ao consultar o histórico de transferências.")
|