Examplebonus22 / app.py
Kgshop's picture
Update app.py
ca44ea6 verified
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
import pytz
import uuid
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError
BOT_TOKEN = os.getenv("BOT_TOKEN", "7835463659:AAGNePbelZIAOeaglyQi1qulOqnjs4BGQn4")
HOST = '0.0.0.0'
PORT = 7860
DATA_FILE = 'data.json'
REPO_ID = "flpolprojects/examplebonus"
HF_DATA_FILE_PATH = "data.json"
HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE")
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
ALMATY_TZ = pytz.timezone('Asia/Almaty')
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.")
return False
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 = {}
if "organization_details" not in visitor_data_cache:
visitor_data_cache["organization_details"] = {}
if "bonus_program_settings" not in visitor_data_cache:
visitor_data_cache["bonus_program_settings"] = {
"invoice_bonus_percentage": 2,
"referral_promo_bonus": 50,
"referrer_first_purchase_percentage": 5
}
def save_visitor_data():
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"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:
if not os.path.getsize(DATA_FILE) > 0:
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(ALMATY_TZ).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 = [f"{key}={value[0]}" for key, value in sorted(parsed_data.items())]
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])
if (int(time.time()) - auth_date) > 86400:
logging.warning(f"Telegram InitData is older than 24 hours.")
return parsed_data, True
else:
logging.warning(f"Data verification failed.")
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>Bonus</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 {
--tg-theme-bg-color: var(--tg-bg-color, #181818);
--tg-theme-text-color: var(--tg-text-color, #ffffff);
--tg-theme-hint-color: var(--tg-hint-color, #aaaaaa);
--tg-theme-button-color: var(--tg-button-color, #FFC107);
--tg-theme-button-text-color: var(--tg-button-text-color, #000000);
--tg-theme-secondary-bg-color: var(--tg-secondary-bg-color, #2c2c2e);
--brand-red: #F44336;
--brand-green: #4CAF50;
--brand-blue: #2196F3;
--border-radius-l: 24px;
--border-radius-m: 16px;
--padding-m: 16px;
--font-family: 'Manrope', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--shadow-color: rgba(255, 193, 7, 0.15);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
html, body {
background-color: var(--tg-theme-bg-color);
font-family: var(--font-family);
color: var(--tg-theme-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: calc(var(--padding-m) + 4px); animation: fadeIn 0.5s ease-out forwards; }
.header { text-align: left; padding: 8px 0; }
.logo { font-size: 2.5em; font-weight: 800; letter-spacing: -1px; }
.logo span { color: var(--tg-theme-button-color); }
.welcome-text { font-size: 1.05em; color: var(--tg-theme-hint-color); margin-top: 4px; }
.nav-buttons {
display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
background-color: var(--tg-theme-secondary-bg-color);
border-radius: 50px; padding: 6px; position: sticky; top: var(--padding-m); z-index: 100;
backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
box-shadow: 0 5px 20px rgba(0,0,0,0.2);
}
.nav-btn {
padding: 12px 15px; border: none; border-radius: 50px;
background-color: transparent; color: var(--tg-theme-hint-color);
font-family: var(--font-family); font-weight: 700; font-size: 1em;
cursor: pointer; transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}
.nav-btn.active { background-color: var(--tg-theme-button-color); color: var(--tg-theme-button-text-color); box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
.content-section { display: none; flex-direction: column; gap: calc(var(--padding-m) + 4px); }
.content-section.active { display: flex; }
.financial-summary-card {
background: linear-gradient(135deg, var(--tg-secondary-bg-color) 0%, #3a3a3c 100%);
border-radius: var(--border-radius-l);
padding: 24px;
box-shadow: 0 10px 30px rgba(0,0,0,0.25);
border: 1px solid rgba(255, 255, 255, 0.1);
animation: slideUp 0.6s ease-out forwards;
}
.main-balance-section { text-align: center; border-bottom: 1px solid rgba(255, 255, 255, 0.1); padding-bottom: 20px; margin-bottom: 20px; }
.main-balance-section .card-label { font-size: 1.2em; font-weight: 600; color: var(--tg-theme-hint-color); margin-bottom: 8px; }
.main-balance-section .bonus-amount { font-size: 4em; font-weight: 800; letter-spacing: -2px; line-height: 1; color: var(--tg-theme-button-color); }
.sub-balances-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--padding-m); }
.sub-balance-item { text-align: center; }
.sub-balance-item .card-label { font-size: 1em; font-weight: 500; color: var(--tg-theme-hint-color); margin-bottom: 8px; }
.sub-balance-item .amount { font-size: 1.8em; font-weight: 700; }
.sub-balance-item .amount.debt { color: var(--brand-red); }
.sub-balance-item .amount.referral { color: var(--brand-blue); }
.animated-card { animation: slideUp 0.6s ease-out 0.2s forwards; opacity: 0; }
.section-card {
background-color: var(--tg-theme-secondary-bg-color); border-radius: var(--border-radius-m);
padding: 20px; border: 1px solid rgba(255, 255, 255, 0.05);
}
.promo-card .card-label { display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 1em; font-weight: 500; color: var(--tg-theme-hint-color); margin-bottom: 12px; }
.promo-info-icon { cursor: pointer; position: relative; display: flex; align-items: center; }
.promo-info-icon .tooltip {
visibility: hidden; opacity: 0; position: absolute; bottom: 140%; left: 50%;
transform: translateX(-50%); background-color: #333; color: #fff; text-align: left;
border-radius: 8px; padding: 12px; z-index: 10; width: 280px;
font-size: 0.9em; font-weight: 400; line-height: 1.4;
box-shadow: 0 4px 10px rgba(0,0,0,0.3); transition: opacity 0.2s, visibility 0.2s;
}
.promo-info-icon:hover .tooltip { visibility: visible; opacity: 1; }
.promo-code-display { display: flex; align-items: stretch; justify-content: center; gap: 2px; }
.promo-code-value {
font-size: 1.5em; font-weight: 700; color: var(--tg-theme-button-color); letter-spacing: 2px;
background-color: rgba(0,0,0,0.2); padding: 12px 18px;
border-radius: 10px 0 0 10px; flex-grow: 1; text-align: center;
}
.copy-btn {
padding: 0 18px; color: var(--tg-theme-button-text-color);
background-color: var(--tg-theme-button-color); border: none; border-radius: 0 10px 10px 0; cursor: pointer;
transition: all 0.2s ease; display: flex; align-items: center; justify-content: center;
}
.copy-btn:active { transform: scale(0.95); }
.copy-btn .icon { width: 22px; height: 22px; }
.client-id-card { display: flex; justify-content: space-between; align-items: center; }
.client-id-label { font-weight: 500; color: var(--tg-theme-hint-color); }
.client-id-value { font-size: 1.3em; font-weight: 700; }
.section-title { font-size: 1.4em; font-weight: 700; margin-bottom: 16px; }
.history-list, .invoices-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }
.history-item, .invoice-item {
display: flex; align-items: center; padding: 14px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08); transition: background-color 0.2s ease; border-radius: 12px;
}
.history-item:last-child, .invoice-item:last-child { border-bottom: none; }
.history-item:hover, .invoice-item:hover { background-color: rgba(255,255,255,0.05); }
.history-icon { margin-right: 16px; width: 42px; height: 42px; display: flex; align-items: center; justify-content: center; border-radius: 50%; }
.history-icon svg { width: 22px; height: 22px; }
.icon-bonus-accrual { background-color: rgba(76, 175, 80, 0.15); color: var(--brand-green); }
.icon-bonus-deduction { background-color: rgba(244, 67, 54, 0.15); color: var(--brand-red); }
.icon-debt-accrual { background-color: rgba(244, 67, 54, 0.15); color: var(--brand-red); }
.icon-debt-payment { background-color: rgba(76, 175, 80, 0.15); color: var(--brand-green); }
.icon-referral { background-color: rgba(33, 150, 243, 0.15); color: var(--brand-blue); }
.history-details { flex-grow: 1; }
.history-description { font-size: 1em; font-weight: 600; }
.history-date { font-size: 0.8em; color: var(--tg-theme-hint-color); margin-top: 4px; }
.history-amount { font-size: 1.1em; font-weight: 700; white-space: nowrap; }
.history-amount.positive { color: var(--brand-green); }
.history-amount.negative { color: var(--brand-red); }
.history-amount.referral { color: var(--brand-blue); }
.invoice-item { cursor: pointer; }
.invoice-details { flex-grow: 1; }
.invoice-description, .invoice-date { margin-left: 16px; }
.invoice-amount { font-size: 1.1em; font-weight: 700; color: var(--tg-theme-button-color); }
.no-data { text-align: center; color: var(--tg-theme-hint-color); padding: 3rem 0; font-size: 1.1em; }
.business-card-item { margin-bottom: 20px; }
.business-card-label { font-weight: 500; color: var(--tg-theme-hint-color); margin-bottom: 8px; font-size: 0.9em; }
.business-card-value { font-size: 1.1em; font-weight: 600; }
.business-card-value a { color: var(--tg-theme-button-color); text-decoration: none; word-break: break-all; transition: opacity 0.2s; }
.business-card-value a:hover { opacity: 0.8; }
.business-card-phone-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; }
.business-card-phone-item a {
display: inline-flex; align-items: center; gap: 12px; color: var(--tg-theme-text-color);
text-decoration: none; background-color: rgba(255,255,255,0.08); padding: 12px 16px;
border-radius: 12px; transition: background-color 0.2s;
}
.business-card-phone-item a:hover { background-color: rgba(255,255,255,0.12); }
.modal {
display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%;
background-color: rgba(0,0,0,0.7); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
align-items: flex-end; justify-content: center;
}
.modal-content {
background-color: var(--tg-theme-secondary-bg-color); width: 100%;
border-top-left-radius: var(--border-radius-l); border-top-right-radius: var(--border-radius-l);
box-shadow: 0 -5px 25px rgba(0,0,0,0.3); padding: var(--padding-m); padding-top: 40px; position: relative;
max-height: 90vh; overflow-y: auto; animation: slideUp 0.3s ease-out;
}
.modal-close {
position: absolute; top: 12px; left: 50%; transform: translateX(-50%);
width: 40px; height: 5px; background-color: var(--tg-theme-hint-color);
border-radius: 3px; cursor: pointer;
}
.modal-title { font-size: 1.5em; font-weight: 700; margin-bottom: 20px; text-align: center; color: var(--tg-theme-button-color); }
.invoice-detail-list { list-style: none; padding: 0; margin: 0; }
.invoice-detail-item {
display: grid; grid-template-columns: 1fr auto; gap: 4px 16px; padding: 12px 0; border-bottom: 1px dashed rgba(255,255,255,0.1);
}
.item-name { font-weight: 500; grid-column: 1; }
.item-qty-price { font-size: 0.9em; color: var(--tg-theme-hint-color); grid-column: 1; }
.item-total { font-weight: 700; grid-column: 2; grid-row: 1 / 3; align-self: center; color: var(--tg-theme-button-color); }
.invoice-total-section {
padding-top: var(--padding-m); border-top: 1px solid rgba(255,255,255,0.2); margin-top: var(--padding-m);
display: flex; flex-direction: column; gap: 8px; font-size: 1.1em;
}
.total-row { display: flex; justify-content: space-between; }
.total-row.final { font-weight: 700; font-size: 1.2em; margin-top: 8px; }
.total-row .deduction { color: var(--brand-red); }
#promoCodeModal .modal-content { align-items: center; text-align: center; padding: 40px 24px 24px; }
#promoCodeModal h2 { margin-bottom: 12px; }
#promoCodeModal p { color: var(--tg-theme-hint-color); margin-bottom: 20px; max-width: 300px; }
#promoCodeModal input {
width: 100%; padding: 16px; margin-bottom: 16px; font-size: 1.2em;
background-color: var(--tg-theme-bg-color); border: 1px solid rgba(255,255,255,0.1);
border-radius: var(--border-radius-m); color: var(--tg-theme-text-color);
text-align: center; letter-spacing: 2px;
}
#promoCodeModal .promo-modal-actions { display: flex; gap: 1rem; width: 100%; }
#promoCodeModal button {
flex-grow: 1; padding: 16px; font-size: 1em; font-weight: 700; border: none;
border-radius: var(--border-radius-m); cursor: pointer; transition: all 0.2s;
}
.btn-apply-promo { background-color: var(--tg-theme-button-color); color: var(--tg-theme-button-text-color); }
.btn-skip-promo { background-color: var(--tg-theme-secondary-bg-color); color: var(--tg-theme-text-color); }
#promoStatus { margin-top: 1rem; font-weight: 500; min-height: 20px; }
</style>
</head>
<body>
<div class="container">
<header class="header">
<div class="logo">BONUS<span>.</span></div>
<p id="greeting" class="welcome-text">Добро пожаловать!</p>
</header>
<nav class="nav-buttons">
<button class="nav-btn active" data-target="dashboard-section">Главная</button>
<button class="nav-btn" data-target="invoices-section">Накладные</button>
<button class="nav-btn" data-target="business-card-section">Визитка</button>
</nav>
<div id="dashboard-section" class="content-section active">
<section class="financial-summary-card">
<div class="main-balance-section">
<p class="card-label">Ваши бонусы</p>
<p class="bonus-amount" id="bonus-amount-display">0.00</p>
</div>
<div class="sub-balances-grid">
<div class="sub-balance-item">
<p class="card-label">Ваш долг</p>
<p class="amount debt">{{ "%.2f"|format(user.debts|float) }}</p>
</div>
<div class="sub-balance-item">
<p class="card-label">Бонусы с друзей</p>
<p class="amount referral">{{ "%.2f"|format(user.referral_bonuses|float) }}</p>
</div>
</div>
</section>
<section class="section-card promo-card animated-card">
<p class="card-label">
Ваш промокод для друзей
<span class="promo-info-icon">
<svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 0 24 24" width="20px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg>
<span class="tooltip">Передай этот промокод другу. При активации он получит <strong>{{ "%.0f"|format(bonus_settings.referral_promo_bonus|float) }}</strong> бонусов, а ты получишь <strong>{{ "%.1f"|format(bonus_settings.referrer_first_purchase_percentage|float) }}%</strong> на свой счет "от друзей" с его первой покупки.</span>
</span>
</p>
<div class="promo-code-display">
<span class="promo-code-value" id="userPromoCode">{{ user.referral_code }}</span>
<button class="copy-btn" onclick="copyPromoCode(this)">
<span id="copy-icon-wrapper">
<svg class="icon" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>
</span>
</button>
</div>
</section>
<section class="section-card client-id-card animated-card">
<p class="client-id-label">Ваш ID клиента</p>
<p class="client-id-value">{{ user.id }}</p>
</section>
<section class="section-card animated-card">
<h2 class="section-title">История операций</h2>
{% if user.combined_history %}
<ul class="history-list">
{% for item in user.combined_history[:10] %}
<li class="history-item">
{% if item.transaction_type == 'bonus' %}
<div class="history-icon {{ 'icon-bonus-accrual' if item.type == 'accrual' else 'icon-bonus-deduction' }}">
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24" fill="currentColor"><g><rect fill="none" height="24" width="24"/></g><g><path d="M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M17,13h-4v4h-2v-4H7v-2h4V7h2v4h4V13z"/></g></svg>
</div>
<div class="history-details">
<span class="history-description">{{ item.description }}</span>
<span class="history-date">{{ item.date_str }}</span>
</div>
<span class="history-amount {{ 'positive' if item.type == 'accrual' else 'negative' }}">
{{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }}
</span>
{% elif item.transaction_type == 'debt' %}
<div class="history-icon {{ 'icon-debt-payment' if item.type == 'payment' else 'icon-debt-accrual' }}">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm-1-5h2v2h-2zm0-8h2v6h-2z"/></svg>
</div>
<div class="history-details">
<span class="history-description">{{ item.description }}</span>
<span class="history-date">{{ item.date_str }}</span>
</div>
<span class="history-amount {{ 'positive' if item.type == 'payment' else 'negative' }}">
{{ '-' if item.type == 'payment' else '+' }}{{ "%.2f"|format(item.amount|float) }}
</span>
{% elif item.transaction_type == 'referral' %}
<div class="history-icon icon-referral">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>
</div>
<div class="history-details">
<span class="history-description">{{ item.description }}</span>
<span class="history-date">{{ item.date_str }}</span>
</div>
<span class="history-amount referral">
{{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }}
</span>
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<p class="no-data">Операций пока не было.</p>
{% endif %}
</section>
</div>
<div id="invoices-section" class="content-section">
<section class="section-card">
<h2 class="section-title">Мои накладные</h2>
{% if user.invoices %}
<ul class="invoices-list">
{% for invoice in user.invoices|sort(attribute='date', reverse=true) %}
<li class="invoice-item" onclick='openInvoiceDetailModal({{ invoice|tojson }})'>
<div class="history-icon" style="background-color: rgba(255, 193, 7, 0.15); color: var(--tg-theme-button-color);">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/></svg>
</div>
<div class="invoice-details">
<span class="invoice-description">Накладная #{{ invoice.invoice_id }}</span>
<span class="invoice-date">{{ invoice.date_str }}</span>
</div>
<span class="invoice-amount">{{ "%.2f"|format(invoice.total_amount|float) }}</span>
</li>
{% endfor %}
</ul>
{% else %}
<p class="no-data">Накладных пока нет.</p>
{% endif %}
</section>
</div>
<div id="business-card-section" class="content-section">
<section class="section-card">
<h2 class="section-title">Визитка организации</h2>
{% if org_details and (org_details.name or org_details.phone_numbers) %}
{% if org_details.name %}
<div class="business-card-item">
<div class="business-card-label">Название организации</div>
<div class="business-card-value">{{ org_details.name }}</div>
</div>
{% endif %}
{% if org_details.phone_numbers %}
<div class="business-card-item">
<div class="business-card-label">Номера телефонов</div>
<ul class="business-card-phone-list">
{% for phone in org_details.phone_numbers %}
<li class="business-card-phone-item">
<a href="tel:{{ phone.replace(' ', '').replace('-', '') }}">
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M6.54 5c.06.89.21 1.76.45 2.59l-1.2 1.2c-.41-1.2-.67-2.47-.76-3.79h1.51m10.92 0h1.51c-.09 1.32-.35 2.59-.76 3.79l-1.2-1.2c.24-.83.39-1.7.45-2.59M7.5 3H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.49c0-.55-.45-1-1-1-1.24 0-2.45-.2-3.57-.57-.1-.04-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.2c.28-.28.36-.67.25-1.02C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1z"/></svg>
{{ phone }}
</a>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if org_details.address %}
<div class="business-card-item">
<div class="business-card-label">Адрес</div>
<div class="business-card-value">{{ org_details.address }}</div>
</div>
{% endif %}
{% if org_details.whatsapp_link %}
<div class="business-card-item">
<div class="business-card-label">WhatsApp</div>
<div class="business-card-value">
<a href="{{ org_details.whatsapp_link }}" target="_blank">Написать в WhatsApp</a>
</div>
</div>
{% endif %}
{% if org_details.telegram_link %}
<div class="business-card-item">
<div class="business-card-label">Telegram</div>
<div class="business-card-value">
<a href="{{ org_details.telegram_link }}" target="_blank">Написать в Telegram</a>
</div>
</div>
{% endif %}
{% else %}
<p class="no-data">Данные организации не указаны.</p>
{% endif %}
</section>
</div>
</div>
<div id="invoiceDetailModal" class="modal">
<div class="modal-content">
<div class="modal-close" onclick="closeModal('invoiceDetailModal')"></div>
<h2 id="invoiceDetailTitle" class="modal-title"></h2>
<ul id="invoiceDetailList" class="invoice-detail-list"></ul>
<div id="invoiceTotalSection" class="invoice-total-section"></div>
</div>
</div>
{% if is_first_visit %}
<div id="promoCodeModal" class="modal" style="display: flex; align-items: center;">
<div class="modal-content">
<h2 class="modal-title">Есть промокод?</h2>
<p>Если у вас есть промокод от друга, введите его, чтобы получить бонус.</p>
<input type="text" id="promoCodeInput" placeholder="PROMO123">
<div id="promoStatus"></div>
<div class="promo-modal-actions">
<button class="btn-skip-promo" onclick="submitPromoCode(false)">Нет, спасибо</button>
<button class="btn-apply-promo" onclick="submitPromoCode(true)">Применить</button>
</div>
</div>
</div>
{% endif %}
<script>
const tg = window.Telegram.WebApp;
const currentUserId = '{{ user.id }}';
const initialBonusAmount = parseFloat('{{ user.bonuses|float }}');
function applyTheme(themeParams) {
if (!themeParams) return;
const root = document.documentElement.style;
root.setProperty('--tg-bg-color', themeParams.bg_color || '#181818');
root.setProperty('--tg-text-color', themeParams.text_color || '#ffffff');
root.setProperty('--tg-hint-color', themeParams.hint_color || '#aaaaaa');
root.setProperty('--tg-button-color', themeParams.button_color || '#FFC107');
root.setProperty('--tg-button-text-color', themeParams.button_text_color || '#000000');
root.setProperty('--tg-secondary-bg-color', themeParams.secondary_bg_color || '#2c2c2e');
}
function setupTelegram() {
if (!tg || !tg.initData) {
console.error("Telegram WebApp script not loaded or initData is missing.");
document.body.style.visibility = 'visible';
applyTheme({});
return;
}
tg.ready();
tg.expand();
tg.setHeaderColor(tg.themeParams.secondary_bg_color || '#2c2c2e');
applyTheme(tg.themeParams);
tg.onEvent('themeChanged', () => {
applyTheme(tg.themeParams);
tg.setHeaderColor(tg.themeParams.secondary_bg_color || '#2c2c2e');
});
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 'Гость' }}! 👋`;
}
}
function showSection(sectionId) {
document.querySelectorAll('.content-section').forEach(section => section.classList.remove('active'));
document.getElementById(sectionId).classList.add('active');
document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
document.querySelector(`.nav-btn[data-target="${sectionId}"]`).classList.add('active');
}
function openModal(modalId) { document.getElementById(modalId).style.display = 'flex'; }
function closeModal(modalId) { document.getElementById(modalId).style.display = 'none'; }
function openInvoiceDetailModal(invoiceData) {
document.getElementById('invoiceDetailTitle').textContent = `Накладная #${invoiceData.invoice_id}`;
const invoiceDetailList = document.getElementById('invoiceDetailList');
invoiceDetailList.innerHTML = '';
invoiceData.items.forEach(item => {
const li = document.createElement('li');
li.className = 'invoice-detail-item';
li.innerHTML = `<span class="item-name">${item.product_name}</span><span class="item-qty-price">${item.quantity} x ${parseFloat(item.unit_price).toFixed(2)}</span><span class="item-total">${parseFloat(item.item_total).toFixed(2)}</span>`;
invoiceDetailList.appendChild(li);
});
const totalSection = document.getElementById('invoiceTotalSection');
const totalAmount = parseFloat(invoiceData.total_amount);
const bonusesDeducted = parseFloat(invoiceData.bonuses_deducted || 0);
const bonusSource = invoiceData.bonus_source_used;
let bonusSourceText = '';
if (bonusSource === 'referral') {
bonusSourceText = ' (от друзей)';
} else if (bonusSource === 'main') {
bonusSourceText = ' (основных)';
}
let html = `<div class="total-row"><span>Сумма</span> <span>${totalAmount.toFixed(2)}</span></div>`;
if (bonusesDeducted > 0) {
html += `<div class="total-row"><span>Списано бонусов${bonusSourceText}</span> <span class="deduction">- ${bonusesDeducted.toFixed(2)}</span></div>`;
html += `<div class="total-row final"><span>К оплате</span> <span>${(totalAmount - bonusesDeducted).toFixed(2)}</span></div>`;
} else {
html += `<div class="total-row final"><span>К оплате</span> <span>${totalAmount.toFixed(2)}</span></div>`;
}
totalSection.innerHTML = html;
openModal('invoiceDetailModal');
}
function copyPromoCode(button) {
const promoCode = document.getElementById('userPromoCode').textContent;
navigator.clipboard.writeText(promoCode).then(() => {
const iconWrapper = document.getElementById('copy-icon-wrapper');
const originalIcon = iconWrapper.innerHTML;
iconWrapper.innerHTML = `<svg class="icon" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="var(--brand-green)"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/></svg>`;
setTimeout(() => { iconWrapper.innerHTML = originalIcon; }, 2000);
}).catch(err => {
console.error('Failed to copy text: ', err);
});
}
function animateValue(obj, start, end, duration) {
let startTimestamp = null;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
obj.innerHTML = parseFloat(progress * (end - start) + start).toFixed(2);
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
async function submitPromoCode(withCode) {
const promoCode = withCode ? document.getElementById('promoCodeInput').value.trim() : null;
const statusEl = document.getElementById('promoStatus');
statusEl.style.color = 'var(--tg-theme-hint-color)';
statusEl.textContent = 'Проверяем...';
try {
const response = await fetch('/submit_referral', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: currentUserId, referral_code: promoCode })
});
const result = await response.json();
if (response.ok) {
statusEl.style.color = 'var(--brand-green)';
statusEl.textContent = result.message;
setTimeout(() => { closeModal('promoCodeModal'); location.reload(); }, 1500);
} else {
throw new Error(result.message || 'Произошла ошибка');
}
} catch (error) {
statusEl.style.color = 'var(--brand-red)';
statusEl.textContent = error.message;
}
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.nav-btn').forEach(button => {
button.addEventListener('click', () => showSection(button.dataset.target));
});
showSection('dashboard-section');
const bonusAmountEl = document.getElementById('bonus-amount-display');
if (bonusAmountEl) {
animateValue(bonusAmountEl, 0, initialBonusAmount, 1000);
}
});
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';
applyTheme({});
}
}, 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>Bonus 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; --admin-info: #0dcaf0;
--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; }
.summary-bar { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: var(--padding); margin-bottom: var(--padding); }
.summary-card { 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); text-align: center; }
.summary-card .value { font-size: 2em; font-weight: 700; }
.summary-card .label { font-size: 0.9em; color: var(--admin-secondary); margin-top: 0.5rem; }
.summary-card .value.bonus { color: var(--admin-primary-dark); }
.summary-card .value.debt { color: var(--admin-danger); }
.summary-card .value.referral { color: var(--admin-info); }
.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-secondary { background-color: var(--admin-secondary); color: white; }
.btn-secondary:hover { background-color: #5a6268; }
.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(340px, 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; }
.referral-info { font-size: 0.85em; color: var(--admin-secondary); margin-top: 8px; padding: 8px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid var(--admin-border); }
.referral-info .ref-by { color: var(--admin-success); }
.referral-info .ref-count { color: var(--admin-info); font-weight: 600; }
.user-balances { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; text-align: center; margin-bottom: 1rem; margin-top: 1rem; }
.user-balances .label { font-size: 0.9em; color: var(--admin-secondary); }
.user-balances .amount { font-size: 1.5em; font-weight: 700; }
.user-balances .amount.bonus { color: var(--admin-primary-dark); }
.user-balances .amount.debt { color: var(--admin-danger); }
.user-balances .amount.referral { color: var(--admin-info); }
.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: 5% auto; padding: var(--padding); border: 1px solid var(--admin-border); width: 90%; max-width: 700px; 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-section { border: 1px solid var(--admin-border); border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem; }
.form-section h3 { margin-top: 0; margin-bottom: 1rem; font-size: 1.1em; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; align-items: flex-end; }
.form-group { display: flex; flex-direction: column; }
.form-group label { margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9em; }
.form-group input, .form-group textarea { padding: 10px; font-size: 1rem; border: 1px solid var(--admin-border); border-radius: 8px; width: 100%; box-sizing: border-box; }
.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.bonus-accrual { color: var(--admin-success); font-weight: 600; }
.history-item .amount.bonus-deduction { color: var(--admin-danger); font-weight: 600; }
.history-item .amount.debt-accrual { color: var(--admin-danger); font-weight: 600; }
.history-item .amount.debt-payment { color: var(--admin-success); font-weight: 600; }
.history-item .amount.referral-accrual { color: var(--admin-info); font-weight: 600; }
.history-item .amount.referral-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; }
.tab-buttons { display: flex; margin-bottom: 1rem; border-bottom: 1px solid var(--admin-border); }
.tab-btn { padding: 10px 15px; border: none; background-color: transparent; color: var(--admin-secondary); font-weight: 600; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.2s ease; }
.tab-btn.active { color: var(--admin-primary-dark); border-bottom-color: var(--admin-primary); }
.tab-content { display: none; }
.tab-content.active { display: block; }
#newInvoiceItemsList { display: flex; flex-direction: column; gap: 1rem; margin-bottom: 1rem; }
.invoice-item-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; padding-bottom: 10px; border-bottom: 1px solid var(--admin-border); }
.invoice-item-row .form-group { margin-bottom: 0; }
.form-group.item-name { flex: 3 1 200px; }
.form-group.item-qty, .form-group.item-price { flex: 1 1 80px; }
.item-total-group { flex: 1 1 90px; text-align: right; padding-bottom: 10px; }
.item-total-group .item-total-display { font-weight: 700; font-size: 1.1em; }
.invoice-item-row .action-btn { align-self: center; margin-bottom: 5px; background: none; border: none; color: var(--admin-danger); cursor: pointer; font-size: 1.2em; }
.invoice-items-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--admin-border); }
.invoice-items-total { font-size: 1.2em; font-weight: 700; }
.invoice-section-summary { padding: 1rem; background-color: #e9ecef; border-radius: 8px; margin-top: 1rem; font-weight: 600; font-size: 1.1em; text-align: right; }
.invoice-section-summary span { color: var(--admin-success); }
.invoice-list-admin { list-style: none; padding: 0; max-height: 200px; overflow-y: auto; border: 1px solid var(--admin-border); border-radius: 8px; }
.invoice-list-admin li { padding: 8px 12px; border-bottom: 1px solid var(--admin-border); display: flex; justify-content: space-between; align-items: center; }
.invoice-list-admin li:last-child { border-bottom: none; }
.invoice-list-admin .invoice-info { font-size: 0.9em; }
.invoice-list-admin .invoice-amount { font-weight: 700; color: var(--admin-primary-dark); }
.invoice-list-admin .view-btn { background: none; border: none; color: var(--admin-secondary); cursor: pointer; font-size: 0.9em; margin-left: 10px; }
.invoice-list-admin .delete-btn { background: none; border: none; color: var(--admin-danger); cursor: pointer; font-size: 0.9em; margin-left: 5px; }
.details-form { display: flex; flex-direction: column; gap: 1rem; }
.details-form textarea { min-height: 80px; resize: vertical; }
.form-group-horizontal { display: flex; align-items: center; gap: 10px; }
.form-group-horizontal input { flex-grow: 1; }
.form-group-horizontal span { font-weight: 500; }
.invoice-detail-list { list-style: none; padding: 0; }
.invoice-detail-item { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px dashed #ccc; }
.invoice-detail-item:last-child { border-bottom: none; }
.item-name { flex-basis: 60%; }
.item-qty-price { flex-basis: 20%; text-align: right; color: #6c757d; }
.item-total { flex-basis: 20%; text-align: right; font-weight: bold; }
.invoice-total-display { margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #dee2e6; display: flex; flex-direction: column; gap: 0.5rem; font-size: 1.1em; }
.invoice-total-display div { display: flex; justify-content: space-between; }
.bonus-source-selector { display: flex; gap: 1rem; margin-bottom: 1rem; align-items: center; flex-wrap: wrap; }
.bonus-source-selector label { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; }
</style>
</head>
<body>
<div class="container">
<h1>Панель администратора Bonus</h1>
<div class="summary-bar">
<div class="summary-card">
<div class="value">{{ summary.total_users }}</div>
<div class="label">Всего клиентов</div>
</div>
<div class="summary-card">
<div class="value bonus">{{ "%.2f"|format(summary.total_bonuses|float) }}</div>
<div class="label">Всего бонусов</div>
</div>
<div class="summary-card">
<div class="value debt">{{ "%.2f"|format(summary.total_debts|float) }}</div>
<div class="label">Всего долгов</div>
</div>
<div class="summary-card">
<div class="value referral">{{ "%.2f"|format(summary.total_referral_bonuses|float) }}</div>
<div class="label">Бонусов с друзей</div>
</div>
</div>
<div class="controls-bar">
<input type="text" id="searchInput" onkeyup="searchUsers()" placeholder="Поиск по имени, ID, username, номеру...">
<button class="btn btn-primary" onclick="openAddClientModal()">Добавить клиента</button>
<button class="btn btn-primary" onclick="openOrgSettingsModal()">Настройки организации</button>
<button class="btn btn-primary" onclick="openBonusSettingsModal()">Настройка бонусов</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="referral-info">
{% if user.referrer_info %}
<div class="ref-by">Приведен(а): <strong>{{ user.referrer_info }}</strong></div>
{% endif %}
<div class="ref-count">Привел(а) клиентов: <strong>{{ user.referrals_count }}</strong></div>
</div>
<div class="user-balances">
<div>
<div class="label">Бонусы</div>
<div class="amount bonus">{{ "%.2f"|format(user.bonuses|float) }}</div>
</div>
<div>
<div class="label">Долг</div>
<div class="amount debt">{{ "%.2f"|format(user.debts|float if user.debts else 0) }}</div>
</div>
<div>
<div class="label">От друзей</div>
<div class="amount referral">{{ "%.2f"|format(user.referral_bonuses|float if user.referral_bonuses else 0) }}</div>
</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="tab-buttons">
<button class="tab-btn active" data-tab="bonus-debt-tab">Счета</button>
<button class="tab-btn" data-tab="invoice-tab">Накладные</button>
<button class="tab-btn" data-tab="referral-history-tab">История</button>
</div>
<div id="bonus-debt-tab" class="tab-content active">
<div class="form-section">
<h3>Основные бонусы</h3>
<div class="form-row">
<div class="form-group">
<label for="accrueAmount">Начислить</label>
<input type="number" id="accrueAmount" placeholder="0" oninput="updateCalculations()">
</div>
<div class="form-group">
<label for="deductAmount">Списать</label>
<input type="number" id="deductAmount" placeholder="0" oninput="updateCalculations()">
</div>
</div>
</div>
<div class="form-section">
<h3>Бонусы от друзей</h3>
<div class="form-row">
<div class="form-group">
<label for="accrueReferralAmount">Начислить</label>
<input type="number" id="accrueReferralAmount" placeholder="0" oninput="updateCalculations()">
</div>
<div class="form-group">
<label for="deductReferralAmount">Списать</label>
<input type="number" id="deductReferralAmount" placeholder="0" oninput="updateCalculations()">
</div>
</div>
</div>
<div class="form-section">
<h3>Долги</h3>
<div class="form-row">
<div class="form-group">
<label for="addDebtAmount">Добавить долг</label>
<input type="number" id="addDebtAmount" placeholder="0" oninput="updateCalculations()">
</div>
<div class="form-group">
<label for="repayDebtAmount">Погасить долг</label>
<input type="number" id="repayDebtAmount" placeholder="0" oninput="updateCalculations()">
</div>
</div>
</div>
<div class="modal-footer">
<div id="modalStatus" class="status-message"></div>
<button class="btn-submit" onclick="submitTransaction()">Провести операцию</button>
</div>
</div>
<div id="invoice-tab" class="tab-content">
<div class="form-section">
<h3>Добавить новую накладную</h3>
<div id="newInvoiceItemsList"></div>
<div class="invoice-items-footer">
<button class="btn btn-secondary" onclick="addNewInvoiceItemRow()">Добавить товар</button>
<div class="invoice-items-total">
<strong>Итого:</strong>
<span id="newInvoiceTotalAmount">0.00</span>
</div>
</div>
</div>
<div class="form-section">
<h3>Оплата бонусами</h3>
<div class="bonus-source-selector">
<strong>Списать с:</strong>
<label><input type="radio" name="bonusSource" value="main" onchange="updateNewInvoiceTotal()" checked> Основного счета</label>
<label><input type="radio" name="bonusSource" value="referral" onchange="updateNewInvoiceTotal()"> Счета "от друзей"</label>
</div>
<p>Доступно для списания: <strong id="invoiceAvailableBonuses">0.00</strong></p>
<div class="form-group">
<label for="invoiceDeductBonuses">Сумма списания</label>
<input type="number" id="invoiceDeductBonuses" oninput="updateNewInvoiceTotal()" placeholder="0.00" step="0.01">
</div>
<div class="invoice-section-summary">
К оплате: <span id="invoiceFinalAmount">0.00</span>
</div>
</div>
<div class="modal-footer">
<div id="invoiceStatus" class="status-message"></div>
<button class="btn-submit" onclick="submitInvoice()">Сохранить накладную</button>
</div>
<div class="history-container">
<h3>История накладных клиента</h3>
<ul id="modalInvoiceList" class="invoice-list-admin"></ul>
</div>
</div>
<div id="referral-history-tab" class="tab-content">
<div class="history-container">
<h3>Общая история операций</h3>
<ul id="modalHistoryList" class="history-list"></ul>
</div>
</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="+77001234567">
</div>
<div class="modal-footer">
<div id="addClientStatus" class="status-message"></div>
<button class="btn-submit" onclick="submitNewClient()">Сохранить клиента</button>
</div>
</div>
</div>
<div id="orgSettingsModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal('orgSettingsModal')">×</span>
<div class="modal-header">
<h2>Настройки организации</h2>
</div>
<div class="details-form">
<div class="form-group">
<label for="orgName">Название организации</label>
<input type="text" id="orgName" placeholder="Название вашей организации">
</div>
<div class="form-group">
<label for="orgPhoneNumbers">Номера телефонов (через запятую)</label>
<input type="text" id="orgPhoneNumbers" placeholder="+77001112233,+77004445566">
</div>
<div class="form-group">
<label for="orgAddress">Адрес</label>
<textarea id="orgAddress" placeholder="Город, улица, дом"></textarea>
</div>
<div class="form-group">
<label for="orgWhatsAppLink">Ссылка на WhatsApp</label>
<input type="url" id="orgWhatsAppLink" placeholder="https://wa.me/77001112233">
</div>
<div class="form-group">
<label for="orgTelegramLink">Ссылка на Telegram</label>
<input type="url" id="orgTelegramLink" placeholder="https://t.me/your_telegram_username">
</div>
</div>
<div class="modal-footer">
<div id="orgStatus" class="status-message"></div>
<button class="btn-submit" onclick="saveOrgSettings()">Сохранить настройки</button>
</div>
</div>
</div>
<div id="bonusSettingsModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal('bonusSettingsModal')">×</span>
<div class="modal-header">
<h2>Настройка бонусной программы</h2>
</div>
<div class="details-form">
<div class="form-group">
<label for="settingInvoiceBonus">Процент бонусов с накладных</label>
<div class="form-group-horizontal">
<input type="number" step="0.1" id="settingInvoiceBonus" placeholder="2">
<span>%</span>
</div>
</div>
<div class="form-group">
<label for="settingPromoBonus">Количество бонусов за ввод промокода</label>
<input type="number" id="settingPromoBonus" placeholder="50">
</div>
<div class="form-group">
<label for="settingReferrerBonus">Процент партнеру с первой покупки друга</label>
<div class="form-group-horizontal">
<input type="number" step="0.1" id="settingReferrerBonus" placeholder="5">
<span>%</span>
</div>
</div>
</div>
<div class="modal-footer">
<div id="bonusSettingsStatus" class="status-message"></div>
<button class="btn-submit" onclick="saveBonusSettings()">Сохранить настройки</button>
</div>
</div>
</div>
<div id="adminInvoiceDetailModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal('adminInvoiceDetailModal')">×</span>
<div class="modal-header">
<h2 id="adminInvoiceDetailTitle"></h2>
</div>
<ul id="adminInvoiceDetailList" class="invoice-detail-list"></ul>
<div id="adminInvoiceDetailTotal" class="invoice-total-display"></div>
</div>
</div>
<script>
const transactionModal = document.getElementById('transactionModal');
const addClientModal = document.getElementById('addClientModal');
const orgSettingsModal = document.getElementById('orgSettingsModal');
const bonusSettingsModal = document.getElementById('bonusSettingsModal');
const adminInvoiceDetailModal = document.getElementById('adminInvoiceDetailModal');
let currentUserData = null;
let newInvoiceItems = [];
function searchUsers() {
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
document.querySelectorAll('.user-card').forEach(card => {
card.style.display = card.getAttribute('data-search-term').includes(searchTerm) ? 'flex' : '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}`;
['accrueAmount', 'deductAmount', 'addDebtAmount', 'repayDebtAmount', 'accrueReferralAmount', 'deductReferralAmount'].forEach(id => document.getElementById(id).value = '');
['modalStatus', 'invoiceStatus'].forEach(id => document.getElementById(id).textContent = '');
document.getElementById('invoiceDeductBonuses').value = '';
newInvoiceItems = [];
renderNewInvoiceItems();
loadUserHistoryAndInvoices();
showTab('bonus-debt-tab');
transactionModal.style.display = 'block';
}
function loadUserHistoryAndInvoices() {
const historyList = document.getElementById('modalHistoryList');
historyList.innerHTML = '';
const bonusHistory = (currentUserData.history || []).map(h => ({...h, transaction_type: 'bonus'}));
const debtHistory = (currentUserData.debt_history || []).map(h => ({...h, transaction_type: 'debt'}));
const referralHistory = (currentUserData.referral_bonus_history || []).map(h => ({...h, transaction_type: 'referral'}));
const combinedHistory = [...bonusHistory, ...debtHistory, ...referralHistory].sort((a, b) => new Date(b.date) - new Date(a.date));
if (combinedHistory.length > 0) {
combinedHistory.forEach(item => {
const li = document.createElement('li');
li.className = 'history-item';
let sign, amountClass, amountText;
if (item.transaction_type === 'bonus') {
sign = item.type === 'accrual' ? '+' : '-';
amountClass = item.type === 'accrual' ? 'bonus-accrual' : 'bonus-deduction';
} else if (item.transaction_type === 'debt') {
sign = item.type === 'accrual' ? '+' : '-';
amountClass = item.type === 'accrual' ? 'debt-accrual' : 'debt-payment';
} else if (item.transaction_type === 'referral') {
sign = item.type === 'accrual' ? '+' : '-';
amountClass = item.type === 'accrual' ? 'referral-accrual' : 'referral-deduction';
}
amountText = `${sign}${parseFloat(item.amount).toFixed(2)}`;
li.innerHTML = `<div><div class="desc">${item.description}</div><div class="date">${item.date_str}</div></div><div class="amount ${amountClass}">${amountText}</div>`;
historyList.appendChild(li);
});
} else {
historyList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Нет истории</li>';
}
const modalInvoiceList = document.getElementById('modalInvoiceList');
modalInvoiceList.innerHTML = '';
const userInvoices = (currentUserData.invoices || []).sort((a, b) => new Date(b.date) - new Date(a.date));
if (userInvoices.length > 0) {
userInvoices.forEach(invoice => {
const li = document.createElement('li');
li.innerHTML = `<div class="invoice-info">Накладная #${invoice.invoice_id}<br>${invoice.date_str}</div><div style="display: flex; align-items: center;"><span class="invoice-amount">${parseFloat(invoice.total_amount).toFixed(2)}</span><button class="view-btn" onclick='openAdminInvoiceDetailModal(${JSON.stringify(invoice)})'>👁️</button><button class="delete-btn" onclick='deleteInvoice("${currentUserData.id}", "${invoice.invoice_id}")'>🗑️</button></div>`;
modalInvoiceList.appendChild(li);
});
} else {
modalInvoiceList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Накладных пока нет.</li>';
}
updateCalculations();
}
function openAddClientModal() {
document.getElementById('newClientFirstName').value = '';
document.getElementById('newClientPhone').value = '';
document.getElementById('addClientStatus').textContent = '';
addClientModal.style.display = 'block';
}
function openOrgSettingsModal() {
fetch('/admin/organization_details')
.then(response => response.json())
.then(data => {
document.getElementById('orgName').value = data.name || '';
document.getElementById('orgPhoneNumbers').value = (data.phone_numbers || []).join(',') || '';
document.getElementById('orgAddress').value = data.address || '';
document.getElementById('orgWhatsAppLink').value = data.whatsapp_link || '';
document.getElementById('orgTelegramLink').value = data.telegram_link || '';
document.getElementById('orgStatus').textContent = '';
orgSettingsModal.style.display = 'block';
})
.catch(error => {
console.error('Error fetching organization details:', error);
const orgStatus = document.getElementById('orgStatus');
orgStatus.style.color = 'var(--admin-danger)';
orgStatus.textContent = 'Ошибка загрузки данных.';
orgSettingsModal.style.display = 'block';
});
}
function openBonusSettingsModal() {
fetch('/admin/bonus_settings')
.then(response => response.json())
.then(data => {
document.getElementById('settingInvoiceBonus').value = data.invoice_bonus_percentage || 0;
document.getElementById('settingPromoBonus').value = data.referral_promo_bonus || 0;
document.getElementById('settingReferrerBonus').value = data.referrer_first_purchase_percentage || 0;
document.getElementById('bonusSettingsStatus').textContent = '';
bonusSettingsModal.style.display = 'block';
})
.catch(error => {
console.error('Error fetching bonus settings:', error);
document.getElementById('bonusSettingsStatus').textContent = 'Ошибка загрузки настроек.';
bonusSettingsModal.style.display = 'block';
});
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = 'none';
if (modalId === 'transactionModal') currentUserData = null;
}
function showTab(tabId) {
document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
document.getElementById(tabId).classList.add('active');
document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
document.querySelector(`.tab-btn[data-tab="${tabId}"]`).classList.add('active');
}
document.querySelectorAll('.tab-btn').forEach(button => {
button.addEventListener('click', () => showTab(button.dataset.tab));
});
function updateCalculations() {
if (!currentUserData) return;
}
async function submitTransaction() {
const statusEl = document.getElementById('modalStatus');
statusEl.style.color = 'var(--admin-secondary)';
statusEl.textContent = 'Обработка...';
const payload = {
user_id: document.getElementById('modalUserId').value,
accrue_amount: parseFloat(document.getElementById('accrueAmount').value) || 0,
deduct_amount: parseFloat(document.getElementById('deductAmount').value) || 0,
accrue_referral_amount: parseFloat(document.getElementById('accrueReferralAmount').value) || 0,
deduct_referral_amount: parseFloat(document.getElementById('deductReferralAmount').value) || 0,
add_debt_amount: parseFloat(document.getElementById('addDebtAmount').value) || 0,
repay_debt_amount: parseFloat(document.getElementById('repayDebtAmount').value) || 0,
};
if (Object.values(payload).slice(1).every(v => v <= 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 saveOrgSettings() {
const statusEl = document.getElementById('orgStatus');
statusEl.style.color = 'var(--admin-secondary)';
statusEl.textContent = 'Сохранение...';
const phoneNumbersRaw = document.getElementById('orgPhoneNumbers').value.trim();
const payload = {
name: document.getElementById('orgName').value.trim(),
phone_numbers: phoneNumbersRaw ? phoneNumbersRaw.split(',').map(p => p.trim()) : [],
address: document.getElementById('orgAddress').value.trim(),
whatsapp_link: document.getElementById('orgWhatsAppLink').value.trim(),
telegram_link: document.getElementById('orgTelegramLink').value.trim(),
};
try {
const response = await fetch('/admin/organization_details', {
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(() => closeModal('orgSettingsModal'), 1500);
} else { throw new Error(result.message || 'Произошла ошибка'); }
} catch (error) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = `Ошибка: ${error.message}`;
}
}
async function saveBonusSettings() {
const statusEl = document.getElementById('bonusSettingsStatus');
statusEl.style.color = 'var(--admin-secondary)';
statusEl.textContent = 'Сохранение...';
const payload = {
invoice_bonus_percentage: parseFloat(document.getElementById('settingInvoiceBonus').value) || 0,
referral_promo_bonus: parseFloat(document.getElementById('settingPromoBonus').value) || 0,
referrer_first_purchase_percentage: parseFloat(document.getElementById('settingReferrerBonus').value) || 0,
};
try {
const response = await fetch('/admin/bonus_settings', {
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(() => closeModal('bonusSettingsModal'), 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}`); }
}
function addNewInvoiceItemRow() {
newInvoiceItems.push({ product_name: '', quantity: 1, unit_price: 0, item_total: 0 });
renderNewInvoiceItems();
}
function updateInvoiceItem(index, field, value) {
if (!newInvoiceItems[index]) return;
newInvoiceItems[index][field] = value;
const qty = parseFloat(newInvoiceItems[index].quantity) || 0;
const price = parseFloat(newInvoiceItems[index].unit_price) || 0;
const itemTotal = qty * price;
newInvoiceItems[index].item_total = itemTotal;
const list = document.getElementById('newInvoiceItemsList');
const itemRow = list.children[index];
if (itemRow) {
itemRow.querySelector('.item-total-display').textContent = itemTotal.toFixed(2);
}
updateNewInvoiceTotal();
}
function removeInvoiceItemRow(index) {
newInvoiceItems.splice(index, 1);
renderNewInvoiceItems();
}
function renderNewInvoiceItems() {
const list = document.getElementById('newInvoiceItemsList');
list.innerHTML = '';
newInvoiceItems.forEach((item, index) => {
const itemDiv = document.createElement('div');
itemDiv.className = 'invoice-item-row';
const productName = item.product_name ? String(item.product_name).replace(/"/g, '&quot;') : '';
itemDiv.innerHTML = `
<div class="form-group item-name">
<label>Товар</label>
<input type="text" placeholder="Название товара" value="${productName}" oninput="updateInvoiceItem(${index}, 'product_name', this.value)">
</div>
<div class="form-group item-qty">
<label>Кол-во</label>
<input type="number" step="1" min="1" placeholder="1" value="${item.quantity || '1'}" oninput="updateInvoiceItem(${index}, 'quantity', this.value)">
</div>
<div class="form-group item-price">
<label>Цена</label>
<input type="number" step="0.01" min="0" placeholder="0.00" value="${item.unit_price || ''}" oninput="updateInvoiceItem(${index}, 'unit_price', this.value)">
</div>
<div class="item-total-group">
<label>Сумма</label>
<div class="item-total-display">${(item.item_total || 0).toFixed(2)}</div>
</div>
<button class="action-btn" onclick="removeInvoiceItemRow(${index})">🗑️</button>
`;
list.appendChild(itemDiv);
});
updateNewInvoiceTotal();
}
function updateNewInvoiceTotal() {
if (!currentUserData) return;
const bonusSource = document.querySelector('input[name="bonusSource"]:checked').value;
const availableBonuses = bonusSource === 'main' ? (parseFloat(currentUserData.bonuses) || 0) : (parseFloat(currentUserData.referral_bonuses) || 0);
document.getElementById('invoiceAvailableBonuses').textContent = availableBonuses.toFixed(2);
let total = newInvoiceItems.reduce((sum, item) => sum + (parseFloat(item.item_total) || 0), 0);
document.getElementById('newInvoiceTotalAmount').textContent = total.toFixed(2);
const deductBonusesInput = document.getElementById('invoiceDeductBonuses');
let deductAmount = parseFloat(deductBonusesInput.value) || 0;
let cappedDeductAmount = Math.max(0, Math.min(deductAmount, availableBonuses, total));
if (deductAmount > cappedDeductAmount) {
deductBonusesInput.value = cappedDeductAmount > 0 ? cappedDeductAmount.toFixed(2) : '';
}
let finalAmount = total - cappedDeductAmount;
document.getElementById('invoiceFinalAmount').textContent = finalAmount.toFixed(2);
}
async function submitInvoice() {
const statusEl = document.getElementById('invoiceStatus');
statusEl.style.color = 'var(--admin-secondary)';
statusEl.textContent = 'Сохранение...';
if (!currentUserData) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = 'Пользователь не выбран.';
return;
}
const itemsToAdd = newInvoiceItems.filter(item => item.product_name && item.product_name.trim() !== '' && (item.quantity > 0 || item.unit_price > 0));
if (itemsToAdd.length === 0) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = 'Добавьте хотя бы один товар.';
return;
}
const totalAmount = itemsToAdd.reduce((sum, item) => sum + item.item_total, 0);
const deductBonuses = parseFloat(document.getElementById('invoiceDeductBonuses').value) || 0;
const bonusSource = document.querySelector('input[name="bonusSource"]:checked').value;
const payload = {
user_id: currentUserData.id,
total_amount: totalAmount,
items: itemsToAdd,
deduct_bonuses: deductBonuses,
bonus_source: bonusSource
};
try {
const response = await fetch('/admin/add_invoice', {
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}`;
}
}
function openAdminInvoiceDetailModal(invoiceData) {
document.getElementById('adminInvoiceDetailTitle').textContent = `Накладная #${invoiceData.invoice_id} от ${invoiceData.date_str}`;
const invoiceDetailList = document.getElementById('adminInvoiceDetailList');
invoiceDetailList.innerHTML = '';
invoiceData.items.forEach(item => {
const li = document.createElement('li');
li.className = 'invoice-detail-item';
li.innerHTML = `<span class="item-name">${item.product_name}</span><span class="item-qty-price">${item.quantity} x ${parseFloat(item.unit_price).toFixed(2)}</span><span class="item-total">${parseFloat(item.item_total).toFixed(2)}</span>`;
invoiceDetailList.appendChild(li);
});
const totalDisplay = document.getElementById('adminInvoiceDetailTotal');
let bonusesDeducted = parseFloat(invoiceData.bonuses_deducted || 0);
let totalAmount = parseFloat(invoiceData.total_amount);
let finalAmount = totalAmount - bonusesDeducted;
let bonusSourceText = invoiceData.bonus_source_used === 'referral' ? ' (от друзей)' : ' (основных)';
let totalHTML = `<div><span>Итого:</span><span>${totalAmount.toFixed(2)}</span></div>`;
if (bonusesDeducted > 0) {
totalHTML += `<div><span>Списано бонусов${bonusSourceText}:</span><span style="color: var(--admin-danger);">- ${bonusesDeducted.toFixed(2)}</span></div>`;
totalHTML += `<hr style="border: none; border-top: 1px solid #dee2e6; margin: 5px 0;"><div><strong style="font-size: 1.1em;">К оплате:</strong><strong style="font-size: 1.1em; color: var(--admin-success);">${finalAmount.toFixed(2)}</strong></div>`;
}
totalDisplay.innerHTML = totalHTML;
adminInvoiceDetailModal.style.display = 'block';
}
async function deleteInvoice(userId, invoiceId) {
if (!confirm(`Вы уверены, что хотите удалить накладную #${invoiceId} для клиента ID ${userId}?`)) return;
try {
const response = await fetch('/admin/delete_invoice', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: userId, invoice_id: invoiceId })
});
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');
if (event.target == orgSettingsModal) closeModal('orgSettingsModal');
if (event.target == bonusSettingsModal) closeModal('bonusSettingsModal');
if (event.target == adminInvoiceDetailModal) closeModal('adminInvoiceDetailModal');
}
document.addEventListener('DOMContentLoaded', () => { addNewInvoiceItemRow(); });
</script>
</body>
</html>
"""
@app.route('/')
def index():
user_id_str = request.args.get('user_id_for_test')
user_data = {}
is_first_visit = False
with _data_lock:
if user_id_str and user_id_str in visitor_data_cache:
user_data = visitor_data_cache[user_id_str]
user_data['id'] = user_id_str
is_first_visit = not user_data.get('has_been_welcomed', False)
bonus_history = user_data.get('history', [])
debt_history = user_data.get('debt_history', [])
referral_history = user_data.get('referral_bonus_history', [])
for item in bonus_history: item['transaction_type'] = 'bonus'
for item in debt_history: item['transaction_type'] = 'debt'
for item in referral_history: item['transaction_type'] = 'referral'
user_data['combined_history'] = sorted(bonus_history + debt_history + referral_history, key=lambda x: datetime.fromisoformat(x['date']), reverse=True)
user_data['invoices'] = user_data.get('invoices', [])
else:
user_data = {"id": "N/A", "bonuses": 0, "debts": 0, "referral_bonuses": 0, "combined_history": [], "invoices": [], "referral_code": "N/A"}
org_details = visitor_data_cache.get('organization_details', {})
bonus_settings = visitor_data_cache.get('bonus_program_settings', {})
return render_template_string(TEMPLATE, user=user_data, org_details=org_details, is_first_visit=is_first_visit, bonus_settings=bonus_settings)
@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_info_dict = json.loads(unquote(user_data_parsed['user'][0]))
except Exception as e:
logging.error(f"Could not parse user JSON: {e}")
if is_valid:
tg_user_id = user_info_dict.get('id')
if tg_user_id:
now = datetime.now(ALMATY_TZ)
user_id_to_save = None
with _data_lock:
existing_user_key = next((k for k, u in visitor_data_cache.items() if k != "organization_details" and str(u.get('telegram_id')) == str(tg_user_id)), None)
if existing_user_key:
user_entry = visitor_data_cache[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'),
'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(visitor_data_cache)
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'),
'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': [], 'debts': 0, 'debt_history': [], 'invoices': [],
'referral_code': f'PROMO{new_user_id}', 'referred_by': None, 'referrals': [], 'has_been_welcomed': False,
'referral_bonuses': 0, 'referral_bonus_history': [], 'has_made_first_purchase': False,
}
visitor_data_cache[new_user_id] = user_entry
user_id_to_save = new_user_id
save_visitor_data()
return jsonify({"status": "ok", "verified": True, "user_id": user_id_to_save})
else:
return jsonify({"status": "error", "verified": True, "message": "User ID not found"}), 400
else:
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('/submit_referral', methods=['POST'])
def submit_referral():
try:
data = request.get_json()
user_id = str(data.get('user_id'))
referral_code = data.get('referral_code')
with _data_lock:
if not user_id or user_id not in visitor_data_cache:
return jsonify({"status": "error", "message": "Пользователь не найден."}), 404
user = visitor_data_cache[user_id]
if user.get('has_been_welcomed', False):
return jsonify({"status": "ok", "message": "Вы уже прошли этот шаг."}), 200
user['has_been_welcomed'] = True
bonus_settings = visitor_data_cache.get('bonus_program_settings', {})
promo_bonus = float(bonus_settings.get('referral_promo_bonus', 0))
if referral_code:
referrer_id = next((u_id for u_id, u in visitor_data_cache.items() if u_id not in ["organization_details", "bonus_program_settings"] and u.get('referral_code') == referral_code), None)
if not referrer_id:
return jsonify({"status": "error", "message": "Промокод не найден."}), 404
if referrer_id == user_id:
return jsonify({"status": "error", "message": "Нельзя использовать свой промокод."}), 400
user['referred_by'] = referrer_id
referrer = visitor_data_cache[referrer_id]
if 'referrals' not in referrer: referrer['referrals'] = []
referrer['referrals'].append(user_id)
if promo_bonus > 0:
user['bonuses'] = user.get('bonuses', 0) + promo_bonus
now = datetime.now(ALMATY_TZ)
history_entry = {
"type": "accrual", "amount": promo_bonus, "description": "Бонус за промокод",
"date": now.isoformat(), "date_str": now.strftime('%Y-%m-%d %H:%M:%S')
}
if 'history' not in user: user['history'] = []
user['history'].append(history_entry)
save_visitor_data()
message = "Промокод успешно применен!" if referral_code else "Добро пожаловать!"
return jsonify({"status": "ok", "message": message}), 200
except Exception as e:
logging.exception("Error in /submit_referral endpoint")
return jsonify({"status": "error", "message": "Внутренняя ошибка сервера"}), 500
@app.route('/admin')
def admin_panel():
users_list = []
user_name_map = {uid: f"{ud.get('first_name', '')} {ud.get('last_name', '')}".strip() or f"ID: {uid}" for uid, ud in visitor_data_cache.items() if uid not in ["organization_details", "bonus_program_settings"]}
for user_id, user_data in visitor_data_cache.items():
if user_id in ["organization_details", "bonus_program_settings"]: continue
user_data_copy = user_data.copy()
user_data_copy['id'] = user_id
user_data_copy['referrals_count'] = len(user_data_copy.get('referrals', []))
referrer_id = user_data_copy.get('referred_by')
user_data_copy['referrer_info'] = user_name_map.get(referrer_id, None)
users_list.append(user_data_copy)
total_users = len(users_list)
total_bonuses = sum(u.get('bonuses', 0) for u in users_list)
total_debts = sum(u.get('debts', 0) for u in users_list)
total_referral_bonuses = sum(u.get('referral_bonuses', 0) for u in users_list)
summary_stats = {
"total_users": total_users, "total_bonuses": total_bonuses,
"total_debts": total_debts, "total_referral_bonuses": total_referral_bonuses
}
return render_template_string(ADMIN_TEMPLATE, users=users_list, summary=summary_stats)
@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
with _data_lock:
if any(u.get('phone_number') == phone_number for k, u in visitor_data_cache.items() if k not in ["organization_details", "bonus_program_settings"]):
return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409
now = datetime.now(ALMATY_TZ)
new_id = generate_unique_id(visitor_data_cache)
new_client = {
'id': new_id, 'telegram_id': None, 'first_name': first_name, 'last_name': None,
'username': None, 'photo_url': None, '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': [], 'debts': 0, 'debt_history': [], 'invoices': [],
'referral_code': f'PROMO{new_id}', 'referred_by': None, 'referrals': [], 'has_been_welcomed': True,
'referral_bonuses': 0, 'referral_bonus_history': [], 'has_made_first_purchase': False,
}
visitor_data_cache[new_id] = new_client
save_visitor_data()
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 = str(data.get('user_id'))
accrue_amount = float(data.get('accrue_amount', 0))
deduct_amount = float(data.get('deduct_amount', 0))
accrue_referral_amount = float(data.get('accrue_referral_amount', 0))
deduct_referral_amount = float(data.get('deduct_referral_amount', 0))
add_debt_amount = float(data.get('add_debt_amount', 0))
repay_debt_amount = float(data.get('repay_debt_amount', 0))
if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400
with _data_lock:
if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
user = visitor_data_cache[user_id]
now = datetime.now(ALMATY_TZ)
now_iso, now_str = now.isoformat(), now.strftime('%Y-%m-%d %H:%M:%S')
if deduct_amount > user.get('bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно основных бонусов для списания"}), 400
if deduct_referral_amount > user.get('referral_bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно бонусов от друзей для списания"}), 400
if repay_debt_amount > user.get('debts', 0): return jsonify({"status": "error", "message": "Сумма погашения превышает текущий долг"}), 400
if 'history' not in user: user['history'] = []
if 'referral_bonus_history' not in user: user['referral_bonus_history'] = []
if 'debt_history' not in user: user['debt_history'] = []
user['bonuses'] = round(user.get('bonuses', 0) + accrue_amount - deduct_amount, 2)
if accrue_amount > 0: user['history'].append({"type": "accrual", "amount": accrue_amount, "description": "Начисление бонусов (админ)", "date": now_iso, "date_str": now_str})
if deduct_amount > 0: user['history'].append({"type": "deduction", "amount": deduct_amount, "description": "Списание бонусов (админ)", "date": now_iso, "date_str": now_str})
user['referral_bonuses'] = round(user.get('referral_bonuses', 0) + accrue_referral_amount - deduct_referral_amount, 2)
if accrue_referral_amount > 0: user['referral_bonus_history'].append({"type": "accrual", "amount": accrue_referral_amount, "description": "Начисление бонусов от друзей (админ)", "date": now_iso, "date_str": now_str})
if deduct_referral_amount > 0: user['referral_bonus_history'].append({"type": "deduction", "amount": deduct_referral_amount, "description": "Списание бонусов от друзей (админ)", "date": now_iso, "date_str": now_str})
user['debts'] = round(user.get('debts', 0) + add_debt_amount - repay_debt_amount, 2)
if add_debt_amount > 0: user['debt_history'].append({"type": "accrual", "amount": add_debt_amount, "description": "Добавление долга", "date": now_iso, "date_str": now_str})
if repay_debt_amount > 0: user['debt_history'].append({"type": "payment", "amount": repay_debt_amount, "description": "Погашение долга", "date": now_iso, "date_str": now_str})
save_visitor_data()
return jsonify({"status": "ok", "message": "Transaction successful"}), 200
except Exception as e:
logging.exception("Error in /admin/add_transaction endpoint")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/admin/add_invoice', methods=['POST'])
def add_invoice():
try:
data = request.get_json()
user_id = str(data.get('user_id'))
total_amount = float(data.get('total_amount', 0))
items = data.get('items', [])
deduct_bonuses = float(data.get('deduct_bonuses', 0))
bonus_source = data.get('bonus_source', 'main')
if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400
if not items: return jsonify({"status": "error", "message": "Необходимо добавить товары в накладную."}), 400
with _data_lock:
if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
user = visitor_data_cache[user_id]
if bonus_source == 'main' and deduct_bonuses > user.get('bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно основных бонусов для списания."}), 400
if bonus_source == 'referral' and deduct_bonuses > user.get('referral_bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно бонусов от друзей для списания."}), 400
if deduct_bonuses > total_amount: return jsonify({"status": "error", "message": "Сумма списания не может превышать сумму накладной."}), 400
now = datetime.now(ALMATY_TZ)
now_iso, now_str = now.isoformat(), now.strftime('%Y-%m-%d %H:%M:%S')
invoice_id = str(uuid.uuid4().hex[:8]).upper()
processed_items = [{"product_name": item.get('product_name'), "quantity": float(item.get('quantity', 0)), "unit_price": float(item.get('unit_price', 0)), "item_total": round(float(item.get('quantity', 0)) * float(item.get('unit_price', 0)), 2)} for item in items]
new_invoice = {
"invoice_id": invoice_id, "date": now_iso, "date_str": now_str,
"total_amount": round(total_amount, 2), "items": processed_items,
"bonuses_deducted": round(deduct_bonuses, 2),
"bonus_source_used": bonus_source if deduct_bonuses > 0 else None
}
if 'invoices' not in user: user['invoices'] = []
user['invoices'].append(new_invoice)
if deduct_bonuses > 0:
if bonus_source == 'main':
user['bonuses'] = round(user.get('bonuses', 0) - deduct_bonuses, 2)
if 'history' not in user: user['history'] = []
user['history'].append({"type": "deduction", "amount": deduct_bonuses, "description": f"Оплата по накладной #{invoice_id}", "date": now_iso, "date_str": now_str})
elif bonus_source == 'referral':
user['referral_bonuses'] = round(user.get('referral_bonuses', 0) - deduct_bonuses, 2)
if 'referral_bonus_history' not in user: user['referral_bonus_history'] = []
user['referral_bonus_history'].append({"type": "deduction", "amount": deduct_bonuses, "description": f"Оплата по накладной #{invoice_id}", "date": now_iso, "date_str": now_str})
bonus_settings = visitor_data_cache.get('bonus_program_settings', {})
invoice_bonus_percentage = float(bonus_settings.get('invoice_bonus_percentage', 0))
if deduct_bonuses <= 0 and invoice_bonus_percentage > 0 and total_amount > 0:
bonus_from_invoice = round((total_amount * invoice_bonus_percentage) / 100, 2)
if bonus_from_invoice > 0:
user['bonuses'] = user.get('bonuses', 0) + bonus_from_invoice
if 'history' not in user: user['history'] = []
user['history'].append({"type": "accrual", "amount": bonus_from_invoice, "description": f"Бонус с накладной #{invoice_id}", "date": now_iso, "date_str": now_str})
if not user.get('has_made_first_purchase', False) and total_amount > 0:
user['has_made_first_purchase'] = True
referrer_id = user.get('referred_by')
if referrer_id and referrer_id in visitor_data_cache:
referrer = visitor_data_cache[referrer_id]
referrer_bonus_percentage = float(bonus_settings.get('referrer_first_purchase_percentage', 0))
if referrer_bonus_percentage > 0:
commission = round((total_amount * referrer_bonus_percentage) / 100, 2)
if commission > 0:
referrer['referral_bonuses'] = referrer.get('referral_bonuses', 0) + commission
if 'referral_bonus_history' not in referrer: referrer['referral_bonus_history'] = []
referrer['referral_bonus_history'].append({
"type": "accrual", "amount": commission,
"description": f"Бонус от друга {user.get('first_name', 'ID:'+user_id)}",
"date": now_iso, "date_str": now_str
})
save_visitor_data()
return jsonify({"status": "ok", "message": "Invoice added successfully", "invoice_id": invoice_id}), 200
except Exception as e:
logging.exception("Error in /admin/add_invoice endpoint")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/admin/delete_invoice', methods=['POST'])
def delete_invoice():
try:
data = request.get_json()
user_id, invoice_id = str(data.get('user_id')), data.get('invoice_id')
if not user_id or not invoice_id: return jsonify({"status": "error", "message": "User ID and Invoice ID are required"}), 400
with _data_lock:
if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
user = visitor_data_cache[user_id]
if 'invoices' not in user: return jsonify({"status": "error", "message": "User has no invoices"}), 404
original_count = len(user['invoices'])
user['invoices'] = [inv for inv in user['invoices'] if inv.get('invoice_id') != invoice_id]
if len(user['invoices']) == original_count: return jsonify({"status": "error", "message": "Invoice not found for this user"}), 404
save_visitor_data()
return jsonify({"status": "ok", "message": "Invoice deleted successfully"}), 200
except Exception as e:
logging.exception("Error in /admin/delete_invoice endpoint")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/admin/delete_client', methods=['POST'])
def delete_client():
try:
user_id = str(request.get_json().get('user_id'))
if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400
with _data_lock:
if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404
if visitor_data_cache[user_id].get('telegram_id') is not None: return jsonify({"status": "error", "message": "Cannot delete a Telegram-linked user"}), 403
user_to_delete = visitor_data_cache[user_id]
referrer_id = user_to_delete.get('referred_by')
if referrer_id and referrer_id in visitor_data_cache:
referrer = visitor_data_cache[referrer_id]
if 'referrals' in referrer and user_id in referrer['referrals']:
referrer['referrals'].remove(user_id)
del visitor_data_cache[user_id]
save_visitor_data()
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
@app.route('/admin/organization_details', methods=['GET'])
def get_organization_details():
try:
return jsonify(visitor_data_cache.get('organization_details', {})), 200
except Exception as e:
logging.exception("Error getting organization details")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/admin/organization_details', methods=['POST'])
def save_organization_details():
try:
data = request.get_json()
with _data_lock:
visitor_data_cache['organization_details'] = {
"name": data.get("name", ""), "phone_numbers": data.get("phone_numbers", []),
"address": data.get("address", ""), "whatsapp_link": data.get("whatsapp_link", ""),
"telegram_link": data.get("telegram_link", "")
}
save_visitor_data()
return jsonify({"status": "ok", "message": "Organization details saved successfully"}), 200
except Exception as e:
logging.exception("Error saving organization details")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/admin/bonus_settings', methods=['GET'])
def get_bonus_settings():
try:
return jsonify(visitor_data_cache.get('bonus_program_settings', {})), 200
except Exception as e:
logging.exception("Error getting bonus settings")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/admin/bonus_settings', methods=['POST'])
def save_bonus_settings():
try:
data = request.get_json()
with _data_lock:
settings = visitor_data_cache.get('bonus_program_settings', {})
settings['invoice_bonus_percentage'] = float(data.get('invoice_bonus_percentage', 0))
settings['referral_promo_bonus'] = float(data.get('referral_promo_bonus', 0))
settings['referrer_first_purchase_percentage'] = float(data.get('referrer_first_purchase_percentage', 0))
visitor_data_cache['bonus_program_settings'] = settings
save_visitor_data()
return jsonify({"status": "ok", "message": "Bonus program settings saved"}), 200
except Exception as e:
logging.exception("Error saving bonus settings")
return jsonify({"status": "error", "message": str(e)}), 500
if __name__ == '__main__':
print("--- BONUS SYSTEM SERVER ---")
print(f"Server starting on http://{HOST}:{PORT}")
print("Attempting to load local data file...")
load_visitor_data()
if not visitor_data_cache or len(visitor_data_cache) <= 2:
print("Local data file not found or is empty.")
if HF_TOKEN_READ:
print("Attempting to restore data from Hugging Face...")
if not download_data_from_hf():
print("Failed to restore from Hugging Face. Starting fresh.")
else:
print("HF_TOKEN_READ not set. Cannot restore from backup. Starting fresh.")
else:
user_count = len([k for k in visitor_data_cache if k not in ['organization_details', 'bonus_program_settings']])
print(f"Successfully loaded data for {user_count} users from local file.")
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).")
else:
print("WARNING: HF_TOKEN_WRITE not set. Periodic backups to Hugging Face are disabled.")
print("--- Server Ready ---")
app.run(host=HOST, port=PORT, debug=False)