Initial commit: VPN Telegram bot (sanitized defaults)
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
"""Активация кода пополнения."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from services.db import Database
|
||||
from services.topup_codes import is_valid_code_format, normalize_code
|
||||
|
||||
|
||||
class TopupCodeError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TopupCodeRedeemResult:
|
||||
ok: bool
|
||||
message: str
|
||||
amount: float = 0.0
|
||||
balance: float = 0.0
|
||||
already: bool = False
|
||||
|
||||
|
||||
def redeem_topup_code(
|
||||
db: Database,
|
||||
*,
|
||||
telegram_id: int,
|
||||
raw_code: str,
|
||||
) -> TopupCodeRedeemResult:
|
||||
code = normalize_code(raw_code)
|
||||
if not is_valid_code_format(code):
|
||||
raise TopupCodeError("Некорректный формат кода (ожидается XXXX-XXXX-XXXX-XXXX)")
|
||||
|
||||
db.ensure_user(telegram_id)
|
||||
try:
|
||||
amount, already = db.redeem_topup_code(code=code, telegram_id=telegram_id)
|
||||
except ValueError as exc:
|
||||
raise TopupCodeError(str(exc)) from exc
|
||||
if already:
|
||||
balance = db.get_balance(telegram_id)
|
||||
return TopupCodeRedeemResult(
|
||||
ok=True,
|
||||
already=True,
|
||||
message="Этот код уже был использован.",
|
||||
amount=amount,
|
||||
balance=balance,
|
||||
)
|
||||
|
||||
balance = db.add_balance(
|
||||
telegram_id,
|
||||
amount,
|
||||
kind="code_topup",
|
||||
meta=f"code:{code}",
|
||||
)
|
||||
text = (
|
||||
f"✅ <b>Баланс пополнен по коду</b>\n\n"
|
||||
f"+{amount:.0f} ₽\n"
|
||||
f"Доступно: <b>{balance:.0f} ₽</b>"
|
||||
)
|
||||
return TopupCodeRedeemResult(
|
||||
ok=True,
|
||||
message=text,
|
||||
amount=amount,
|
||||
balance=balance,
|
||||
)
|
||||
Reference in New Issue
Block a user