Исправление точности вещественных чисел (Float Precision) при ставках, казино, переводах и вкладах #38

Merged
q merged 1 commit from Dan4ick/bot_tg:feature/FenyaBot into main 2026-07-11 17:56:01 +00:00
5 changed files with 34 additions and 30 deletions

View file

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

View file

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

View file

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