Merge pull request #9 from xpack-ai/feature/0.3-backend

Support manual addition of balance
This commit is contained in:
Dot.L authored and GitHub committed 2025-07-28 16:40:27 +08:00
commit d3efa08da2
5 files changed
+296 -33

No files matched your search

@@ -1,16 +1,15 @@
from fastapi import APIRouter, Query
from typing import Optional
from pydantic import BaseModel
from fastapi import APIRouter, Query, Body, Request
from sqlalchemy.orm import Session
from fastapi import Depends
from services.admin_service.services.user_service import UserService
from services.admin_service.services.user_wallet_service import UserWalletService
from services.common.database import get_db
from services.common.models.user import User
from services.common.response.user_manager_response import UserManagerResponse
from services.common.utils.response_utils import ResponseUtils
from services.common.utils.validation_utils import ValidationUtils
from services.common.logging_config import get_logger
import json,hashlib
from services.admin_service.services.payment_service import PaymentService
logger = get_logger(__name__)
@@ -24,6 +23,9 @@ def get_user_wallet_service(db: Session = Depends(get_db)) -> UserWalletService:
def get_user_service(db: Session = Depends(get_db)) -> UserService:
return UserService(db)
def get_payment_service(db: Session = Depends(get_db)) -> PaymentService:
return PaymentService(db)
@router.delete("/account", summary="Delete user account")
async def delete_user(
@@ -77,3 +79,35 @@ async def get_user_list(
user_list.append({"id": user.id, "email": user.email, "created_at": user.created_at, "balance": wallet.balance if wallet else 0})
return ResponseUtils.success_page(data=user_list, total=total, page_num=page, page_size=page_size)
@router.post("/balance/recharge")
async def recharge_balance(
request: Request,
payment_service: PaymentService = Depends(get_payment_service),
):
body = await request.body()
body_str = body.decode('utf-8')
timestamp=request.headers.get("x-xpack-timestamp")
sign = request.headers.get("x-xpack-sign")
# calculate md5 hash of the body and timestamp
md5_hash = hashlib.md5(f"{timestamp}{body_str}".encode('utf-8')).hexdigest()
calculated_sign = hashlib.sha256(md5_hash.encode('utf-8')).hexdigest()
print(f"sign: {sign}, calculated_sign: {calculated_sign},md5_hash: {md5_hash}")
if sign != calculated_sign:
return ResponseUtils.error(message="Invalid signature")
try:
body_str = body_str.replace("'", '"') # Ensure JSON format
body = json.loads(body_str)
except json.JSONDecodeError:
return ResponseUtils.error(message="Invalid JSON format")
user_id = body.get("user_id")
balance = body.get("balance")
typ = body.get("type")
transaction_id = hashlib.md5(f"{timestamp}{user_id}{balance}{typ}".encode('utf-8')).hexdigest()
if payment_service.check_transaction_id_exists(transaction_id):
return ResponseUtils.error(message="Transaction ID already exists")
success = payment_service.platform_payment(user_id=user_id, amount=balance, typ=typ, transaction_id=transaction_id)
if not success:
return ResponseUtils.error(message="Failed to recharge wallet balance")
return ResponseUtils.success(message="Wallet recharge successful")
@@ -19,7 +19,7 @@ class UserWalletHistoryRepository:
def __init__(self, db: Session):
self.db = db
def add_deposit(self, user_id: str, amount: float, payment_method: str) -> UserWalletHistory:
def add_deposit(self, user_id: str, amount: float, payment_method: str, transaction_id: str = "", status: int = 0) -> UserWalletHistory:
"""
Create a new deposit record.
@@ -27,21 +27,83 @@ class UserWalletHistoryRepository:
user_id: User ID
amount: Deposit amount
payment_method: Payment method
transaction_id: Transaction ID from payment platform, optional
status: Transaction status (0=new, 1=completed, 2=refunded), default is 0
Returns:
UserWalletHistory: Created deposit record
"""
now = datetime.now(timezone.utc)
if transaction_id == "":
transaction_id = str(uuid4())
history = UserWalletHistory(
id=transaction_id,
user_id=user_id,
payment_method=PaymentMethod(payment_method),
amount=amount,
balance_after=0.00,
type=TransactionType.DEPOSIT,
status=status,
created_at=now,
updated_at=now,
)
self.db.add(history)
self.db.commit()
self.db.refresh(history)
return history
def add_withdrawal(self, user_id: str, amount: float, payment_method: str) -> UserWalletHistory:
"""
Create a new withdrawal/consume record.
Args:
user_id: User ID
amount: Withdrawal amount (positive value)
payment_method: Payment method
Returns:
UserWalletHistory: Created withdrawal record
"""
now = datetime.now(timezone.utc)
history = UserWalletHistory(
id=str(uuid4()),
user_id=user_id,
payment_method=PaymentMethod(payment_method),
amount=amount, # Store as positive value
balance_after=0.00,
type=TransactionType.CONSUME,
status=1, # Mark as completed immediately for platform withdrawals
created_at=now,
updated_at=now,
)
self.db.add(history)
self.db.commit()
self.db.refresh(history)
return history
def set_balance(self,user_id: str,amount:float, payment_method: str, transaction_id: str = "", status: int = 0) -> UserWalletHistory:
"""
Create a new balance record.
Args:
user_id: User ID
amount: Balance amount
payment_method: Payment method
transaction_id: Transaction ID from payment platform, optional
status: Status of the transaction (0=new, 1=completed, 2=refunded)
Returns:
UserWalletHistory: Created balance record
"""
now = datetime.now(timezone.utc)
if transaction_id == "":
transaction_id = str(uuid4())
history = UserWalletHistory(
id=transaction_id,
user_id=user_id,
payment_method=PaymentMethod(payment_method),
amount=amount,
balance_after=0.00,
type=TransactionType.DEPOSIT,
status=0,
transaction_id=None,
channel_user_id=None,
type=TransactionType.RESET,
status=status, # 0=new, 1=completed, 2=refunded
created_at=now,
updated_at=now,
)
@@ -3,6 +3,7 @@ import secrets
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy.orm import Session
from sqlalchemy import text
from services.common.models.user_wallet import UserWallet
@@ -27,11 +28,46 @@ class UserWalletRepository:
def get_by_user_id(self, user_id: str) -> Optional[UserWallet]:
return self.db.query(UserWallet).filter(UserWallet.user_id == user_id).first()
def get_by_user_id_with_lock(self, user_id: str) -> Optional[UserWallet]:
"""Get user wallet with row-level lock for update"""
return self.db.query(UserWallet).filter(UserWallet.user_id == user_id).with_for_update().first()
def update_balance(self, user_id: str, new_balance: float) -> bool:
"""Update user balance"""
wallet = self.get_by_user_id(user_id)
if wallet:
wallet.balance = new_balance
wallet.updated_at = datetime.now(timezone.utc)
self.db.commit()
return True
return False
def update_balance_atomic(self, user_id: str, new_balance: float, expected_balance: float) -> bool:
"""
Atomically update user balance with optimistic locking.
Args:
user_id: User ID
new_balance: New balance to set
expected_balance: Expected current balance (for optimistic locking)
Returns:
bool: True if update successful, False if balance was modified by another transaction
"""
try:
# Use ORM update with WHERE condition for optimistic locking
updated_rows = self.db.query(UserWallet).filter(
UserWallet.user_id == user_id,
UserWallet.balance == expected_balance
).update({
"balance": new_balance,
"updated_at": datetime.now(timezone.utc)
}, synchronize_session=False)
# Commit the transaction and check if any row was updated
self.db.commit()
return updated_rows > 0
except Exception as e:
self.db.rollback()
raise e
@@ -110,27 +110,157 @@ class PaymentService:
logger.info(f"Payment succeeded: payment_id={payment_id}, email={customer_email}, amount={amount} {currency}")
# Trigger fulfillment logic (example)
try:
return self.user_wallet_history_repository.deposit_complete(payment_id, payment_intent_id)
except Exception as e:
logger.error(f"Failed to fulfill order for payment_id={payment_id}: {str(e)}")
return False
# # Handle refund event
# elif event["type"] == "charge.refunded":
# charge = event["data"]["object"]
# payment_id = charge.get("payment_intent")
# amount_refunded = charge.get("amount_refunded") / 100 # Convert to actual amount
# currency = charge.get("currency")
# logging.info(f"Refund processed: payment_id={payment_id}, amount_refunded={amount_refunded} {currency}")
# # Trigger refund processing logic (example)
# try:
# # process_refund(payment_id, amount_refunded)
# logging.info(f"Refund processed for payment_id={payment_id}")
# except Exception as e:
# logging.error(f"Failed to process refund for payment_id={payment_id}: {str(e)}")
# return False
# try:
# return self.user_wallet_history_repository.deposit_complete(payment_id, payment_intent_id)
# except Exception as e:
# logger.error(f"Failed to fulfill order for payment_id={payment_id}: {str(e)}")
# return False
return self._add_wallet_balance(payment_id=payment_id, payment_channel_id=payment_intent_id)
return False
def check_transaction_id_exists(self, transaction_id: str) -> bool:
"""
Check if a transaction ID already exists in the user wallet history.
Args:
transaction_id (str): The transaction ID to check.
Returns:
bool: True if the transaction ID exists, False otherwise.
"""
return self.user_wallet_history_repository.get_by_id(transaction_id) is not None
def _add_wallet_balance(self, payment_id: str, payment_channel_id: str, max_retries: int = 3) -> bool:
history = self.user_wallet_history_repository.get_by_id(payment_id)
if history is None:
logger.error(f"Payment history not found for payment_id {payment_id}")
return False
if history.status == 1:
logger.warning(f"Payment history already completed for payment_id {payment_id}")
return True
user_id = history.user_id
amount = history.amount
user_wallet = self.user_wallet_repository.get_by_user_id(user_id)
if not user_wallet:
logger.error(f"User wallet not found for user_id {user_id}")
return False
# Retry mechanism for optimistic locking
for attempt in range(max_retries):
try:
# Get current wallet with row-level lock
current_wallet = self.user_wallet_repository.get_by_user_id_with_lock(user_id)
if not current_wallet:
logger.error(f"User wallet not found for user_id {user_id}")
return False
# Calculate new balance based on operation type
new_balance = current_wallet.balance + amount
# Atomic update with optimistic locking
success = self.user_wallet_repository.update_balance_atomic(
user_id=user_id,
new_balance=new_balance,
expected_balance=current_wallet.balance
)
if success:
# Create wallet history record after successful balance update
return self.user_wallet_history_repository.deposit_complete(payment_id,payment_channel_id)
else:
# Balance was modified by another transaction, retry
logger.warning(f"Balance conflict detected for user_id {user_id}, attempt {attempt + 1}")
continue
except Exception as e:
logger.error(f"Transaction failed for user_id {user_id}, attempt {attempt + 1}: {str(e)}")
if attempt == max_retries - 1:
logger.error(f"All retry attempts failed for user_id {user_id}")
return False
continue
logger.error(f"Failed to update balance after {max_retries} attempts for user_id {user_id}")
return False
def platform_payment(self, user_id: str, amount: float, transaction_id: str, typ: str = "incr", max_retries: int = 3) -> bool:
"""
Process platform payment for user wallet with high-concurrency transaction safety.
Args:
user_id (str): User ID
amount (float): Amount to add or reduce
transaction_id (str): Unique transaction ID for the operation
typ (str): Transaction type, "incr" for deposit, "reduce" for withdrawal, "set" for set balance
max_retries (int): Maximum retry attempts for optimistic locking
"""
if transaction_id == "":
logger.error("Transaction ID cannot be empty")
return False
if self.user_wallet_history_repository.get_by_id(transaction_id) is not None:
logger.error(f"Transaction ID {transaction_id} already exists")
return False
# Validate user wallet exists
user_wallet = self.user_wallet_repository.get_by_user_id(user_id)
if not user_wallet:
logger.error(f"User wallet not found for user_id {user_id}")
return False
# Retry mechanism for optimistic locking
for attempt in range(max_retries):
try:
# Get current wallet with row-level lock
current_wallet = self.user_wallet_repository.get_by_user_id_with_lock(user_id)
if not current_wallet:
logger.error(f"User wallet not found for user_id {user_id}")
return False
# Calculate new balance based on operation type
new_balance = current_wallet.balance
match typ:
case "incr":
new_balance = current_wallet.balance + amount
case "set":
new_balance = amount
case _:
logger.error(f"Invalid transaction type: {typ}")
return False
# Atomic update with optimistic locking
success = self.user_wallet_repository.update_balance_atomic(
user_id=user_id,
new_balance=new_balance,
expected_balance=current_wallet.balance
)
if success:
# Create wallet history record after successful balance update
try:
if typ == "incr":
self.user_wallet_history_repository.add_deposit(
user_id=user_id, amount=amount, payment_method="platform", transaction_id=transaction_id,status=1
)
elif typ == "set":
self.user_wallet_history_repository.set_balance(
user_id=user_id, amount=amount, payment_method="platform", transaction_id=transaction_id,status=1
)
logger.info(f"Successfully updated balance for user_id {user_id}: {current_wallet.balance} -> {new_balance}")
return True
except Exception as history_error:
logger.error(f"Failed to create wallet history for user_id {user_id}: {str(history_error)}")
# Balance was updated but history creation failed
# This is not critical for the balance update itself
return True
else:
# Balance was modified by another transaction, retry
logger.warning(f"Balance conflict detected for user_id {user_id}, attempt {attempt + 1}")
continue
except Exception as e:
logger.error(f"Transaction failed for user_id {user_id}, attempt {attempt + 1}: {str(e)}")
if attempt == max_retries - 1:
logger.error(f"All retry attempts failed for user_id {user_id}")
return False
continue
logger.error(f"Failed to update balance after {max_retries} attempts for user_id {user_id}")
return False
@@ -17,6 +17,7 @@ class TransactionType(PyEnum):
CONSUME = "consume"
REFUND = "refund"
API_CALL = "api_call"
RESET = "reset"
class UserWalletHistory(Base):