-
-
Notifications
You must be signed in to change notification settings - Fork 0
No-Tuning GPT Copilot #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
""" | ||
Add wallet and transaction tables. | ||
|
||
Revision ID: 20250915_add_wallets_transactions | ||
Revises: 1a31ce608336 | ||
Create Date: 2025-09-15 | ||
|
||
""" | ||
|
||
import sqlalchemy as sa | ||
from alembic import op | ||
from sqlalchemy.dialects import postgresql | ||
|
||
# revision identifiers, used by Alembic. | ||
revision = "20250915_add_wallets_transactions" | ||
down_revision = "1a31ce608336" | ||
branch_labels: str | None = None | ||
depends_on: str | None = None | ||
|
||
|
||
def upgrade() -> None: | ||
op.create_table( | ||
"wallet", | ||
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False), | ||
sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False), | ||
sa.Column("currency", sa.String(length=255), nullable=False), | ||
sa.Column("balance", sa.Numeric(18, 2), nullable=False, server_default="0.00"), | ||
sa.ForeignKeyConstraint(["user_id"], ["user.id"], ondelete="CASCADE"), | ||
sa.PrimaryKeyConstraint("id"), | ||
sa.UniqueConstraint("user_id", "currency", name="uq_wallet_user_currency"), | ||
) | ||
|
||
transaction_type = sa.Enum("credit", "debit", name="transaction_type") | ||
transaction_type.create(op.get_bind(), checkfirst=True) | ||
|
||
op.create_table( | ||
"transaction", | ||
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False), | ||
sa.Column("wallet_id", postgresql.UUID(as_uuid=True), nullable=False), | ||
sa.Column("amount", sa.Numeric(18, 2), nullable=False), | ||
sa.Column("type", transaction_type, nullable=False), | ||
sa.Column( | ||
"timestamp", | ||
sa.DateTime(timezone=True), | ||
nullable=False, | ||
server_default=sa.text("now()"), | ||
), | ||
sa.Column("currency", sa.String(length=255), nullable=False), | ||
sa.ForeignKeyConstraint(["wallet_id"], ["wallet.id"], ondelete="CASCADE"), | ||
sa.PrimaryKeyConstraint("id"), | ||
) | ||
|
||
|
||
def downgrade() -> None: | ||
op.drop_table("transaction") | ||
op.drop_table("wallet") | ||
sa.Enum(name="transaction_type").drop(op.get_bind(), checkfirst=True) |
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,144 @@ | ||||||||||||||||||||||||||||||
"""Wallet and Transaction management endpoints.""" | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
import uuid | ||||||||||||||||||||||||||||||
from decimal import Decimal | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
from fastapi import APIRouter, HTTPException | ||||||||||||||||||||||||||||||
from sqlmodel import func, select | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
from app.api.deps import CurrentUser, SessionDep | ||||||||||||||||||||||||||||||
from app.constants import BAD_REQUEST_CODE, CONFLICT_CODE, NOT_FOUND_CODE | ||||||||||||||||||||||||||||||
from typing import cast | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
from app.core.currency import Currency, apply_fee, convert, quantize_money | ||||||||||||||||||||||||||||||
from app.models import ( | ||||||||||||||||||||||||||||||
Transaction, | ||||||||||||||||||||||||||||||
TransactionCreate, | ||||||||||||||||||||||||||||||
TransactionPublic, | ||||||||||||||||||||||||||||||
Wallet, | ||||||||||||||||||||||||||||||
WalletCreate, | ||||||||||||||||||||||||||||||
WalletPublic, | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
router = APIRouter(prefix="/wallets", tags=["wallets"]) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
@router.post("/") | ||||||||||||||||||||||||||||||
def create_wallet( | ||||||||||||||||||||||||||||||
*, session: SessionDep, current_user: CurrentUser, wallet_in: WalletCreate | ||||||||||||||||||||||||||||||
) -> WalletPublic: | ||||||||||||||||||||||||||||||
"""Create a wallet for the current user in the given currency. | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
Rules: | ||||||||||||||||||||||||||||||
- Max 3 wallets per user | ||||||||||||||||||||||||||||||
- One wallet per currency | ||||||||||||||||||||||||||||||
- Balance starts at 0.00 | ||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||
count_stmt = ( | ||||||||||||||||||||||||||||||
select(func.count()) | ||||||||||||||||||||||||||||||
.select_from(Wallet) | ||||||||||||||||||||||||||||||
.where(Wallet.user_id == current_user.id) | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
current_count = session.exec(count_stmt).one() | ||||||||||||||||||||||||||||||
if current_count >= 3: | ||||||||||||||||||||||||||||||
raise HTTPException( | ||||||||||||||||||||||||||||||
status_code=BAD_REQUEST_CODE, detail="User wallet limit reached" | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
existing_stmt = select(Wallet).where( | ||||||||||||||||||||||||||||||
Wallet.user_id == current_user.id, Wallet.currency == wallet_in.currency | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
if session.exec(existing_stmt).first(): | ||||||||||||||||||||||||||||||
raise HTTPException( | ||||||||||||||||||||||||||||||
status_code=CONFLICT_CODE, detail="Wallet for this currency already exists" | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
db_wallet = Wallet( | ||||||||||||||||||||||||||||||
user_id=current_user.id, | ||||||||||||||||||||||||||||||
currency=wallet_in.currency, | ||||||||||||||||||||||||||||||
balance=Decimal("0.00"), | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
session.add(db_wallet) | ||||||||||||||||||||||||||||||
session.commit() | ||||||||||||||||||||||||||||||
session.refresh(db_wallet) | ||||||||||||||||||||||||||||||
return WalletPublic.model_validate(db_wallet) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
@router.get("/{wallet_id}") | ||||||||||||||||||||||||||||||
def read_wallet( | ||||||||||||||||||||||||||||||
*, session: SessionDep, current_user: CurrentUser, wallet_id: uuid.UUID | ||||||||||||||||||||||||||||||
) -> WalletPublic: | ||||||||||||||||||||||||||||||
db_wallet = session.get(Wallet, wallet_id) | ||||||||||||||||||||||||||||||
if not db_wallet: | ||||||||||||||||||||||||||||||
raise HTTPException(status_code=NOT_FOUND_CODE, detail="Wallet not found") | ||||||||||||||||||||||||||||||
if not current_user.is_superuser and db_wallet.user_id != current_user.id: | ||||||||||||||||||||||||||||||
raise HTTPException( | ||||||||||||||||||||||||||||||
status_code=BAD_REQUEST_CODE, detail="Not enough permissions" | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
return WalletPublic.model_validate(db_wallet) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
@router.post("/{wallet_id}/transactions") | ||||||||||||||||||||||||||||||
def create_transaction( | ||||||||||||||||||||||||||||||
*, | ||||||||||||||||||||||||||||||
session: SessionDep, | ||||||||||||||||||||||||||||||
current_user: CurrentUser, | ||||||||||||||||||||||||||||||
wallet_id: uuid.UUID, | ||||||||||||||||||||||||||||||
txn_in: TransactionCreate, | ||||||||||||||||||||||||||||||
) -> TransactionPublic: | ||||||||||||||||||||||||||||||
"""Create a credit/debit transaction on a wallet with currency conversion and fees. | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
- Credit: add to balance | ||||||||||||||||||||||||||||||
- Debit: subtract from balance, cannot go negative | ||||||||||||||||||||||||||||||
- If txn currency != wallet currency: convert and apply fee (on converted amount) | ||||||||||||||||||||||||||||||
""" | ||||||||||||||||||||||||||||||
db_wallet = session.get(Wallet, wallet_id) | ||||||||||||||||||||||||||||||
if not db_wallet: | ||||||||||||||||||||||||||||||
raise HTTPException(status_code=NOT_FOUND_CODE, detail="Wallet not found") | ||||||||||||||||||||||||||||||
if not current_user.is_superuser and db_wallet.user_id != current_user.id: | ||||||||||||||||||||||||||||||
raise HTTPException( | ||||||||||||||||||||||||||||||
status_code=BAD_REQUEST_CODE, detail="Not enough permissions" | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
# Normalize amount to 2 decimals | ||||||||||||||||||||||||||||||
amount = quantize_money(Decimal(txn_in.amount)) | ||||||||||||||||||||||||||||||
if amount <= 0: | ||||||||||||||||||||||||||||||
raise HTTPException( | ||||||||||||||||||||||||||||||
status_code=BAD_REQUEST_CODE, detail="Amount must be positive" | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
# Convert if currencies differ | ||||||||||||||||||||||||||||||
cross = txn_in.currency != db_wallet.currency | ||||||||||||||||||||||||||||||
effective_amount = ( | ||||||||||||||||||||||||||||||
convert( | ||||||||||||||||||||||||||||||
amount, cast(Currency, txn_in.currency), cast(Currency, db_wallet.currency) | ||||||||||||||||||||||||||||||
Comment on lines
+112
to
+114
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Using cast() to force type compatibility suggests a potential type safety issue. Consider validating that txn_in.currency and db_wallet.currency are valid Currency values before conversion, or redesign the type system to ensure type safety without casting.
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
if cross | ||||||||||||||||||||||||||||||
else amount | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
effective_amount = apply_fee(effective_amount, cross_currency=cross) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
new_balance = Decimal(db_wallet.balance) | ||||||||||||||||||||||||||||||
if txn_in.type == "credit": | ||||||||||||||||||||||||||||||
new_balance = quantize_money(new_balance + effective_amount) | ||||||||||||||||||||||||||||||
else: # debit | ||||||||||||||||||||||||||||||
if new_balance - effective_amount < Decimal("0.00"): | ||||||||||||||||||||||||||||||
raise HTTPException( | ||||||||||||||||||||||||||||||
status_code=BAD_REQUEST_CODE, | ||||||||||||||||||||||||||||||
detail="Insufficient funds", | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
new_balance = quantize_money(new_balance - effective_amount) | ||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||
# Persist transaction and update balance atomically | ||||||||||||||||||||||||||||||
db_txn = Transaction( | ||||||||||||||||||||||||||||||
wallet_id=db_wallet.id, | ||||||||||||||||||||||||||||||
amount=amount, # store original amount in original currency for audit | ||||||||||||||||||||||||||||||
type=txn_in.type, | ||||||||||||||||||||||||||||||
currency=txn_in.currency, | ||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||
db_wallet.balance = new_balance | ||||||||||||||||||||||||||||||
session.add(db_txn) | ||||||||||||||||||||||||||||||
session.add(db_wallet) | ||||||||||||||||||||||||||||||
session.commit() | ||||||||||||||||||||||||||||||
session.refresh(db_txn) | ||||||||||||||||||||||||||||||
return TransactionPublic.model_validate(db_txn) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
"""Currency conversion utilities with fixed exchange rates and fees.""" | ||
|
||
from decimal import ROUND_HALF_UP, Decimal | ||
from typing import Literal | ||
|
||
Currency = Literal["USD", "EUR", "RUB"] | ||
|
||
# Fixed exchange rates relative to USD for simplicity | ||
RATES: dict[tuple[Currency, Currency], Decimal] = { | ||
("USD", "USD"): Decimal("1.0"), | ||
("USD", "EUR"): Decimal("0.90"), | ||
("USD", "RUB"): Decimal("90.0"), | ||
("EUR", "USD"): Decimal("1.1111111111"), # 1/0.90 | ||
("EUR", "EUR"): Decimal("1.0"), | ||
("EUR", "RUB"): Decimal("100.0"), | ||
("RUB", "USD"): Decimal("0.011"), | ||
("RUB", "EUR"): Decimal("0.010"), | ||
("RUB", "RUB"): Decimal("1.0"), | ||
} | ||
|
||
FEE_RATE = Decimal("0.01") # 1% fee on cross-currency operations | ||
|
||
|
||
def quantize_money(value: Decimal) -> Decimal: | ||
"""Quantize Decimal to two places using bankers' rounding policy.""" | ||
return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) | ||
|
||
|
||
def convert(amount: Decimal, from_currency: Currency, to_currency: Currency) -> Decimal: | ||
"""Convert amount between currencies using fixed rates, quantized to 2 decimals.""" | ||
rate = RATES[(from_currency, to_currency)] | ||
return quantize_money(amount * rate) | ||
|
||
|
||
def apply_fee(amount: Decimal, *, cross_currency: bool) -> Decimal: | ||
"""Apply a percentage fee if cross-currency conversion is used.""" | ||
if not cross_currency: | ||
return quantize_money(amount) | ||
fee = quantize_money(amount * FEE_RATE) | ||
return quantize_money(amount - fee) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] The typing import should be grouped with other standard library imports at the top. Move this import to line 4 with the other imports from the typing module.
Copilot uses AI. Check for mistakes.