-
-
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
Open
vodkar
wants to merge
3
commits into
master
Choose a base branch
from
copilot-task-no-tuning
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+645
−69
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
57 changes: 57 additions & 0 deletions
57
backend/app/alembic/versions/20250915_add_wallets_transactions.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
|
||||||||||||||||||||||||||||||
| effective_amount = ( | |
| convert( | |
| amount, cast(Currency, txn_in.currency), cast(Currency, db_wallet.currency) | |
| try: | |
| txn_currency = Currency(txn_in.currency) | |
| wallet_currency = Currency(db_wallet.currency) | |
| except ValueError: | |
| raise HTTPException( | |
| status_code=BAD_REQUEST_CODE, | |
| detail="Invalid currency value" | |
| ) | |
| effective_amount = ( | |
| convert( | |
| amount, txn_currency, wallet_currency |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.