Examplebonus33 / app.py
Kgshop's picture
Update app.py
7ea0e3b verified
raw
history blame
38.7 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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
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/druzhbabase"
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 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=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--tg-theme-bg-color: #111111;
--tg-theme-text-color: #ffffff;
--tg-theme-hint-color: #aaaaaa;
--tg-theme-link-color: #FFC107;
--tg-theme-button-color: #FFC107;
--tg-theme-button-text-color: #000000;
--tg-theme-secondary-bg-color: #1e1e1e;
--brand-yellow: #FFC107;
--brand-black: #111111;
--card-bg: #222222;
--text-color: #ffffff;
--text-secondary-color: #aaaaaa;
--border-radius-m: 14px;
--border-radius-l: 18px;
--padding-m: 18px;
--padding-l: 28px;
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--shadow-color: rgba(0, 0, 0, 0.4);
--shadow-light: 0 4px 15px var(--shadow-color);
--shadow-medium: 0 6px 25px 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: 650px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: var(--padding-l);
}
.header {
text-align: center;
padding: var(--padding-m) 0;
}
.logo {
font-size: 2em;
font-weight: 700;
color: var(--brand-yellow);
}
.welcome-text {
font-size: 1.1em;
color: var(--text-secondary-color);
margin-top: 8px;
}
.bonus-card {
background: linear-gradient(145deg, #2a2a2a, #1c1c1c);
border-radius: var(--border-radius-l);
padding: var(--padding-l);
text-align: center;
box-shadow: var(--shadow-medium);
border: 1px solid rgba(255, 193, 7, 0.2);
}
.bonus-label {
font-size: 1.2em;
font-weight: 500;
color: var(--text-secondary-color);
margin-bottom: 12px;
}
.bonus-amount {
font-size: 3.5em;
font-weight: 700;
color: var(--brand-yellow);
letter-spacing: -1px;
}
.bonus-amount-minor {
font-size: 0.5em;
opacity: 0.8;
}
.history-section {
background-color: var(--card-bg);
border-radius: var(--border-radius-l);
padding: var(--padding-l);
box-shadow: var(--shadow-light);
border: 1px solid rgba(255, 255, 255, 0.08);
}
.history-title {
font-size: 1.5em;
font-weight: 600;
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: 400px;
overflow-y: auto;
}
.history-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 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.85em;
color: var(--text-secondary-color);
margin-top: 4px;
}
.history-amount {
font-size: 1.2em;
font-weight: 600;
}
.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</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="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;
if (themeParams.bg_color) root.style.setProperty('--tg-theme-bg-color', themeParams.bg_color);
if (themeParams.text_color) root.style.setProperty('--tg-theme-text-color', themeParams.text_color);
if (themeParams.hint_color) root.style.setProperty('--tg-theme-hint-color', themeParams.hint_color);
if (themeParams.link_color) root.style.setProperty('--tg-theme-link-color', themeParams.link_color);
if (themeParams.button_color) root.style.setProperty('--tg-theme-button-color', themeParams.button_color);
if (themeParams.button_text_color) root.style.setProperty('--tg-theme-button-text-color', themeParams.button_text_color);
if (themeParams.secondary_bg_color) root.style.setProperty('--tg-theme-secondary-bg-color', themeParams.secondary_bg_color);
}
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));
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) {
console.log('Backend verification successful.');
} else {
console.warn('Backend verification failed:', data.message);
}
})
.catch(error => console.error('Error sending initData for verification:', error));
const user = tg.initDataUnsafe?.user;
const greetingElement = document.getElementById('greeting');
if (user) {
const name = user.first_name || user.username || 'Гость';
greetingElement.textContent = `Добро пожаловать, ${name}! 👋`;
}
document.body.style.visibility = 'visible';
}
if (window.Telegram && window.Telegram.WebApp) {
setupTelegram();
} else {
window.addEventListener('load', setupTelegram);
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 { 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"] { width: 100%; padding: 12px 15px; font-size: 1.1em; border-radius: 8px; border: 1px solid var(--admin-border); box-sizing: border-box; }
.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.95em; }
.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 .btn { 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; }
.user-actions .btn: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; }
.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 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 { margin-top: 1rem; text-align: center; font-weight: 500; }
</style>
</head>
<body>
<div class="container">
<h1>Панель администратора Druzhba</h1>
<div class="controls-bar">
<input type="text" id="searchInput" onkeyup="searchUsers()" placeholder="Поиск по имени, ID, username...">
</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 }}">
<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 or 'N/A' }}</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" onclick='openTransactionModal({{ user|tojson }})'>Управление бонусами</button>
</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()">×</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">
<button class="btn-submit" onclick="submitTransaction()">Провести операцию</button>
<div id="modalStatus" class="status-message"></div>
</div>
</div>
</div>
<script>
const modal = document.getElementById('transactionModal');
const allUsers = {{ users|tojson }};
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 || 'N/A'}`;
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();
modal.style.display = 'block';
}
function closeModal() {
modal.style.display = 'none';
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;
}
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}`;
}
}
window.onclick = function(event) {
if (event.target == modal) {
closeModal();
}
}
</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]
else:
user_data = { "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:
user_id = user_info_dict.get('id')
if user_id:
now = datetime.now()
user_id_str = str(user_id)
all_data = load_visitor_data()
if user_id_str in all_data:
user_entry = all_data[user_id_str]
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')
})
else:
user_entry = {
'id': 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),
'visited_at': now.timestamp(),
'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'),
'bonuses': 0,
'history': []
}
save_visitor_data({user_id_str: user_entry})
return redirect(url_for('index', user_id_for_test=user_id_str))
return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
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 = list(current_data.values())
return render_template_string(ADMIN_TEMPLATE, users=users_list)
@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
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)