|
| 1 | +"""Wallet and Transaction management endpoints.""" |
| 2 | + |
| 3 | +import uuid |
| 4 | +from decimal import Decimal |
| 5 | + |
| 6 | +from fastapi import APIRouter, HTTPException |
| 7 | +from sqlmodel import func, select |
| 8 | + |
| 9 | +from app.api.deps import CurrentUser, SessionDep |
| 10 | +from app.constants import BAD_REQUEST_CODE, CONFLICT_CODE, NOT_FOUND_CODE |
| 11 | +from typing import cast |
| 12 | + |
| 13 | +from app.core.currency import Currency, apply_fee, convert, quantize_money |
| 14 | +from app.models import ( |
| 15 | + Transaction, |
| 16 | + TransactionCreate, |
| 17 | + TransactionPublic, |
| 18 | + Wallet, |
| 19 | + WalletCreate, |
| 20 | + WalletPublic, |
| 21 | +) |
| 22 | + |
| 23 | +router = APIRouter(prefix="/wallets", tags=["wallets"]) |
| 24 | + |
| 25 | + |
| 26 | +@router.post("/") |
| 27 | +def create_wallet( |
| 28 | + *, session: SessionDep, current_user: CurrentUser, wallet_in: WalletCreate |
| 29 | +) -> WalletPublic: |
| 30 | + """Create a wallet for the current user in the given currency. |
| 31 | +
|
| 32 | + Rules: |
| 33 | + - Max 3 wallets per user |
| 34 | + - One wallet per currency |
| 35 | + - Balance starts at 0.00 |
| 36 | + """ |
| 37 | + count_stmt = ( |
| 38 | + select(func.count()) |
| 39 | + .select_from(Wallet) |
| 40 | + .where(Wallet.user_id == current_user.id) |
| 41 | + ) |
| 42 | + current_count = session.exec(count_stmt).one() |
| 43 | + if current_count >= 3: |
| 44 | + raise HTTPException( |
| 45 | + status_code=BAD_REQUEST_CODE, detail="User wallet limit reached" |
| 46 | + ) |
| 47 | + |
| 48 | + existing_stmt = select(Wallet).where( |
| 49 | + Wallet.user_id == current_user.id, Wallet.currency == wallet_in.currency |
| 50 | + ) |
| 51 | + if session.exec(existing_stmt).first(): |
| 52 | + raise HTTPException( |
| 53 | + status_code=CONFLICT_CODE, detail="Wallet for this currency already exists" |
| 54 | + ) |
| 55 | + |
| 56 | + db_wallet = Wallet( |
| 57 | + user_id=current_user.id, |
| 58 | + currency=wallet_in.currency, |
| 59 | + balance=Decimal("0.00"), |
| 60 | + ) |
| 61 | + session.add(db_wallet) |
| 62 | + session.commit() |
| 63 | + session.refresh(db_wallet) |
| 64 | + return WalletPublic.model_validate(db_wallet) |
| 65 | + |
| 66 | + |
| 67 | +@router.get("/{wallet_id}") |
| 68 | +def read_wallet( |
| 69 | + *, session: SessionDep, current_user: CurrentUser, wallet_id: uuid.UUID |
| 70 | +) -> WalletPublic: |
| 71 | + db_wallet = session.get(Wallet, wallet_id) |
| 72 | + if not db_wallet: |
| 73 | + raise HTTPException(status_code=NOT_FOUND_CODE, detail="Wallet not found") |
| 74 | + if not current_user.is_superuser and db_wallet.user_id != current_user.id: |
| 75 | + raise HTTPException( |
| 76 | + status_code=BAD_REQUEST_CODE, detail="Not enough permissions" |
| 77 | + ) |
| 78 | + return WalletPublic.model_validate(db_wallet) |
| 79 | + |
| 80 | + |
| 81 | +@router.post("/{wallet_id}/transactions") |
| 82 | +def create_transaction( |
| 83 | + *, |
| 84 | + session: SessionDep, |
| 85 | + current_user: CurrentUser, |
| 86 | + wallet_id: uuid.UUID, |
| 87 | + txn_in: TransactionCreate, |
| 88 | +) -> TransactionPublic: |
| 89 | + """Create a credit/debit transaction on a wallet with currency conversion and fees. |
| 90 | +
|
| 91 | + - Credit: add to balance |
| 92 | + - Debit: subtract from balance, cannot go negative |
| 93 | + - If txn currency != wallet currency: convert and apply fee (on converted amount) |
| 94 | + """ |
| 95 | + db_wallet = session.get(Wallet, wallet_id) |
| 96 | + if not db_wallet: |
| 97 | + raise HTTPException(status_code=NOT_FOUND_CODE, detail="Wallet not found") |
| 98 | + if not current_user.is_superuser and db_wallet.user_id != current_user.id: |
| 99 | + raise HTTPException( |
| 100 | + status_code=BAD_REQUEST_CODE, detail="Not enough permissions" |
| 101 | + ) |
| 102 | + |
| 103 | + # Normalize amount to 2 decimals |
| 104 | + amount = quantize_money(Decimal(txn_in.amount)) |
| 105 | + if amount <= 0: |
| 106 | + raise HTTPException( |
| 107 | + status_code=BAD_REQUEST_CODE, detail="Amount must be positive" |
| 108 | + ) |
| 109 | + |
| 110 | + # Convert if currencies differ |
| 111 | + cross = txn_in.currency != db_wallet.currency |
| 112 | + effective_amount = ( |
| 113 | + convert( |
| 114 | + amount, cast(Currency, txn_in.currency), cast(Currency, db_wallet.currency) |
| 115 | + ) |
| 116 | + if cross |
| 117 | + else amount |
| 118 | + ) |
| 119 | + effective_amount = apply_fee(effective_amount, cross_currency=cross) |
| 120 | + |
| 121 | + new_balance = Decimal(db_wallet.balance) |
| 122 | + if txn_in.type == "credit": |
| 123 | + new_balance = quantize_money(new_balance + effective_amount) |
| 124 | + else: # debit |
| 125 | + if new_balance - effective_amount < Decimal("0.00"): |
| 126 | + raise HTTPException( |
| 127 | + status_code=BAD_REQUEST_CODE, |
| 128 | + detail="Insufficient funds", |
| 129 | + ) |
| 130 | + new_balance = quantize_money(new_balance - effective_amount) |
| 131 | + |
| 132 | + # Persist transaction and update balance atomically |
| 133 | + db_txn = Transaction( |
| 134 | + wallet_id=db_wallet.id, |
| 135 | + amount=amount, # store original amount in original currency for audit |
| 136 | + type=txn_in.type, |
| 137 | + currency=txn_in.currency, |
| 138 | + ) |
| 139 | + db_wallet.balance = new_balance |
| 140 | + session.add(db_txn) |
| 141 | + session.add(db_wallet) |
| 142 | + session.commit() |
| 143 | + session.refresh(db_txn) |
| 144 | + return TransactionPublic.model_validate(db_txn) |
0 commit comments