Spaces:
Sleeping
Sleeping
Pedot
Fix: SenangPay HMAC-SHA256 hash, admin unlimited quota, promo 3 resumes/30days, upgrade button always visible, required name/email params
19315b9 Download database/db.py from Tengkolok/resume-bot: direct link, hf CLI and curl.
- Browser
- Download file 8.77 kB
-
https://huggingface.co/spaces/Tengkolok/resume-bot/resolve/main/database/db.py
- Command line
-
hf download hf://spaces/Tengkolok/resume-bot/database/db.py
-
curl -L -o db.py https://huggingface.co/spaces/Tengkolok/resume-bot/resolve/main/database/db.py
8.77 kB
| import os | |
| import sqlite3 | |
| from datetime import datetime, timedelta | |
| DB_PATH = os.path.join(os.path.dirname(__file__), "..", "resumeforge.db") | |
| def get_conn(): | |
| """Bug #5 fix: return connection for context manager usage.""" | |
| return sqlite3.connect(DB_PATH) | |
| def init_db(): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute(""" | |
| CREATE TABLE IF NOT EXISTS users ( | |
| telegram_id TEXT PRIMARY KEY, | |
| username TEXT, | |
| full_name TEXT, | |
| tier TEXT DEFAULT 'free', | |
| resumes_used INTEGER DEFAULT 0, | |
| resumes_limit INTEGER DEFAULT 1, | |
| sub_expires_at TEXT, | |
| language TEXT DEFAULT 'en', | |
| created_at TEXT DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| c.execute(""" | |
| CREATE TABLE IF NOT EXISTS pending_payments ( | |
| ref_code TEXT PRIMARY KEY, | |
| telegram_id TEXT, | |
| plan TEXT, | |
| amount REAL, | |
| status TEXT DEFAULT 'pending', | |
| file_id TEXT, | |
| file_type TEXT, | |
| transaction_id TEXT, | |
| created_at TEXT DEFAULT CURRENT_TIMESTAMP, | |
| paid_at TEXT | |
| ) | |
| """) | |
| c.execute(""" | |
| CREATE TABLE IF NOT EXISTS resume_log ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| telegram_id TEXT, | |
| tier_used TEXT, | |
| ref_code TEXT, | |
| status TEXT, | |
| created_at TEXT DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| conn.commit() | |
| print("β Database tables created") | |
| # ββ User operations ββ | |
| def get_user(telegram_id: str) -> dict: | |
| with get_conn() as conn: | |
| conn.row_factory = sqlite3.Row | |
| c = conn.cursor() | |
| c.execute("SELECT * FROM users WHERE telegram_id = ?", (telegram_id,)) | |
| row = c.fetchone() | |
| if row: | |
| return dict(row) | |
| return None | |
| def create_user(telegram_id: str, username: str = "", full_name: str = "") -> dict: | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute( | |
| "INSERT OR IGNORE INTO users (telegram_id, username, full_name) VALUES (?, ?, ?)", | |
| (telegram_id, username, full_name) | |
| ) | |
| conn.commit() | |
| return get_user(telegram_id) | |
| def update_user_tier(telegram_id: str, tier: str, resumes_limit: int, sub_expires_at: str = None): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute( | |
| "UPDATE users SET tier = ?, resumes_limit = ?, sub_expires_at = ? WHERE telegram_id = ?", | |
| (tier, resumes_limit, sub_expires_at, telegram_id) | |
| ) | |
| conn.commit() | |
| def increment_usage(telegram_id: str): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute( | |
| "UPDATE users SET resumes_used = resumes_used + 1 WHERE telegram_id = ?", | |
| (telegram_id,) | |
| ) | |
| conn.commit() | |
| def set_language(telegram_id: str, language: str): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute("UPDATE users SET language = ? WHERE telegram_id = ?", (language, telegram_id)) | |
| conn.commit() | |
| def check_subscription(telegram_id: str) -> dict: | |
| """Check and auto-downgrade expired Basic plans. Returns user dict.""" | |
| user = get_user(telegram_id) | |
| if not user: | |
| return None | |
| if user["tier"] == "basic" and user.get("sub_expires_at"): | |
| expires = datetime.fromisoformat(user["sub_expires_at"]) | |
| if datetime.now() > expires: | |
| update_user_tier(telegram_id, tier="free", resumes_limit=1, sub_expires_at=None) | |
| user = get_user(telegram_id) | |
| return {**user, "just_expired": True} | |
| return {**user, "just_expired": False} | |
| # ββ Payment operations ββ | |
| def create_pending_payment(ref_code: str, telegram_id: str, plan: str, amount: float, | |
| file_id: str = "", file_type: str = ""): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute( | |
| "INSERT OR REPLACE INTO pending_payments (ref_code, telegram_id, plan, amount, file_id, file_type) VALUES (?, ?, ?, ?, ?, ?)", | |
| (ref_code, telegram_id, plan, amount, file_id, file_type) | |
| ) | |
| conn.commit() | |
| def get_pending_by_ref(ref_code: str) -> dict: | |
| with get_conn() as conn: | |
| conn.row_factory = sqlite3.Row | |
| c = conn.cursor() | |
| c.execute("SELECT * FROM pending_payments WHERE ref_code = ?", (ref_code,)) | |
| row = c.fetchone() | |
| if row: | |
| return dict(row) | |
| return None | |
| def mark_payment_paid(ref_code: str, transaction_id: str): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute( | |
| "UPDATE pending_payments SET status = 'paid', transaction_id = ?, paid_at = ? WHERE ref_code = ?", | |
| (transaction_id, datetime.now().isoformat(), ref_code) | |
| ) | |
| conn.commit() | |
| def mark_payment_failed(ref_code: str): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute("UPDATE pending_payments SET status = 'failed' WHERE ref_code = ?", (ref_code,)) | |
| conn.commit() | |
| # ββ Resume log ββ | |
| def log_resume(telegram_id: str, tier: str = "", ref_code: str = "", status: str = "success"): | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute( | |
| "INSERT INTO resume_log (telegram_id, tier_used, ref_code, status) VALUES (?, ?, ?, ?)", | |
| (telegram_id, tier, ref_code, status) | |
| ) | |
| conn.commit() | |
| # ββ Admin stats ββ | |
| def get_stats() -> dict: | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute("SELECT COUNT(*) FROM users") | |
| total_users = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM users WHERE tier = 'free'") | |
| free_users = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM users WHERE tier = 'ppu'") | |
| ppu_users = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM users WHERE tier = 'basic'") | |
| basic_users = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM resume_log WHERE status = 'success'") | |
| total_resumes = c.fetchone()[0] | |
| c.execute("SELECT COUNT(*) FROM pending_payments WHERE status = 'paid'") | |
| paid_count = c.fetchone()[0] | |
| c.execute("SELECT COALESCE(SUM(amount), 0) FROM pending_payments WHERE status = 'paid'") | |
| estimated_revenue = c.fetchone()[0] | |
| return { | |
| "total_users": total_users, | |
| "free_users": free_users, | |
| "ppu_users": ppu_users, | |
| "basic_users": basic_users, | |
| "total_resumes": total_resumes, | |
| "paid_count": paid_count, | |
| "estimated_revenue": estimated_revenue, | |
| } | |
| # ββ Rate limiting (Gap #3) ββ | |
| def check_rate_limit(telegram_id: str, max_per_hour: int = 5) -> bool: | |
| """Return True if under limit, False if rate limited.""" | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute( | |
| "SELECT COUNT(*) FROM resume_log WHERE telegram_id = ? AND created_at >= datetime('now', '-1 hour')", | |
| (telegram_id,) | |
| ) | |
| count = c.fetchone()[0] | |
| return count < max_per_hour | |
| # ββ Admin bypass & promo logic ββ | |
| ADMIN_ID = os.getenv("ADMIN_TELEGRAM_ID", "") | |
| PROMO_START = "2026-04-19" # Launch date | |
| PROMO_RESUMES = 3 # Free resumes during promo | |
| def is_admin(telegram_id: str) -> bool: | |
| """Check if user is the admin.""" | |
| return str(telegram_id) == ADMIN_ID | |
| def get_user_limit(telegram_id: str) -> int: | |
| """Get the resume limit for a user. Admin gets unlimited. Promo users get 3.""" | |
| if is_admin(telegram_id): | |
| return 999999 # Unlimited for admin | |
| user = get_user(telegram_id) | |
| if not user: | |
| return 1 # Default | |
| tier = user.get("tier", "free") | |
| if tier == "free": | |
| # Promo: first 30 days from account creation = 3 resumes | |
| created = user.get("created_at", "") | |
| if created: | |
| try: | |
| from datetime import datetime | |
| created_dt = datetime.fromisoformat(created) | |
| promo_end = created_dt + timedelta(days=30) | |
| if datetime.now() < promo_end: | |
| return PROMO_RESUMES # 3 during promo period | |
| except Exception: | |
| pass | |
| return 1 # After promo: 1 resume lifetime | |
| else: | |
| return user.get("resumes_limit", 1) | |
| def set_promo_limit(telegram_id: str): | |
| """Set promo limit for a new user (3 resumes for 30 days).""" | |
| with get_conn() as conn: | |
| c = conn.cursor() | |
| c.execute("UPDATE users SET resumes_limit = ? WHERE telegram_id = ?", (PROMO_RESUMES, telegram_id)) | |
| conn.commit() |