hisham-cmd commited on
Commit
8bd2304
·
verified ·
1 Parent(s): c27aa86

Upload routers/payments.py

Browse files
Files changed (1) hide show
  1. routers/payments.py +68 -0
routers/payments.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlalchemy.future import select
4
+ from typing import List
5
+ from database.session import get_db
6
+ from database.models import Transaction as TransactionModel, User as UserModel
7
+ from auth import get_current_user
8
+ import schemas
9
+
10
+ router = APIRouter(
11
+ prefix="/payments",
12
+ tags=["payments"]
13
+ )
14
+
15
+ @router.post("/deposit", response_model=schemas.Transaction, status_code=status.HTTP_201_CREATED)
16
+ async def create_deposit(
17
+ transaction: schemas.TransactionCreate,
18
+ current_user: UserModel = Depends(get_current_user),
19
+ db: AsyncSession = Depends(get_db)
20
+ ):
21
+ """
22
+ Create a deposit transaction (simulate payment for now).
23
+ """
24
+ if transaction.amount <= 0:
25
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Amount must be positive")
26
+
27
+ balance_before = current_user.balance
28
+ balance_after = balance_before + transaction.amount
29
+
30
+ # Update user balance
31
+ current_user.balance = balance_after
32
+
33
+ # Create transaction record
34
+ new_txn = TransactionModel(
35
+ user_id=current_user.id,
36
+ amount=transaction.amount,
37
+ type="Deposit",
38
+ payment_method=transaction.payment_method,
39
+ status="Completed",
40
+ balance_before=balance_before,
41
+ balance_after=balance_after,
42
+ note=transaction.note
43
+ )
44
+
45
+ db.add(new_txn)
46
+ await db.commit()
47
+ await db.refresh(new_txn)
48
+
49
+ return new_txn
50
+
51
+ @router.get("/transactions", response_model=List[schemas.Transaction])
52
+ async def get_transactions(
53
+ skip: int = 0,
54
+ limit: int = 100,
55
+ current_user: UserModel = Depends(get_current_user),
56
+ db: AsyncSession = Depends(get_db)
57
+ ):
58
+ """
59
+ Get user's transactions.
60
+ """
61
+ result = await db.execute(
62
+ select(TransactionModel)
63
+ .where(TransactionModel.user_id == current_user.id)
64
+ .order_by(TransactionModel.created_at.desc())
65
+ .offset(skip)
66
+ .limit(limit)
67
+ )
68
+ return result.scalars().all()