rmi-backend/app/domains/referral/core.py
cryptorugmunch 0a8c73d99b feat(domains): consolidate bulletin, intelligence, markets, admin, referral, mcp + mypy gate
- Make app/domains/auth/ and app/core/redis.py mypy-clean under strict.
- Add mypy-gate.ini and Makefile mypy-gate target; promote typecheck-gate in CI.
- Consolidate domains into app/domains/: bulletin, admin, intelligence, markets.
- Extract referral domain incl. DeFi partner DEX ref links; keep Telegram bot wired.
- Move app/mcp/ package and app/api/v1/mcp/router into app/domains/mcp/.
- Archive dead app/mcp_router.py.
2026-07-07 16:43:49 +07:00

77 lines
2.3 KiB
Python

"""Referral domain - Telegram bot referral system.
Phase 4 domain consolidation: extracted from telegram/rugmunchbot/bot.py.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
import sqlite3
REFERRAL_BONUS_SCANS = 5
MILESTONES = {5: "🥉", 10: "🥈", 25: "🥇", 50: "💎", 100: "👑"}
def apply_referral_code(
user_id: int,
ref_code: str,
user_referral_code: str | None,
referred_by: str | None,
conn: sqlite3.Connection,
) -> bool:
"""Apply a referral code for a new/existing user.
Returns True if the referral was successfully applied.
"""
if not ref_code or ref_code == user_referral_code or referred_by:
return False
referrer = conn.execute(
"SELECT user_id FROM users WHERE referral_code = ?", (ref_code,)
).fetchone()
if not referrer:
return False
conn.execute(
"UPDATE users SET referred_by = ?, bonus_scans = bonus_scans + ? WHERE user_id = ?",
(ref_code, REFERRAL_BONUS_SCANS, user_id),
)
conn.execute(
"UPDATE users SET bonus_scans = bonus_scans + ? WHERE user_id = ?",
(REFERRAL_BONUS_SCANS, referrer["user_id"]),
)
conn.commit()
return True
def get_referral_stats(user_id: int, referral_code: str, conn: sqlite3.Connection) -> dict[str, Any]:
"""Return referral stats for a user.
Includes total referrals, bonus scans earned, next milestone info, and share link.
"""
count_row = conn.execute(
"SELECT COUNT(*) as c FROM users WHERE referred_by = ?", (referral_code,)
).fetchone()
count = count_row["c"] if count_row else 0
next_ms = next((k for k in sorted(MILESTONES.keys()) if k > count), None)
ms_text = (
f"\n🎯 Next milestone: {MILESTONES[next_ms]} {next_ms} referrals"
if next_ms
else "\n👑 You've hit all milestones!"
)
return {
"user_id": user_id,
"referral_code": referral_code,
"count": count,
"bonus_earned": count * REFERRAL_BONUS_SCANS,
"next_milestone_text": ms_text,
}
def generate_referral_link(bot_username: str, referral_code: str) -> str:
"""Generate a Telegram referral start link."""
return f"https://t.me/{bot_username}?start=ref_{referral_code}"