Rompiendo
23 Abr 2025, Mié

3.Transferencias y movimientos

Incluirá:

  • Transferencias internas (entre usuarios).
  • Consulta de historial (mock inicial).
  • Validación de saldo.

transaction_service.py

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List

router = APIRouter()

Simulación de base de datos

from routers.account_service import accounts_db

transactions_log: List[dict] = []

class TransferRequest(BaseModel):
from_user: str
to_user: str
amount: float

@router.post(«/transferir»)
def transferir_fondos(transfer: TransferRequest):
origen = accounts_db.get(transfer.from_user)
destino = accounts_db.get(transfer.to_user)

if not origen or not destino:
    raise HTTPException(status_code=404, detail="Una de las cuentas no existe")

if origen["balance"] < transfer.amount:
    raise HTTPException(status_code=400, detail="Fondos insuficientes")

origen["balance"] -= transfer.amount
destino["balance"] += transfer.amount

transaccion = {
    "from": transfer.from_user,
    "to": transfer.to_user,
    "amount": transfer.amount
}
transactions_log.append(transaccion)
return {"message": "Transferencia completada", "transaccion": transaccion}

@router.get(«/historial/{user_id}»)
def historial_usuario(user_id: str):
historial = [t for t in transactions_log if t[«from»] == user_id or t[«to»] == user_id]
return {«historial»: historial}

Te has perdido

Enable Notifications OK No thanks