| |
|
|
| import os |
| from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for |
| import hmac |
| import hashlib |
| import json |
| from urllib.parse import unquote, parse_qs, quote |
| import time |
| from datetime import datetime |
| import logging |
| import threading |
| import random |
| from huggingface_hub import HfApi, hf_hub_download |
| from huggingface_hub.utils import RepositoryNotFoundError |
|
|
| BOT_TOKEN = os.getenv("BOT_TOKEN", "7531615056:AAFL7Lp1kc-sAshoiM0tfez5-7wea26GXYU") |
| HOST = '0.0.0.0' |
| PORT = 7860 |
| DATA_FILE = 'data.json' |
|
|
| REPO_ID = "flpolprojects/druzhbaset" |
| HF_DATA_FILE_PATH = "data.json" |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") |
|
|
| app = Flask(__name__) |
| logging.basicConfig(level=logging.INFO) |
| app.secret_key = os.urandom(24) |
|
|
| _data_lock = threading.Lock() |
| visitor_data_cache = {} |
|
|
| def generate_unique_id(all_data): |
| while True: |
| new_id = str(random.randint(10000, 99999)) |
| if new_id not in all_data: |
| return new_id |
|
|
| def download_data_from_hf(): |
| global visitor_data_cache |
| if not HF_TOKEN_READ: |
| logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.") |
| return False |
| try: |
| logging.info(f"Attempting to download {HF_DATA_FILE_PATH} from {REPO_ID}...") |
| hf_hub_download( |
| repo_id=REPO_ID, |
| filename=HF_DATA_FILE_PATH, |
| repo_type="dataset", |
| token=HF_TOKEN_READ, |
| local_dir=".", |
| local_dir_use_symlinks=False, |
| force_download=True, |
| etag_timeout=10 |
| ) |
| logging.info("Data file successfully downloaded from Hugging Face.") |
| with _data_lock: |
| try: |
| with open(DATA_FILE, 'r', encoding='utf-8') as f: |
| visitor_data_cache = json.load(f) |
| logging.info("Successfully loaded downloaded data into cache.") |
| except (FileNotFoundError, json.JSONDecodeError) as e: |
| logging.error(f"Error reading downloaded data file: {e}. Starting with empty cache.") |
| visitor_data_cache = {} |
| return True |
| except RepositoryNotFoundError: |
| logging.error(f"Hugging Face repository '{REPO_ID}' not found. Cannot download data.") |
| except Exception as e: |
| logging.error(f"Error downloading data from Hugging Face: {e}") |
| return False |
|
|
| def load_visitor_data(): |
| global visitor_data_cache |
| with _data_lock: |
| if not visitor_data_cache: |
| try: |
| with open(DATA_FILE, 'r', encoding='utf-8') as f: |
| visitor_data_cache = json.load(f) |
| logging.info("Visitor data loaded from local JSON.") |
| except FileNotFoundError: |
| logging.warning(f"{DATA_FILE} not found locally. Starting with empty data.") |
| visitor_data_cache = {} |
| except json.JSONDecodeError: |
| logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.") |
| visitor_data_cache = {} |
| except Exception as e: |
| logging.error(f"Unexpected error loading visitor data: {e}") |
| visitor_data_cache = {} |
| return visitor_data_cache |
|
|
| def save_visitor_data(data): |
| with _data_lock: |
| try: |
| visitor_data_cache.update(data) |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: |
| json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4) |
| logging.info(f"Visitor data successfully saved to {DATA_FILE}.") |
| upload_data_to_hf_async() |
| except Exception as e: |
| logging.error(f"Error saving visitor data: {e}") |
|
|
| def upload_data_to_hf(): |
| if not HF_TOKEN_WRITE: |
| logging.warning("HF_TOKEN_WRITE not set. Skipping Hugging Face upload.") |
| return |
| if not os.path.exists(DATA_FILE): |
| logging.warning(f"{DATA_FILE} does not exist. Skipping upload.") |
| return |
|
|
| try: |
| api = HfApi() |
| with _data_lock: |
| file_content_exists = os.path.getsize(DATA_FILE) > 0 |
| if not file_content_exists: |
| logging.warning(f"{DATA_FILE} is empty. Skipping upload.") |
| return |
|
|
| logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}/{HF_DATA_FILE_PATH}...") |
| api.upload_file( |
| path_or_fileobj=DATA_FILE, |
| path_in_repo=HF_DATA_FILE_PATH, |
| repo_id=REPO_ID, |
| repo_type="dataset", |
| token=HF_TOKEN_WRITE, |
| commit_message=f"Update bonus data {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" |
| ) |
| logging.info("Bonus data successfully uploaded to Hugging Face.") |
| except Exception as e: |
| logging.error(f"Error uploading data to Hugging Face: {e}") |
|
|
| def upload_data_to_hf_async(): |
| upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True) |
| upload_thread.start() |
|
|
| def periodic_backup(): |
| if not HF_TOKEN_WRITE: |
| logging.info("Periodic backup disabled: HF_TOKEN_WRITE not set.") |
| return |
| while True: |
| time.sleep(3600) |
| logging.info("Initiating periodic backup...") |
| upload_data_to_hf() |
|
|
| def verify_telegram_data(init_data_str): |
| try: |
| parsed_data = parse_qs(init_data_str) |
| received_hash = parsed_data.pop('hash', [None])[0] |
|
|
| if not received_hash: |
| return None, False |
|
|
| data_check_list = [] |
| for key, value in sorted(parsed_data.items()): |
| data_check_list.append(f"{key}={value[0]}") |
| data_check_string = "\n".join(data_check_list) |
|
|
| secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest() |
| calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() |
|
|
| if calculated_hash == received_hash: |
| auth_date = int(parsed_data.get('auth_date', [0])[0]) |
| current_time = int(time.time()) |
| if current_time - auth_date > 86400: |
| logging.warning(f"Telegram InitData is older than 24 hours (Auth Date: {auth_date}, Current: {current_time}).") |
| return parsed_data, True |
| else: |
| logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}") |
| return parsed_data, False |
| except Exception as e: |
| logging.error(f"Error verifying Telegram data: {e}") |
| return None, False |
|
|
| TEMPLATE = """ |
| <!DOCTYPE html> |
| <html lang="ru"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover"> |
| <title>Druzhba Бонусы</title> |
| <script src="https://telegram.org/js/telegram-web-app.js"></script> |
| <link rel="preconnect" href="https://fonts.googleapis.com"> |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> |
| <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap" rel="stylesheet"> |
| <style> |
| :root { |
| --brand-yellow: #FFC107; |
| --brand-black: #101010; |
| --card-bg: #1c1c1e; |
| --text-color: #ffffff; |
| --text-secondary-color: #a0a0a0; |
| --border-radius: 16px; |
| --padding-m: 16px; |
| --padding-l: 24px; |
| --font-family: 'Manrope', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; |
| --shadow-color: rgba(255, 193, 7, 0.15); |
| --shadow-glow: 0 0 35px var(--shadow-color); |
| } |
| * { box-sizing: border-box; margin: 0; padding: 0; } |
| html, body { |
| background-color: var(--brand-black); |
| font-family: var(--font-family); |
| color: var(--text-color); |
| padding: var(--padding-m); |
| overscroll-behavior-y: none; |
| -webkit-font-smoothing: antialiased; |
| -moz-osx-font-smoothing: grayscale; |
| visibility: hidden; |
| min-height: 100vh; |
| } |
| .container { |
| max-width: 600px; |
| margin: 0 auto; |
| display: flex; |
| flex-direction: column; |
| gap: var(--padding-l); |
| } |
| .header { |
| text-align: left; |
| padding: var(--padding-m) 0; |
| } |
| .logo { |
| font-size: 2.5em; |
| font-weight: 800; |
| color: var(--text-color); |
| letter-spacing: -1px; |
| } |
| .logo span { color: var(--brand-yellow); } |
| .welcome-text { |
| font-size: 1em; |
| color: var(--text-secondary-color); |
| margin-top: 4px; |
| } |
| .bonus-card { |
| background: linear-gradient(145deg, #2a2a2a, #1c1c1c); |
| border-radius: calc(var(--border-radius) + 8px); |
| padding: var(--padding-l); |
| text-align: center; |
| box-shadow: var(--shadow-glow); |
| border: 1px solid rgba(255, 193, 7, 0.2); |
| position: relative; |
| overflow: hidden; |
| } |
| .bonus-label { |
| font-size: 1.1em; |
| font-weight: 500; |
| color: var(--text-secondary-color); |
| margin-bottom: 12px; |
| } |
| .bonus-amount { |
| font-size: 4em; |
| font-weight: 800; |
| color: var(--brand-yellow); |
| letter-spacing: -2px; |
| line-height: 1; |
| } |
| .client-id-card { |
| background-color: var(--card-bg); |
| border-radius: var(--border-radius); |
| padding: var(--padding-m); |
| display: flex; |
| justify-content: space-between; |
| align-items: center; |
| } |
| .client-id-label { |
| font-weight: 500; |
| color: var(--text-secondary-color); |
| } |
| .client-id-value { |
| font-size: 1.3em; |
| font-weight: 700; |
| color: var(--brand-yellow); |
| letter-spacing: 2px; |
| background-color: rgba(255,193,7,0.1); |
| padding: 4px 10px; |
| border-radius: 8px; |
| } |
| .history-section { |
| background-color: var(--card-bg); |
| border-radius: var(--border-radius); |
| padding: var(--padding-l); |
| } |
| .history-title { |
| font-size: 1.4em; |
| font-weight: 700; |
| margin-bottom: var(--padding-m); |
| padding-bottom: var(--padding-m); |
| border-bottom: 1px solid rgba(255, 255, 255, 0.1); |
| } |
| .history-list { |
| list-style: none; |
| padding: 0; |
| margin: 0; |
| max-height: 35vh; |
| overflow-y: auto; |
| } |
| .history-item { |
| display: flex; |
| justify-content: space-between; |
| align-items: center; |
| padding: 14px 4px; |
| border-bottom: 1px solid rgba(255, 255, 255, 0.05); |
| } |
| .history-item:last-child { border-bottom: none; } |
| .history-details { display: flex; flex-direction: column; } |
| .history-description { font-size: 1em; font-weight: 500; } |
| .history-date { font-size: 0.8em; color: var(--text-secondary-color); margin-top: 4px; } |
| .history-amount { font-size: 1.1em; font-weight: 700; } |
| .history-amount.accrual { color: #4CAF50; } |
| .history-amount.deduction { color: #F44336; } |
| .no-history { |
| text-align: center; |
| color: var(--text-secondary-color); |
| padding: 2rem 0; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <header class="header"> |
| <div class="logo">DRUZHBA<span>.</span></div> |
| <p id="greeting" class="welcome-text">Добро пожаловать!</p> |
| </header> |
| |
| <section class="bonus-card"> |
| <p class="bonus-label">Ваши бонусы</p> |
| <p class="bonus-amount">{{ "%.2f"|format(user.bonuses|float) }}</p> |
| </section> |
| |
| <section class="client-id-card"> |
| <p class="client-id-label">Ваш ID клиента</p> |
| <p class="client-id-value">{{ user.id }}</p> |
| </section> |
| |
| <section class="history-section"> |
| <h2 class="history-title">История операций</h2> |
| {% if user.history %} |
| <ul class="history-list"> |
| {% for item in user.history|sort(attribute='date', reverse=true) %} |
| <li class="history-item"> |
| <div class="history-details"> |
| <span class="history-description">{{ item.description }}</span> |
| <span class="history-date">{{ item.date_str }}</span> |
| </div> |
| <span class="history-amount {{ 'accrual' if item.type == 'accrual' else 'deduction' }}"> |
| {{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }} |
| </span> |
| </li> |
| {% endfor %} |
| </ul> |
| {% else %} |
| <p class="no-history">Операций пока не было.</p> |
| {% endif %} |
| </section> |
| </div> |
| |
| <script> |
| const tg = window.Telegram.WebApp; |
| |
| function applyTheme(themeParams) { |
| const root = document.documentElement; |
| const isDark = themeParams.bg_color ? (parseInt(themeParams.bg_color.substring(1, 3), 16) < 128) : true; |
| |
| root.style.setProperty('--brand-black', themeParams.bg_color || '#101010'); |
| root.style.setProperty('--text-color', themeParams.text_color || '#ffffff'); |
| root.style.setProperty('--text-secondary-color', themeParams.hint_color || '#a0a0a0'); |
| root.style.setProperty('--brand-yellow', themeParams.button_color || '#FFC107'); |
| root.style.setProperty('--card-bg', themeParams.secondary_bg_color || (isDark ? '#1c1c1e' : '#f1f1f1')); |
| } |
| |
| function setupTelegram() { |
| if (!tg || !tg.initData) { |
| console.error("Telegram WebApp script not loaded or initData is missing."); |
| document.body.style.visibility = 'visible'; |
| return; |
| } |
| |
| tg.ready(); |
| tg.expand(); |
| |
| if (tg.themeParams && Object.keys(tg.themeParams).length > 0) { |
| applyTheme(tg.themeParams); |
| } |
| tg.onEvent('themeChanged', () => applyTheme(tg.themeParams)); |
| |
| const urlParams = new URLSearchParams(window.location.search); |
| const userIdForTest = urlParams.get('user_id_for_test'); |
| |
| if (!userIdForTest) { |
| fetch('/verify', { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, |
| body: JSON.stringify({ initData: tg.initData }), |
| }) |
| .then(response => response.json()) |
| .then(data => { |
| if (data.status === 'ok' && data.verified && data.user_id) { |
| window.location.replace('/?user_id_for_test=' + data.user_id); |
| } else { |
| console.warn('Backend verification failed:', data.message); |
| document.body.style.visibility = 'visible'; |
| } |
| }) |
| .catch(error => { |
| console.error('Error sending initData for verification:', error); |
| document.body.style.visibility = 'visible'; |
| }); |
| } else { |
| document.body.style.visibility = 'visible'; |
| } |
| |
| const user = tg.initDataUnsafe?.user; |
| const greetingElement = document.getElementById('greeting'); |
| if (user) { |
| const name = user.first_name || user.username || 'Гость'; |
| greetingElement.textContent = `Привет, ${name}! 👋`; |
| } else { |
| greetingElement.textContent = `Привет, {{ user.first_name or 'Гость' }}! 👋`; |
| } |
| } |
| |
| if (window.Telegram && window.Telegram.WebApp) { |
| setupTelegram(); |
| } else { |
| window.addEventListener('load', setupTelegram, {once: true}); |
| setTimeout(() => { |
| if (document.body.style.visibility !== 'visible') { |
| document.body.style.visibility = 'visible'; |
| } |
| }, 3000); |
| } |
| </script> |
| </body> |
| </html> |
| """ |
|
|
| ADMIN_TEMPLATE = """ |
| <!DOCTYPE html> |
| <html lang="ru"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>Druzhba Admin</title> |
| <link rel="preconnect" href="https://fonts.googleapis.com"> |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> |
| <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"> |
| <style> |
| :root { |
| --admin-bg: #f8f9fa; |
| --admin-text: #212529; |
| --admin-card-bg: #ffffff; |
| --admin-border: #dee2e6; |
| --admin-shadow: rgba(0, 0, 0, 0.05); |
| --admin-primary: #FFC107; |
| --admin-primary-dark: #e0a800; |
| --admin-secondary: #6c757d; |
| --admin-success: #198754; |
| --admin-danger: #dc3545; |
| --border-radius: 12px; |
| --padding: 1.5rem; |
| --font-family: 'Inter', sans-serif; |
| } |
| body { font-family: var(--font-family); background-color: var(--admin-bg); color: var(--admin-text); margin: 0; padding: var(--padding); line-height: 1.6; } |
| .container { max-width: 1200px; margin: 0 auto; } |
| h1 { text-align: center; color: var(--admin-secondary); margin-bottom: var(--padding); font-weight: 600; } |
| .controls-bar { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; background: var(--admin-card-bg); padding: var(--padding); border-radius: var(--border-radius); box-shadow: 0 4px 15px var(--admin-shadow); border: 1px solid var(--admin-border); margin-bottom: var(--padding); } |
| .controls-bar input[type="text"] { flex-grow: 1; padding: 12px 15px; font-size: 1.1em; border-radius: 8px; border: 1px solid var(--admin-border); box-sizing: border-box; min-width: 250px; } |
| .btn { padding: 12px 20px; font-size: 1em; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background-color 0.2s ease; } |
| .btn-primary { background-color: var(--admin-primary); color: #000; } |
| .btn-primary:hover { background-color: var(--admin-primary-dark); } |
| .btn-delete { background-color: var(--admin-danger); color: white; } |
| .btn-delete:hover { background-color: #c82333; } |
| .user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: var(--padding); margin-top: var(--padding); } |
| .user-card { background-color: var(--admin-card-bg); border-radius: var(--border-radius); padding: var(--padding); box-shadow: 0 4px 15px var(--admin-shadow); border: 1px solid var(--admin-border); display: flex; flex-direction: column; transition: transform 0.2s ease, box-shadow 0.2s ease; } |
| .user-card:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08); } |
| .user-info { display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem; } |
| .user-info img { width: 60px; height: 60px; border-radius: 50%; object-fit: cover; border: 3px solid var(--admin-border); background-color: #eee; } |
| .user-details .name { font-weight: 600; font-size: 1.2em; } |
| .user-details .username { color: var(--admin-secondary); font-size: 0.9em; } |
| .user-bonuses { text-align: center; margin-bottom: 1rem; } |
| .user-bonuses .label { font-size: 0.9em; color: var(--admin-secondary); } |
| .user-bonuses .amount { font-size: 1.8em; font-weight: 700; color: var(--admin-primary-dark); } |
| .user-actions { margin-top: auto; display: flex; flex-direction: column; gap: 0.5rem; } |
| .btn-manage { display: block; width: 100%; padding: 10px; background-color: var(--admin-primary); color: #000; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background-color 0.2s; } |
| .btn-manage:hover { background-color: var(--admin-primary-dark); } |
| .no-users { text-align: center; color: var(--admin-secondary); margin-top: 2rem; font-size: 1.1em; } |
| .modal { display: none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); backdrop-filter: blur(5px); } |
| .modal-content { background-color: var(--admin-bg); margin: 10% auto; padding: var(--padding); border: 1px solid var(--admin-border); width: 90%; max-width: 600px; border-radius: var(--border-radius); position: relative; box-shadow: 0 8px 30px rgba(0,0,0,0.15); } |
| .modal-close { color: #aaa; position: absolute; top: 15px; right: 25px; font-size: 28px; font-weight: bold; cursor: pointer; } |
| .modal-header { padding-bottom: 1rem; margin-bottom: 1.5rem; border-bottom: 1px solid var(--admin-border); } |
| .modal-header h2 { margin: 0; font-size: 1.5rem; } |
| .modal-header .username { font-size: 1rem; color: var(--admin-secondary); } |
| .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; align-items: center; margin-bottom: 1.5rem; } |
| .form-group { display: flex; flex-direction: column; } |
| .form-group label { margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9em; } |
| .form-group input { padding: 10px; font-size: 1rem; border: 1px solid var(--admin-border); border-radius: 8px; width: 100%; box-sizing: border-box; } |
| .calculation-summary { background: #f0f0f0; padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem; } |
| .summary-item { display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-size: 0.95em; } |
| .summary-item strong { font-weight: 600; } |
| .history-container { margin-top: 1.5rem; } |
| .history-container h3 { font-size: 1.2rem; margin-bottom: 1rem; } |
| .history-list { list-style: none; padding: 0; max-height: 200px; overflow-y: auto; border: 1px solid var(--admin-border); border-radius: 8px; } |
| .history-item { display: flex; justify-content: space-between; padding: 8px 12px; border-bottom: 1px solid var(--admin-border); } |
| .history-item:last-child { border-bottom: none; } |
| .history-item .desc { font-size: 0.9em; } |
| .history-item .date { font-size: 0.8em; color: var(--admin-secondary); } |
| .history-item .amount.accrual { color: var(--admin-success); font-weight: 600; } |
| .history-item .amount.deduction { color: var(--admin-danger); font-weight: 600; } |
| .modal-footer { margin-top: 1.5rem; display: flex; justify-content: flex-end; align-items: center; gap: 1rem;} |
| .modal-footer button { padding: 12px 25px; font-size: 1.1em; border-radius: 8px; border: none; font-weight: 600; cursor: pointer; } |
| .btn-submit { background-color: var(--admin-success); color: white; } |
| .status-message { text-align: center; font-weight: 500; flex-grow: 1; text-align: left; } |
| </style> |
| </head> |
| <body> |
| <div class="container"> |
| <h1>Панель администратора Druzhba</h1> |
| <div class="controls-bar"> |
| <input type="text" id="searchInput" onkeyup="searchUsers()" placeholder="Поиск по имени, ID, username, номеру..."> |
| <button class="btn btn-primary" onclick="openAddClientModal()">Добавить клиента</button> |
| </div> |
| |
| {% if users %} |
| <div class="user-grid" id="userGrid"> |
| {% for user in users|sort(attribute='visited_at', reverse=true) %} |
| <div class="user-card" data-user-id="{{ user.id }}" data-search-term="{{ user.first_name|lower }} {{ user.last_name|lower }} {{ user.username|lower }} {{ user.id }} {{ user.phone_number|lower if user.phone_number }}"> |
| <div class="user-info"> |
| <img src="{{ user.photo_url if user.photo_url else 'data:image/svg+xml;charset=UTF-8,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3e%3crect width=%27100%27 height=%27100%27 fill=%27%23e9ecef%27/%3e%3ctext x=%2750%25%27 y=%2755%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2745%27 font-family=%27sans-serif%27 fill=%27%23adb5bd%27%3e?%3c/text%3e%3c/svg%3e' }}" alt="User Avatar"> |
| <div class="user-details"> |
| <div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div> |
| <div class="username">@{{ user.username if user.username else user.phone_number }} | ID: {{ user.id }}</div> |
| </div> |
| </div> |
| <div class="user-bonuses"> |
| <div class="label">Текущие бонусы</div> |
| <div class="amount">{{ "%.2f"|format(user.bonuses|float) }}</div> |
| </div> |
| <div class="user-actions"> |
| <button class="btn-manage" onclick='openTransactionModal({{ user|tojson }})'>Управление бонусами</button> |
| {% if user.telegram_id == None %} |
| <button class="btn btn-delete" onclick='deleteClient("{{ user.id }}")'>Удалить клиента</button> |
| {% endif %} |
| </div> |
| </div> |
| {% endfor %} |
| </div> |
| {% else %} |
| <p class="no-users">Пользователей пока нет.</p> |
| {% endif %} |
| </div> |
| |
| <div id="transactionModal" class="modal"> |
| <div class="modal-content"> |
| <span class="modal-close" onclick="closeModal('transactionModal')">×</span> |
| <div class="modal-header"> |
| <h2 id="modalUserName"></h2> |
| <div id="modalUserUsername" class="username"></div> |
| </div> |
| <input type="hidden" id="modalUserId"> |
| <div class="form-row"> |
| <div class="form-group"> |
| <label for="purchaseAmount">Сумма покупки</label> |
| <input type="number" id="purchaseAmount" placeholder="Например, 1500" oninput="calculateBonuses()"> |
| </div> |
| <div class="form-group"> |
| <label for="deductAmount">Списать бонусов</label> |
| <input type="number" id="deductAmount" placeholder="Например, 100" oninput="calculateBonuses()"> |
| </div> |
| </div> |
| <div class="calculation-summary"> |
| <div class="summary-item"><span>Текущий баланс:</span> <strong id="summaryCurrentBalance">0.00</strong></div> |
| <div class="summary-item"><span>Будет начислено (2%):</span> <strong id="summaryAccrual">+0.00</strong></div> |
| <div class="summary-item"><span>Будет списано:</span> <strong id="summaryDeduction">-0.00</strong></div> |
| <hr> |
| <div class="summary-item"><strong>Итоговый баланс:</strong> <strong id="summaryFinalBalance">0.00</strong></div> |
| </div> |
| <div class="history-container"> |
| <h3>История операций</h3> |
| <ul id="modalHistoryList" class="history-list"></ul> |
| </div> |
| <div class="modal-footer"> |
| <div id="modalStatus" class="status-message"></div> |
| <button class="btn-submit" onclick="submitTransaction()">Провести операцию</button> |
| </div> |
| </div> |
| </div> |
| |
| <div id="addClientModal" class="modal"> |
| <div class="modal-content"> |
| <span class="modal-close" onclick="closeModal('addClientModal')">×</span> |
| <div class="modal-header"> |
| <h2>Добавить нового клиента</h2> |
| </div> |
| <div class="form-group" style="margin-bottom: 1rem;"> |
| <label for="newClientFirstName">Имя</label> |
| <input type="text" id="newClientFirstName" placeholder="Иван"> |
| </div> |
| <div class="form-group" style="margin-bottom: 1.5rem;"> |
| <label for="newClientPhone">Номер телефона (уникальный)</label> |
| <input type="tel" id="newClientPhone" placeholder="+79001234567"> |
| </div> |
| <div class="modal-footer"> |
| <div id="addClientStatus" class="status-message"></div> |
| <button class="btn-submit" onclick="submitNewClient()">Сохранить клиента</button> |
| </div> |
| </div> |
| </div> |
| |
| <script> |
| const transactionModal = document.getElementById('transactionModal'); |
| const addClientModal = document.getElementById('addClientModal'); |
| let currentUserData = null; |
| |
| function searchUsers() { |
| const searchTerm = document.getElementById('searchInput').value.toLowerCase(); |
| const userCards = document.querySelectorAll('.user-card'); |
| userCards.forEach(card => { |
| const cardSearchTerm = card.getAttribute('data-search-term'); |
| if (cardSearchTerm.includes(searchTerm)) { |
| card.style.display = 'flex'; |
| } else { |
| card.style.display = 'none'; |
| } |
| }); |
| } |
| |
| function openTransactionModal(userData) { |
| currentUserData = userData; |
| document.getElementById('modalUserId').value = userData.id; |
| document.getElementById('modalUserName').textContent = `${userData.first_name || ''} ${userData.last_name || ''}`; |
| document.getElementById('modalUserUsername').textContent = `@${userData.username || userData.phone_number} | ID: ${userData.id}`; |
| document.getElementById('purchaseAmount').value = ''; |
| document.getElementById('deductAmount').value = ''; |
| document.getElementById('modalStatus').textContent = ''; |
| |
| const historyList = document.getElementById('modalHistoryList'); |
| historyList.innerHTML = ''; |
| if (userData.history && userData.history.length > 0) { |
| const sortedHistory = [...userData.history].sort((a, b) => new Date(b.date) - new Date(a.date)); |
| sortedHistory.forEach(item => { |
| const li = document.createElement('li'); |
| li.className = 'history-item'; |
| const sign = item.type === 'accrual' ? '+' : '-'; |
| const amountClass = item.type === 'accrual' ? 'accrual' : 'deduction'; |
| li.innerHTML = ` |
| <div> |
| <div class="desc">${item.description}</div> |
| <div class="date">${item.date_str}</div> |
| </div> |
| <div class="amount ${amountClass}">${sign}${parseFloat(item.amount).toFixed(2)}</div> |
| `; |
| historyList.appendChild(li); |
| }); |
| } else { |
| historyList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Нет истории</li>'; |
| } |
| |
| calculateBonuses(); |
| transactionModal.style.display = 'block'; |
| } |
| |
| function openAddClientModal() { |
| document.getElementById('newClientFirstName').value = ''; |
| document.getElementById('newClientPhone').value = ''; |
| document.getElementById('addClientStatus').textContent = ''; |
| addClientModal.style.display = 'block'; |
| } |
| |
| function closeModal(modalId) { |
| document.getElementById(modalId).style.display = 'none'; |
| if (modalId === 'transactionModal') { |
| currentUserData = null; |
| } |
| } |
| |
| function calculateBonuses() { |
| if (!currentUserData) return; |
| const currentBalance = parseFloat(currentUserData.bonuses) || 0; |
| const purchaseAmount = parseFloat(document.getElementById('purchaseAmount').value) || 0; |
| const deductAmount = parseFloat(document.getElementById('deductAmount').value) || 0; |
| const accrualAmount = purchaseAmount * 0.02; |
| let finalDeductAmount = deductAmount; |
| if (deductAmount > currentBalance) { |
| finalDeductAmount = currentBalance; |
| document.getElementById('deductAmount').value = finalDeductAmount.toFixed(2); |
| } |
| const finalBalance = currentBalance + accrualAmount - finalDeductAmount; |
| document.getElementById('summaryCurrentBalance').textContent = currentBalance.toFixed(2); |
| document.getElementById('summaryAccrual').textContent = `+${accrualAmount.toFixed(2)}`; |
| document.getElementById('summaryDeduction').textContent = `-${finalDeductAmount.toFixed(2)}`; |
| document.getElementById('summaryFinalBalance').textContent = finalBalance.toFixed(2); |
| } |
| |
| async function submitTransaction() { |
| const statusEl = document.getElementById('modalStatus'); |
| statusEl.style.color = 'var(--admin-secondary)'; |
| statusEl.textContent = 'Обработка...'; |
| const payload = { |
| user_id: document.getElementById('modalUserId').value, |
| purchase_amount: parseFloat(document.getElementById('purchaseAmount').value) || 0, |
| deduct_amount: parseFloat(document.getElementById('deductAmount').value) || 0, |
| }; |
| if (payload.purchase_amount <= 0 && payload.deduct_amount <= 0) { |
| statusEl.style.color = 'var(--admin-danger)'; |
| statusEl.textContent = 'Введите сумму покупки или сумму для списания.'; |
| return; |
| } |
| try { |
| const response = await fetch('/admin/add_transaction', { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify(payload) |
| }); |
| const result = await response.json(); |
| if (response.ok) { |
| statusEl.style.color = 'var(--admin-success)'; |
| statusEl.textContent = 'Операция успешно проведена!'; |
| setTimeout(() => { location.reload(); }, 1500); |
| } else { |
| throw new Error(result.message || 'Произошла ошибка'); |
| } |
| } catch (error) { |
| statusEl.style.color = 'var(--admin-danger)'; |
| statusEl.textContent = `Ошибка: ${error.message}`; |
| } |
| } |
| |
| async function submitNewClient() { |
| const statusEl = document.getElementById('addClientStatus'); |
| statusEl.style.color = 'var(--admin-secondary)'; |
| statusEl.textContent = 'Сохранение...'; |
| |
| const payload = { |
| first_name: document.getElementById('newClientFirstName').value.trim(), |
| phone_number: document.getElementById('newClientPhone').value.trim(), |
| }; |
| |
| if (!payload.first_name || !payload.phone_number) { |
| statusEl.style.color = 'var(--admin-danger)'; |
| statusEl.textContent = 'Имя и номер телефона обязательны.'; |
| return; |
| } |
| |
| try { |
| const response = await fetch('/admin/add_client', { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify(payload) |
| }); |
| const result = await response.json(); |
| if (response.ok) { |
| statusEl.style.color = 'var(--admin-success)'; |
| statusEl.textContent = 'Клиент успешно добавлен!'; |
| setTimeout(() => { location.reload(); }, 1500); |
| } else { |
| throw new Error(result.message || 'Произошла ошибка'); |
| } |
| } catch (error) { |
| statusEl.style.color = 'var(--admin-danger)'; |
| statusEl.textContent = `Ошибка: ${error.message}`; |
| } |
| } |
| |
| async function deleteClient(userId) { |
| if (!confirm(`Вы уверены, что хотите удалить клиента с ID ${userId}? Это действие необратимо.`)) { |
| return; |
| } |
| try { |
| const response = await fetch('/admin/delete_client', { |
| method: 'POST', |
| headers: { 'Content-Type': 'application/json' }, |
| body: JSON.stringify({ user_id: userId }) |
| }); |
| const result = await response.json(); |
| if (response.ok) { |
| location.reload(); |
| } else { |
| throw new Error(result.message || 'Не удалось удалить клиента.'); |
| } |
| } catch (error) { |
| alert(`Ошибка: ${error.message}`); |
| } |
| } |
| |
| window.onclick = function(event) { |
| if (event.target == transactionModal) { |
| closeModal('transactionModal'); |
| } |
| if (event.target == addClientModal) { |
| closeModal('addClientModal'); |
| } |
| } |
| </script> |
| </body> |
| </html> |
| """ |
|
|
| @app.route('/') |
| def index(): |
| user_id_str = request.args.get('user_id_for_test') |
| |
| current_data = load_visitor_data() |
| user_data = {} |
|
|
| if user_id_str and user_id_str in current_data: |
| user_data = current_data[user_id_str] |
| user_data['id'] = user_id_str |
| else: |
| user_data = { "id": "N/A", "bonuses": 0, "history": [] } |
|
|
| return render_template_string(TEMPLATE, user=user_data) |
|
|
| @app.route('/verify', methods=['POST']) |
| def verify_data(): |
| try: |
| req_data = request.get_json() |
| init_data_str = req_data.get('initData') |
| if not init_data_str: |
| return jsonify({"status": "error", "message": "Missing initData"}), 400 |
|
|
| user_data_parsed, is_valid = verify_telegram_data(init_data_str) |
|
|
| user_info_dict = {} |
| if user_data_parsed and 'user' in user_data_parsed: |
| try: |
| user_json_str = unquote(user_data_parsed['user'][0]) |
| user_info_dict = json.loads(user_json_str) |
| except Exception as e: |
| logging.error(f"Could not parse user JSON: {e}") |
| user_info_dict = {} |
|
|
| if is_valid: |
| tg_user_id = user_info_dict.get('id') |
| if tg_user_id: |
| now = datetime.now() |
| all_data = load_visitor_data() |
| |
| existing_user_key = None |
| for key, user_data_item in all_data.items(): |
| if str(user_data_item.get('telegram_id')) == str(tg_user_id): |
| existing_user_key = key |
| break |
| |
| if existing_user_key: |
| user_entry = all_data[existing_user_key] |
| user_entry.update({ |
| 'first_name': user_info_dict.get('first_name'), |
| 'last_name': user_info_dict.get('last_name'), |
| 'username': user_info_dict.get('username'), |
| 'photo_url': user_info_dict.get('photo_url'), |
| 'language_code': user_info_dict.get('language_code'), |
| 'visited_at': now.timestamp(), |
| 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S') |
| }) |
| user_id_to_save = existing_user_key |
| else: |
| new_user_id = generate_unique_id(all_data) |
| user_entry = { |
| 'id': new_user_id, |
| 'telegram_id': tg_user_id, |
| 'first_name': user_info_dict.get('first_name'), |
| 'last_name': user_info_dict.get('last_name'), |
| 'username': user_info_dict.get('username'), |
| 'photo_url': user_info_dict.get('photo_url'), |
| 'language_code': user_info_dict.get('language_code'), |
| 'is_premium': user_info_dict.get('is_premium', False), |
| 'phone_number': None, |
| 'visited_at': now.timestamp(), |
| 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'), |
| 'bonuses': 0, |
| 'history': [] |
| } |
| user_id_to_save = new_user_id |
| |
| save_visitor_data({user_id_to_save: user_entry}) |
| |
| return jsonify({"status": "ok", "verified": True, "user_id": user_id_to_save}) |
| else: |
| return jsonify({"status": "error", "verified": True, "message": "User ID not found in parsed data"}), 400 |
| else: |
| logging.warning(f"Verification failed for user: {user_info_dict.get('id')}") |
| return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403 |
|
|
| except Exception as e: |
| logging.exception("Error in /verify endpoint") |
| return jsonify({"status": "error", "message": "Internal server error"}), 500 |
|
|
| @app.route('/admin') |
| def admin_panel(): |
| current_data = load_visitor_data() |
| users_list = [] |
| for user_id, user_data in current_data.items(): |
| user_data['id'] = user_id |
| users_list.append(user_data) |
| return render_template_string(ADMIN_TEMPLATE, users=users_list) |
|
|
| @app.route('/admin/add_client', methods=['POST']) |
| def add_client(): |
| try: |
| data = request.get_json() |
| phone_number = data.get('phone_number') |
| first_name = data.get('first_name') |
|
|
| if not phone_number or not first_name: |
| return jsonify({"status": "error", "message": "Имя и номер телефона обязательны."}), 400 |
| |
| all_data = load_visitor_data() |
|
|
| for user in all_data.values(): |
| if user.get('phone_number') == phone_number: |
| return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409 |
|
|
| now = datetime.now() |
| new_id = generate_unique_id(all_data) |
| |
| new_client = { |
| 'id': new_id, |
| 'telegram_id': None, |
| 'first_name': first_name, |
| 'last_name': None, |
| 'username': None, |
| 'photo_url': None, |
| 'language_code': 'ru', |
| 'is_premium': False, |
| 'phone_number': phone_number, |
| 'visited_at': now.timestamp(), |
| 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'), |
| 'bonuses': 0, |
| 'history': [] |
| } |
| |
| save_visitor_data({new_id: new_client}) |
|
|
| return jsonify({"status": "ok", "message": "Client added successfully"}), 201 |
|
|
| except Exception as e: |
| logging.exception("Error in /admin/add_client endpoint") |
| return jsonify({"status": "error", "message": str(e)}), 500 |
|
|
|
|
| @app.route('/admin/add_transaction', methods=['POST']) |
| def add_transaction(): |
| try: |
| data = request.get_json() |
| user_id = data.get('user_id') |
| purchase_amount = float(data.get('purchase_amount', 0)) |
| deduct_amount = float(data.get('deduct_amount', 0)) |
|
|
| if not user_id: |
| return jsonify({"status": "error", "message": "User ID is required"}), 400 |
| |
| user_id_str = str(user_id) |
| all_data = load_visitor_data() |
|
|
| if user_id_str not in all_data: |
| return jsonify({"status": "error", "message": "User not found"}), 404 |
|
|
| user = all_data[user_id_str] |
| now = datetime.now() |
| now_str = now.strftime('%Y-%m-%d %H:%M:%S') |
| |
| accrual_amount = purchase_amount * 0.02 |
|
|
| if deduct_amount > user.get('bonuses', 0): |
| return jsonify({"status": "error", "message": "Not enough bonuses to deduct"}), 400 |
|
|
| user['bonuses'] = user.get('bonuses', 0) + accrual_amount - deduct_amount |
|
|
| if 'history' not in user or not isinstance(user['history'], list): |
| user['history'] = [] |
|
|
| if accrual_amount > 0: |
| user['history'].append({ |
| "type": "accrual", |
| "amount": accrual_amount, |
| "description": f"Начисление с покупки {purchase_amount}", |
| "date": now.isoformat(), |
| "date_str": now_str |
| }) |
| |
| if deduct_amount > 0: |
| user['history'].append({ |
| "type": "deduction", |
| "amount": deduct_amount, |
| "description": "Списание бонусов", |
| "date": now.isoformat(), |
| "date_str": now_str |
| }) |
| |
| save_visitor_data({user_id_str: user}) |
|
|
| return jsonify({"status": "ok", "message": "Transaction successful", "new_balance": user['bonuses']}), 200 |
|
|
| except Exception as e: |
| logging.exception("Error in /admin/add_transaction endpoint") |
| return jsonify({"status": "error", "message": str(e)}), 500 |
|
|
| @app.route('/admin/delete_client', methods=['POST']) |
| def delete_client(): |
| try: |
| data = request.get_json() |
| user_id = data.get('user_id') |
|
|
| if not user_id: |
| return jsonify({"status": "error", "message": "User ID is required"}), 400 |
|
|
| user_id_str = str(user_id) |
| load_visitor_data() |
|
|
| with _data_lock: |
| if user_id_str not in visitor_data_cache: |
| return jsonify({"status": "error", "message": "User not found"}), 404 |
|
|
| user_to_delete = visitor_data_cache[user_id_str] |
| if user_to_delete.get('telegram_id') is not None: |
| return jsonify({"status": "error", "message": "Cannot delete a Telegram-linked user"}), 403 |
|
|
| del visitor_data_cache[user_id_str] |
|
|
| try: |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: |
| json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4) |
| logging.info(f"User {user_id_str} deleted. Data saved to {DATA_FILE}.") |
| upload_data_to_hf_async() |
| except Exception as e: |
| logging.error(f"Error saving data after deletion: {e}") |
| return jsonify({"status": "error", "message": "Failed to save data after deletion"}), 500 |
|
|
| return jsonify({"status": "ok", "message": "Client deleted successfully"}), 200 |
|
|
| except Exception as e: |
| logging.exception("Error in /admin/delete_client endpoint") |
| return jsonify({"status": "error", "message": str(e)}), 500 |
|
|
| if __name__ == '__main__': |
| print("--- DRUZHBA BONUS SYSTEM SERVER ---") |
| print(f"Server starting on http://{HOST}:{PORT}") |
| if not HF_TOKEN_READ or not HF_TOKEN_WRITE: |
| print("WARNING: Hugging Face token(s) not set. Backup/restore functionality will be limited.") |
| else: |
| print("Attempting initial data download from Hugging Face...") |
| download_data_from_hf() |
|
|
| load_visitor_data() |
|
|
| print("WARNING: The /admin route is NOT protected. Implement proper authentication for production.") |
| |
| if HF_TOKEN_WRITE: |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) |
| backup_thread.start() |
| print("Periodic backup thread started (every hour).") |
|
|
| print("--- Server Ready ---") |
| app.run(host=HOST, port=PORT, debug=False) |