Compare commits

..

No commits in common. "d4cd100ba0f518a8edd1782ae7332ef6eb144817" and "71a3982513dd9b0e726ab9e597a7402a91c052b0" have entirely different histories.

5 changed files with 30 additions and 34 deletions

View file

@ -286,26 +286,26 @@ async def get_match_by_index(sport_alias: str, index: int) -> dict | None:
return None
def place_bet(user_id: int, match: dict, sport: str, chosen_team: str, amount: float) -> tuple[bool, str]:
def place_bet(user_id: int, match: dict, sport: str, chosen_team: str, amount: float) -> str:
current = get_user_length(user_id)
if current is None:
return False, "Сначала заведи счёт через /penis, братуха."
return "Сначала заведи счёт через /penis, братуха."
if current <= 0:
return False, "🚫 С кредитом ставки не принимаем."
return "🚫 С кредитом ставки не принимаем."
if amount <= 0:
return False, "Ставка должна быть больше нуля."
return "Ставка должна быть больше нуля."
if amount > config.BET_MAX_AMOUNT:
return False, f"Максимальная ставка — {config.BET_MAX_AMOUNT} см."
if round(amount, 2) > round(current, 2):
return False, f"У тебя {current:.1f} см, а ставишь {amount:.1f}. Не хватает, фраер."
return f"Максимальная ставка — {config.BET_MAX_AMOUNT} см."
if amount > current:
return f"У тебя {current:.1f} см, а ставишь {amount:.1f}. Не хватает, фраер."
team_odds = match["odds"].get(chosen_team)
if team_odds is None:
return False, f"Исход не найден. Доступные: {describe_match_outcomes(match)}"
return f"Исход не найден. Доступные: {describe_match_outcomes(match)}"
new_length = update_user_length(user_id, -amount)
if new_length is None:
return False, "Ошибка БД."
return "Ошибка БД."
now_ts = int(_time.time())
try:
@ -323,11 +323,12 @@ def place_bet(user_id: int, match: dict, sport: str, chosen_team: str, amount: f
except psycopg2.Error:
logger.exception("Failed to place bet")
update_user_length(user_id, amount)
return False, "Ошибка БД."
return "Ошибка БД."
potential = round(amount * team_odds, 1)
return True, (
return (
f"✅ Ставка принята!\n"
f"🏟 {match['home']} vs {match['away']}\n"
f"📌 {chosen_team} (x{team_odds:.2f})\n"
f"💰 Ставка: {amount:.1f} см\n"
f"🎯 Возможный выигрыш: {potential:.1f} см\n"

View file

@ -75,7 +75,7 @@ def play_casino(user_id: int, bet: float) -> str:
return f"Максимальная ставка — {config.CASINO_MAX_BET} см, не жадничай."
if bet <= 0:
return "Ставка должна быть больше нуля, фраер."
if round(bet, 2) > round(current, 2):
if bet > current:
return f"У тебя {current:.1f} см, а ставишь {bet:.1f}. Столько нет, фраер."
reels, matches = spin_slots()

View file

@ -179,8 +179,7 @@ class EconomyManager:
return False
from_balance = self.get_user_balance(from_user_id)
limit = round(from_balance * 0.2, 2)
if round(amount, 2) > limit or round(from_balance, 2) < round(amount, 2):
if amount > from_balance * 0.2 or from_balance < amount:
return False
with get_conn() as conn:
@ -202,17 +201,15 @@ class EconomyManager:
logger.info(f"Transfer: {amount} from user {from_user_id} to user {to_user_id}")
return True
def create_deposit(self, user_id: int, amount: float, days: int) -> tuple[bool, str]:
def create_deposit(self, user_id: int, amount: float, days: int) -> bool:
if amount <= 0:
return False, "Сумма вклада должна быть больше нуля."
return False
balance = self.get_user_balance(user_id)
min_deposit = float(self.get_setting('deposit_min_amount'))
if round(amount, 2) < round(min_deposit, 2):
return False, f"Минимальная сумма вклада — {min_deposit:.1f} см. Твой баланс: {balance:.1f} см."
if round(balance, 2) < round(amount, 2):
return False, f"Недостаточно средств. Твой баланс: {balance:.1f} см, а сумма вклада: {amount:.1f} см."
if amount < min_deposit or balance < amount:
return False
central_bank_rate = float(self.get_setting('central_bank_rate'))
matures_at = datetime.now() + timedelta(days=days)
@ -233,7 +230,7 @@ class EconomyManager:
''', (user_id, amount, central_bank_rate, matures_at))
logger.info(f"Deposit created: user {user_id}, amount {amount}, rate {central_bank_rate}%")
return True, "Вклад успешно открыт!"
return True
def create_loan(self, user_id: int, amount: float, days: int) -> bool:
if amount <= 0:
@ -242,7 +239,7 @@ class EconomyManager:
max_loan = float(self.get_setting('loan_max_amount'))
loan_rate = float(self.get_setting('loan_interest_rate'))
if round(amount, 2) > round(max_loan, 2):
if amount > max_loan:
return False
with get_conn() as conn:
@ -254,13 +251,13 @@ class EconomyManager:
(user_id,),
)
outstanding = float(cur.fetchone()['total'])
if round(outstanding + amount, 2) > round(max_loan, 2):
if outstanding + amount > max_loan:
return False
# ЦБ должен иметь достаточно капитала
cur.execute("SELECT capital FROM central_bank WHERE id=1")
cb_capital = float(cur.fetchone()['capital'])
if round(cb_capital, 2) < round(amount, 2):
if cb_capital < amount:
return False
due_at = datetime.now() + timedelta(days=days)
@ -296,10 +293,10 @@ class EconomyManager:
if not loan or loan['is_repaid']:
return False
total_repayment = round(loan['amount'] * (1 + loan['interest_rate'] / 100), 2)
total_repayment = loan['amount'] * (1 + loan['interest_rate'] / 100)
balance = self.get_user_balance(user_id)
if round(balance, 2) < total_repayment:
if balance < total_repayment:
return False
wcur = conn.cursor()
@ -482,7 +479,7 @@ class EconomyManager:
logger.info(f"Central bank updated: {capital_change} ({transaction_type})")
def emit_money(self, amount: float, reason: str = "") -> bool:
if round(self.get_central_bank_stats()['capital'], 2) < round(amount, 2):
if self.get_central_bank_stats()['capital'] < amount:
return False
self.update_central_bank(-amount, 'emission', reason)
logger.info(f"Money emitted: {amount} cm ({reason})")

View file

@ -1263,12 +1263,12 @@ async def handle_deposit_cmd(message: Message):
await message.reply("Сумма и дни должны быть положительными.", parse_mode=None)
return
success, error_msg = await asyncio.to_thread(economy.create_deposit, message.from_user.id, amount, days)
success = await asyncio.to_thread(economy.create_deposit, message.from_user.id, amount, days)
if success:
rate = economy.get_setting('central_bank_rate')
await message.reply(f"✅ Вклад открыт!\n💰 Сумма: {amount:.1f} см\n📅 Срок: {days} дней\n📈 Ставка: {rate}% годовых", parse_mode=None)
else:
await message.reply(f"Не удалось открыть вклад. {error_msg}", parse_mode=None)
await message.reply("Не удалось открыть вклад. Проверь баланс и минимальную сумму.", parse_mode=None)
async def handle_loans_cmd(message: Message):
"""Показать кредиты"""
@ -1562,7 +1562,7 @@ async def handle_bet_cmd(message: Message):
)
return
success, result = await asyncio.to_thread(place_bet, message.from_user.id, match, sport_alias, team, amount)
result = await asyncio.to_thread(place_bet, message.from_user.id, match, sport_alias, team, amount)
await message.reply(result, parse_mode=None)
async def handle_mybets_cmd(message: Message):

View file

@ -253,9 +253,7 @@ async def create_bet(
raise HTTPException(status_code=400, detail="Неверный исход ставки")
# 3. Разместить ставку (синхронная функция)
success, result = await asyncio.to_thread(place_bet, user_id, match, req.league, team, req.amount)
if not success:
raise HTTPException(status_code=400, detail=result)
result = await asyncio.to_thread(place_bet, user_id, match, req.league, team, req.amount)
return {"message": result}
@ -296,7 +294,7 @@ async def play_casino_api(
raise HTTPException(status_code=400, detail=f"Макс ставка: {config.CASINO_MAX_BET} см")
if req.bet <= 0:
raise HTTPException(status_code=400, detail="Ставка > 0")
if round(req.bet, 2) > round(current, 2):
if req.bet > current:
raise HTTPException(status_code=400, detail=f"У тебя {current:.1f} см")
reels, match_count = await asyncio.to_thread(spin_slots)