Examplebonus33 / app (19).py
Kgshop's picture
Upload app (19).py
ed36cc7 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")
BISHKEK_TZ = pytz.timezone('Asia/Bishkek')
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:
# Generate a 5-digit numeric ID
new_id = str(random.randint(10000, 99999))
# Check if this ID exists as a client ID or a partner code
is_duplicate = False
for user_id, user_data in all_data.items():
if user_id == "organization_details": continue
if user_id == new_id or user_data.get('partner_code') == new_id:
is_duplicate = True
break
if not is_duplicate:
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 = {}
# Ensure organization_details and initial user fields exist after loading
if "organization_details" not in visitor_data_cache:
visitor_data_cache["organization_details"] = {}
if 'referral_percentage' not in visitor_data_cache["organization_details"]:
visitor_data_cache["organization_details"]['referral_percentage'] = 2.0 # Default 2%
# Ensure all user entries have required fields (partner_code, referred_by, referred_users, invoices)
# This is a migration step for existing data
users_to_update = {}
for user_id, user_data in visitor_data_cache.items():
if user_id == "organization_details": continue
updated_user_data = user_data.copy()
if 'partner_code' not in updated_user_data or not updated_user_data['partner_code']:
updated_user_data['partner_code'] = generate_unique_id(visitor_data_cache) # Generate unique code
if 'referred_by' not in updated_user_data:
updated_user_data['referred_by'] = None
if 'referred_users' not in updated_user_data or not isinstance(updated_user_data['referred_users'], list):
updated_user_data['referred_users'] = []
if 'invoices' not in updated_user_data or not isinstance(updated_user_data['invoices'], list):
updated_user_data['invoices'] = []
if updated_user_data != user_data:
users_to_update[user_id] = updated_user_data
for user_id, user_data in users_to_update.items():
visitor_data_cache[user_id] = user_data
logging.info(f"Migrated user data for ID {user_id}")
if users_to_update:
# Rebuild referred_users lists based on current referred_by fields
temp_referred_users = {}
for user_id, user_data in visitor_data_cache.items():
if user_id == "organization_details": continue
user_data['referred_users'] = [] # Clear old list
referred_by_code = user_data.get('referred_by')
if referred_by_code:
temp_referred_users.setdefault(referred_by_code, []).append(user_id)
# Update the actual referred_users lists
for referrer_code, referred_ids in temp_referred_users.items():
found_referrer = False
for user_id, user_data in visitor_data_cache.items():
if user_id == "organization_details": continue
if user_data.get('partner_code') == referrer_code:
user_data['referred_users'] = referred_ids
found_referrer = True
break
if not found_referrer:
logging.warning(f"Referrer with code {referrer_code} not found for referred users {referred_ids}. Clearing referred_by.")
# Clear referred_by for these users if referrer doesn't exist
for referred_id in referred_ids:
if referred_id in visitor_data_cache and referred_id != "organization_details":
visitor_data_cache[referred_id]['referred_by'] = None
logging.info("Rebuilt referred_users lists.")
# Save the potentially updated cache after migration and rebuild
save_visitor_data(visitor_data_cache)
return True
except RepositoryNotFoundError:
logging.error(f"Hugging Face repository '{REPO_ID}' not found. Cannot download data.")
except Exception as e:
logging.error(f"Error downloading data from Hugging Face: {e}")
return False
def load_visitor_data():
global visitor_data_cache
with _data_lock:
if not visitor_data_cache:
try:
with open(DATA_FILE, 'r', encoding='utf-8') as f:
visitor_data_cache = json.load(f)
logging.info("Visitor data loaded from local JSON.")
except FileNotFoundError:
logging.warning(f"{DATA_FILE} not found locally. Starting with empty data.")
visitor_data_cache = {"organization_details": {}}
except json.JSONDecodeError:
logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.")
visitor_data_cache = {"organization_details": {}}
except Exception as e:
logging.error(f"Unexpected error loading visitor data: {e}")
visitor_data_cache = {"organization_details": {}}
# Ensure organization_details key exists
if "organization_details" not in visitor_data_cache:
visitor_data_cache["organization_details"] = {}
if 'referral_percentage' not in visitor_data_cache["organization_details"]:
visitor_data_cache["organization_details"]['referral_percentage'] = 2.0 # Default
# Ensure all user entries have required fields on load if not already present
users_to_update = {}
for user_id, user_data in visitor_data_cache.items():
if user_id == "organization_details": continue
updated_user_data = user_data.copy() # Copy to detect changes
if 'partner_code' not in updated_user_data or not updated_user_data['partner_code']:
# Generating a unique code here on load might be problematic if called frequently without saving.
# Better to ensure it's generated on user creation. If missing, leave as None or generate and mark for save.
# Let's ensure generation only happens on creation (verify or add_client).
# If it's missing on load, maybe just log a warning or assign None. Let's assign None for now.
# The initial download/load function handles generation for missing codes on migration.
updated_user_data['partner_code'] = updated_user_data.get('partner_code') # Keep existing or None
if 'referred_by' not in updated_user_data:
updated_user_data['referred_by'] = None
if 'referred_users' not in updated_user_data or not isinstance(updated_user_data['referred_users'], list):
updated_user_data['referred_users'] = []
if 'invoices' not in updated_user_data or not isinstance(updated_user_data['invoices'], list):
updated_user_data['invoices'] = []
if 'debt_history' not in updated_user_data or not isinstance(updated_user_data['debt_history'], list):
updated_user_data['debt_history'] = []
if 'history' not in updated_user_data or not isinstance(updated_user_data['history'], list):
updated_user_data['history'] = []
if updated_user_data != user_data:
users_to_update[user_id] = updated_user_data # Mark for potential update
if users_to_update:
logging.warning(f"Missing keys in {len(users_to_update)} user entries. Updating cache but not saving automatically.")
for user_id, updated_data in users_to_update.items():
visitor_data_cache[user_id] = updated_data
# Rebuild referred_users lists on every load just to be safe
temp_referred_users = {}
for user_id, user_data in visitor_data_cache.items():
if user_id == "organization_details": continue
user_data['referred_users'] = [] # Clear old list
referred_by_code = user_data.get('referred_by')
if referred_by_code:
temp_referred_users.setdefault(referred_by_code, []).append(user_id)
# Update the actual referred_users lists
for referrer_code, referred_ids in temp_referred_users.items():
found_referrer = False
for user_id, user_data in visitor_data_cache.items():
if user_id == "organization_details": continue
if user_data.get('partner_code') == referrer_code:
user_data['referred_users'] = referred_ids
found_referrer = True
break
if not found_referrer:
logging.warning(f"Referrer with code {referrer_code} not found during referred_users rebuild.")
# Don't clear referred_by here, it's safer to keep the link even if referrer was deleted manually
return visitor_data_cache
def save_visitor_data(data_to_save):
with _data_lock:
try:
# Ensure visitor_data_cache is the source of truth before saving
# In calling code, modifications should happen directly on visitor_data_cache
# This function now simply dumps the current state of visitor_data_cache
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:
# Check file size *within* the lock just before reading
file_content_exists = os.path.getsize(DATA_FILE) > 0
if not file_content_exists:
logging.warning(f"{DATA_FILE} is empty. Skipping upload.")
return
logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}/{HF_DATA_FILE_PATH}...")
api.upload_file(
path_or_fileobj=DATA_FILE,
path_in_repo=HF_DATA_FILE_PATH,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN_WRITE,
commit_message=f"Update bonus data {datetime.now(BISHKEK_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 = []
for key, value in sorted(parsed_data.items()):
data_check_list.append(f"{key}={value[0]}")
data_check_string = "\n".join(data_check_list)
secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest()
calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
if calculated_hash == received_hash:
auth_date = int(parsed_data.get('auth_date', [0])[0])
current_time = int(time.time())
if current_time - auth_date > 86400:
logging.warning(f"Telegram InitData is older than 24 hours (Auth Date: {auth_date}, Current: {current_time}).")
return parsed_data, True
else:
logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}")
return parsed_data, False
except Exception as e:
logging.error(f"Error verifying Telegram data: {e}")
return None, False
TEMPLATE = """
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover">
<title>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 {
--brand-yellow: #FFC107;
--brand-black: #101010;
--brand-red: #F44336;
--card-bg: #1c1c1e;
--text-color: #ffffff;
--text-secondary-color: #a0a0a0;
--border-radius: 16px;
--padding-m: 16px;
--padding-l: 24px;
--font-family: 'Manrope', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--shadow-color: rgba(255, 193, 7, 0.15);
--shadow-glow: 0 0 35px var(--shadow-color);
--shadow-color-red: rgba(244, 67, 54, 0.15);
--shadow-glow-red: 0 0 35px var(--shadow-color-red);
--button-bg: var(--brand-yellow);
--button-text: var(--brand-black);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
background-color: var(--brand-black);
font-family: var(--font-family);
color: var(--text-color);
padding: var(--padding-m);
overscroll-behavior-y: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
visibility: hidden;
min-height: 100vh;
}
.container {
max-width: 600px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: var(--padding-m);
}
.header {
text-align: left;
padding: var(--padding-m) 0;
margin-bottom: 0;
}
.logo {
font-size: 2.5em;
font-weight: 800;
color: var(--text-color);
letter-spacing: -1px;
}
.logo span { color: var(--brand-yellow); }
.welcome-text {
font-size: 1em;
color: var(--text-secondary-color);
margin-top: 4px;
}
.nav-buttons {
display: flex;
justify-content: space-around;
background-color: var(--card-bg);
border-radius: var(--border-radius);
padding: 8px;
margin-bottom: var(--padding-m);
}
.nav-btn {
flex-grow: 1;
padding: 10px 15px;
border: none;
border-radius: 12px;
background-color: transparent;
color: var(--text-secondary-color);
font-family: var(--font-family);
font-weight: 600;
font-size: 1em;
cursor: pointer;
transition: background-color 0.2s, color 0.2s;
}
.nav-btn.active {
background-color: var(--brand-yellow);
color: var(--brand-black);
box-shadow: 0 2px 10px rgba(255,193,7,0.3);
}
.content-section {
display: none;
flex-direction: column;
gap: var(--padding-m);
}
.content-section.active {
display: flex;
}
.card-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--padding-m);
}
.bonus-card, .debt-card {
background: linear-gradient(145deg, #2a2a2a, #1c1c1c);
border-radius: calc(var(--border-radius) + 8px);
padding: var(--padding-l);
text-align: center;
position: relative;
overflow: hidden;
}
.bonus-card {
box-shadow: var(--shadow-glow);
border: 1px solid rgba(255, 193, 7, 0.2);
}
.debt-card {
box-shadow: var(--shadow-glow-red);
border: 1px solid rgba(244, 67, 54, 0.2);
}
.card-label {
font-size: 1.1em;
font-weight: 500;
color: var(--text-secondary-color);
margin-bottom: 12px;
}
.bonus-amount {
font-size: 3em;
font-weight: 800;
color: var(--brand-yellow);
letter-spacing: -2px;
line-height: 1;
}
.debt-amount {
font-size: 3em;
font-weight: 800;
color: var(--brand-red);
letter-spacing: -2px;
line-height: 1;
}
.client-id-card, .partner-section, .referred-by-section {
background-color: var(--card-bg);
border-radius: var(--border-radius);
padding: var(--padding-m);
display: flex;
flex-direction: column; /* Stack content vertically */
gap: 8px;
}
.client-id-card {
flex-direction: row; /* Keep client ID horizontal */
justify-content: space-between;
align-items: center;
}
.client-id-label, .partner-label, .referred-by-label {
font-weight: 500;
color: var(--text-secondary-color);
}
.client-id-value {
font-size: 1.3em;
font-weight: 700;
color: var(--brand-yellow);
letter-spacing: 2px;
background-color: rgba(255,193,7,0.1);
padding: 4px 10px;
border-radius: 8px;
}
.partner-code-display, .referred-by-value {
font-size: 1.1em;
font-weight: 700;
color: var(--text-color);
}
.partner-code-display {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
background-color: rgba(255,193,7,0.05);
padding: 8px 12px;
border-radius: 8px;
}
.partner-code-value {
font-size: 1.2em;
font-weight: 800;
color: var(--brand-yellow);
letter-spacing: 1px;
}
.copy-btn {
background-color: var(--button-bg);
color: var(--button-text);
border: none;
padding: 6px 12px;
border-radius: 6px;
font-weight: 600;
cursor: pointer;
font-size: 0.9em;
}
.copy-btn:active {
opacity: 0.8;
}
.activate-partner-section {
background-color: var(--card-bg);
border-radius: var(--border-radius);
padding: var(--padding-m);
display: flex;
flex-direction: column;
gap: 12px;
}
.activate-partner-section h3 {
font-size: 1.2em;
font-weight: 700;
margin-bottom: 4px;
}
.activate-form {
display: flex;
gap: 10px;
}
.activate-form input[type="text"] {
flex-grow: 1;
padding: 10px;
border-radius: 8px;
border: 1px solid rgba(255,255,255,0.1);
background-color: rgba(0,0,0,0.2);
color: var(--text-color);
font-family: var(--font-family);
font-size: 1em;
}
.activate-form input[type="text"]::placeholder {
color: var(--text-secondary-color);
}
.activate-form button {
padding: 10px 15px;
border: none;
border-radius: 8px;
background-color: var(--button-bg);
color: var(--button-text);
font-family: var(--font-family);
font-weight: 600;
cursor: pointer;
}
.activate-status {
font-size: 0.9em;
color: var(--text-secondary-color);
min-height: 1.2em;
}
.history-section, .invoices-section, .business-card-section {
background-color: var(--card-bg);
border-radius: var(--border-radius);
padding: var(--padding-l);
display: flex;
flex-direction: column;
gap: var(--padding-m);
}
.history-title, .invoices-title, .business-card-title {
font-size: 1.4em;
font-weight: 700;
padding-bottom: var(--padding-m);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.history-list, .invoices-list {
list-style: none;
padding: 0;
margin: 0;
max-height: 35vh;
overflow-y: auto;
}
.history-item, .invoice-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 14px 4px;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.history-item:last-child, .invoice-item:last-child { border-bottom: none; }
.history-details, .invoice-details { display: flex; flex-direction: column; }
.history-description, .invoice-description { font-size: 1em; font-weight: 500; }
.history-date, .invoice-date { font-size: 0.8em; color: var(--text-secondary-color); margin-top: 4px; }
.history-amount, .invoice-amount { font-size: 1.1em; font-weight: 700; }
.history-amount.accrual { color: #4CAF50; } /* Bonus accrual */
.history-amount.deduction { color: #F44336; } /* Bonus deduction */
.history-amount.referral-accrual { color: #2196F3; } /* Referral bonus accrual */
.history-amount.debt-accrual { color: #F44336; } /* Debt increase */
.history-amount.debt-payment { color: #4CAF50; } /* Debt decrease (payment) */
.invoice-amount { color: var(--brand-yellow); }
.no-history, .no-invoices {
text-align: center;
color: var(--text-secondary-color);
padding: 2rem 0;
}
/* Business Card Styles */
.business-card-item {
margin-bottom: 10px;
}
.business-card-label {
font-weight: 500;
color: var(--text-secondary-color);
margin-bottom: 4px;
}
.business-card-value {
font-size: 1.1em;
font-weight: 600;
color: var(--text-color);
}
.business-card-value a {
color: var(--brand-yellow);
text-decoration: none;
word-break: break-all;
}
.business-card-value a:hover {
text-decoration: underline;
}
.business-card-phone-list {
list-style: none;
padding: 0;
margin: 0;
}
.business-card-phone-item {
margin-bottom: 5px;
}
.business-card-phone-item a {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--text-color);
text-decoration: none;
background-color: #2a2a2a;
padding: 8px 12px;
border-radius: 8px;
transition: background-color 0.2s;
}
.business-card-phone-item a:hover {
background-color: #3a3a3a;
}
.business-card-phone-item img {
height: 20px;
width: 20px;
}
/* Invoice Detail Modal */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.7);
backdrop-filter: blur(5px);
-webkit-backdrop-filter: blur(5px);
}
.modal-content {
background-color: var(--card-bg);
margin: 15% auto;
padding: var(--padding-l);
border-radius: var(--border-radius);
max-width: 90%;
width: 500px;
box-shadow: 0 5px 15px rgba(0,0,0,0.5);
position: relative;
}
.modal-close {
color: var(--text-secondary-color);
position: absolute;
top: 10px;
right: 20px;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.modal-close:hover,
.modal-close:focus {
color: var(--text-color);
text-decoration: none;
cursor: pointer;
}
.modal-title {
font-size: 1.5em;
font-weight: 700;
margin-bottom: var(--padding-m);
color: var(--brand-yellow);
}
.invoice-detail-list {
list-style: none;
padding: 0;
margin: 0;
}
.invoice-detail-item {
display: flex;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px dashed rgba(255,255,255,0.1);
}
.invoice-detail-item:last-child {
border-bottom: none;
}
.item-name {
font-weight: 500;
flex-basis: 60%;
}
.item-qty-price {
font-size: 0.9em;
color: var(--text-secondary-color);
flex-basis: 20%;
text-align: right;
}
.item-total {
font-weight: 700;
flex-basis: 20%;
text-align: right;
color: var(--brand-yellow);
}
.invoice-total-display {
padding-top: var(--padding-m);
border-top: 1px solid rgba(255,255,255,0.2);
margin-top: var(--padding-m);
display: flex;
justify-content: space-between;
font-size: 1.2em;
font-weight: 700;
}
.invoice-total-display span:first-child {
color: var(--text-color);
}
.invoice-total-display span:last-child {
color: var(--brand-yellow);
}
</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="card-grid">
<div class="bonus-card">
<p class="card-label">Ваши бонусы</p>
<p class="bonus-amount">{{ "%.2f"|format(user.bonuses|float) }}</p>
</div>
<div class="debt-card">
<p class="card-label">Ваш долг</p>
<p class="debt-amount">{{ "%.2f"|format(user.debts|float) }}</p>
</div>
</section>
<section class="client-id-card">
<p class="client-id-label">Ваш ID клиента</p>
<p class="client-id-value">{{ user.id }}</p>
</section>
<section class="partner-section">
<p class="partner-label">Ваш партнерский код</p>
<div class="partner-code-display">
<span class="partner-code-value">{{ user.partner_code | default('Нет кода') }}</span>
{% if user.partner_code %}
<button class="copy-btn" onclick="copyPartnerCode('{{ user.partner_code }}')">Копировать</button>
{% endif %}
</div>
</section>
<section class="referred-by-section">
<p class="referred-by-label">Вас пригласил</p>
<p class="referred-by-value">{{ user.referred_by | default('Никто') }}</p>
</section>
{% if not user.referred_by %}
<section class="activate-partner-section">
<h3>Активировать партнерский код</h3>
<div class="activate-form">
<input type="text" id="partnerCodeInput" placeholder="Введите код">
<button onclick="activatePartnerCode()">Активировать</button>
</div>
<p id="activateStatus" class="activate-status"></p>
</section>
{% endif %}
<section class="history-section">
<h2 class="history-title">История операций</h2>
{% if user.combined_history %}
<ul class="history-list">
{% for item in user.combined_history %}
<li class="history-item">
<div class="history-details">
<span class="history-description">{{ item.description }}</span>
<span class="history-date">{{ item.date_str }}</span>
</div>
{% if item.transaction_type == 'bonus' %}
<span class="history-amount {{ 'accrual' if item.type == 'accrual' else ('referral-accrual' if item.type == 'referral' else 'deduction') }}">
{{ '+' if item.type in ['accrual', 'referral'] else '-' }}{{ "%.2f"|format(item.amount|float) }}
</span>
{% elif item.transaction_type == 'debt' %}
<span class="history-amount {{ 'debt-accrual' if item.type == 'accrual' else 'debt-payment' }}">
{{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }}
</span>
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<p class="no-history">Операций пока не было.</p>
{% endif %}
</section>
</div>
<div id="invoices-section" class="content-section">
<section class="invoices-section">
<h2 class="invoices-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="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-invoices">Накладных пока нет.</p>
{% endif %}
</section>
</div>
<div id="business-card-section" class="content-section">
<section class="business-card-section">
<h2 class="business-card-title">Визитка организации</h2>
{% if org_details %}
<div class="business-card-item">
<div class="business-card-label">Название организации</div>
<div class="business-card-value">{{ org_details.name | default('Не указано') }}</div>
</div>
<div class="business-card-item">
<div class="business-card-label">Номера телефонов</div>
{% if org_details.phone_numbers %}
<ul class="business-card-phone-list">
{% for phone in org_details.phone_numbers %}
<li class="business-card-phone-item">
<a href="tel:{{ phone }}">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJjdXJyZW50Q29sb3IiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWNvaW49InJvdW5kIj48cGF0aCBkPSJtMjIuMDIyIDEuOTY3LTMuMDkgMy41MjNhOC40OCA4LjQ4IDAgMCAwLTEzLjA5OSAwTDEuOTc4IDEuOTY3Yy0uOTc0LTEuMTA3LTIuNTI1LS40MS0yLjUxMiAxLjAzNXYxOC44NjhjLjAwMSAxLjQ0NSAxLjUyOCAyLjEzNiAyLjQ4OCAxLjAzN2wzLjA5LTMuNTIzYTEwLjE2IDEwLjE2IDAgMCAwIDEzLjA5OSAwbDMuMDkgMy41MjNjLjk3NCAxLjEwNyAyLjUyNS40MSAyLjUxMi0xLjAzN1YyLjAwMWMtLjAwMS0xLjQ0NS0xLjUyOC0yLjEzNi0yLjQ4OC0xLjAzN3zeiIvPjxwYXRoIGQ9Im03LjUgMi45NzZjMS4yMjUuMDYxIDIuNDUuMDkxIDMuNjc1LjA5MXMyLjQ1LS4wMzEgMy42NzUtLjA5MWMuNjg3LS4wMzQgMS40MzMuMzI1IDEuNzA5Ljc0N2wxLjQ3MyAxLjY3OGMuNDkuNTU3LjgzNyAxLjI2Ny44OTkgMi4wODMuMDQxLjU1MS4wNjIgMS4xLjA2MiAxLjY2djEuNTA0YzAgLjc3NS0uMTcgMS41NTMtLjUwOCAyLjIzMy0uNDcyLjkyNS0xLjExNyAxLjc0OC0xLjkzNSAyLjM4OGwtLjEzNC4xMDVjLS43NTQuNTgzLTEuNjQ3Ljk3NS0yLjU2MiAxLjE4NC0uNjAyLjEzNi0xLjAwOS4yMDgtMS43MjUuMjA4LTEuMTE1IDAtLjc1NC0uMTUzIDMuNjgyLS4xNTMgNS41NDJzLjE1NCA0Ljc4Ni4xNTMgNS41NDJjLjAwMi0uNjU3LS4wNzgtMS4yNy0uMjItMS44MjQtLjE0OC0uNTU4LS40MTctMS4wODgtLjc2NC0xLjU1MS0uNjMyLS44NDUtMS40NDctMS41NTctMi40MTItMi4wNjItLjk2My0uNTA3LTEuOTk0LS44Mi0zLjA0Ni0uOTUyLS44MTMtLjEwNC0xLjU3MS0uMTQ1LTIuMzM4LS4wOTktLjY5NC4wMTEtMS4zMzcuMTA2LTEuOTI0LjI4NS0uNTg5LjE4NC0xLjEyNi40MjEtMS42MDEuNjkzLS40NzYuMjczLS45MDYuNTc0LTEuMjk3Ljg5LS4zODguMzE0LS43NDMuNjQ3LTEuMDY3Ljk5OC0uMzI2LjM1My0uNjQ2LjcyMi0wLjk1OS4xMDU5LTMuMTMuMzI4LS42Mi42NTMtLjkyMS45NzUtLjI5NC4zMTEtLjU3Ni42MjMtLjg0NC45MzItLjI3LjMwOS0uNTIuNjE3LS43NTcuOTE4LS4xOTcuMjU0LS4zNjEuNDkzLS40ODEuNzI1LS4xMTkuMjMyLS4xODUuNDUyLS4xOTMuNTkzLS4wMDkuMTQ1LS4wMTQuMjkzLS4wMTYuNDQxdjEuNzZjMCAuNTc2LS4xNzUgMS4xMjItLjQ0NyAxLjU2LS4yMjcuMzkzLS41NjUuNTk5LTEuMDE5LjU5OS0xLjE4Ni0uMDAxLTEuOTk2LTEuMzk3LTIuMjk2LTIuODQyLS4zMjMtMS41NTgtLjMyMy00LjU2OS0uMzIzLTYuNDExcy4wMTUtNC44NTQuMzIzLTYuNDEyczAuMjk5LTEuNDQ1IDEuMTEtMi44NDEgMi4yOTYtMi44NDIuNDU0LjAwNy43ODEuMjU5IDEuMDE5LjYwOS4yMTUuMzM0LjMyMy43My4zMjMgMS4xNDd2Ljk1Yy4wMyAxLjMxNC0uMDE1IDIuNjEtLjE0NyAzLjg3NS0uMTA2IDEuMDMtLjIzNCAyLjA0Ni0uMzUxIDIuOTk2bC41OTMtLjM3OWMuMzI2LS4yMDYuNjgyLS4zODEgMS4wNDktLjU3MS4zODYtLjE5Ny43OS0uMzY1IDEuMTk0LS40OTQuNDA1LS4xMjkuNzguMjMzIDEuMTI4LS4yOTAuMzQyLS4wNTguNjA0LS4wNzQuNzgyLS4wNDdaIi8+PC9zdmc+">
{{ phone }}
</a>
</li>
{% endfor %}
</ul>
{% else %}
<div class="business-card-value">Не указано</div>
{% endif %}
</div>
<div class="business-card-item">
<div class="business-card-label">Адрес</div>
<div class="business-card-value">{{ org_details.address | default('Не указано') }}</div>
</div>
<div class="business-card-item">
<div class="business-card-label">WhatsApp</div>
<div class="business-card-value">
{% if org_details.whatsapp_link %}
<a href="{{ org_details.whatsapp_link }}" target="_blank">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iI2ZmZiIgY2xhc3M9ImJpIGJpLXdoYXRzYXBwIiB2aWV3Qm94PSIwIDAgMTYgMTYiPjxwYXRoIGQ9Ik0xMy42NzYgMS40NTJBMTAuNTE1IDEwLjUxNSAwIDAgMCA3Ljg4MyAwQzMuNTEgMCAuMDYzIDMuNDQuMDYzIDcuNjU0YzAgMS40MS4zNDcgMi44NjIgLjk2NiA0LjExOC4wNC4wNy4wNjYuMTc2LjA3My4yOTlsLjA2NSAxLjg5MmExLjIzMyAxLjIzMyAwIDAgMCAxLjU1MyAxLjQ1NmwxLjg4Ljc4Yy4xMzYuMDU2LjI3Ni4wOTYuNDI4.1NzIgMS4yNTYuNjY4IDIuNjE0Ljk4MiA0LjA0OC45ODIgNC4zNzIgMCA3LjkxLTMuNDQgNy45MS03LjY1NCAwLTIuMDQyLS44NS0zLjk2NS0yLjM0MS01LjM1M1ptLS42NzYgOS4yMzFhLjg4MS44ODEgMCAwIDEtMS4yMjUuMDM2bC0uNzk0LS40ODMtLjQ2NC4zNjYtLjY1MS0uNDktMS4xNjYgMS4xNjYtLjUzLS4zMTctLjA4NC41NTUtLjEwMi40NTktLjI1MS4xNjItLjU3LjU3LS41NTUuMDgyLS4zMjIuMDY5LS42Mi0uMTc3LS45ODQtLjE5LS45MDgtLjYxNy0uNDc4LS45MDktLjY3Ny0uNzUxLS40MzQtMS4xNzgtLjMyMi0xLjQ3MS0uMzIyLS42MDcgMC0uODguMDQyLS45NjYuMDg4LS40OTcuMjU3LS42MTEuNzMyLS42MTEgMS4xMzdhMS42MzkgMS42MzkgMCAwIDAgLjQ4NiAxLjY5Yy40MTYuNDE2Ljc2Mi43MjQuNzYyLjk1NSAwIC41NDIuMjgyIDEuMDQ2LjMwNCAxLjQxMS41ODYgMS4wNTEgMS43NzUgMS44NDcgMy4wNCAyLjAxOCAxLjMxMi4xNzcgMi4xMDYuMDk1IDIuNzYzLjA3Mi4wOTYtLjE1LjM3Mi0uMjg1LjcwMi0uNDgzLjMxLS40OC41MDktLjUxNS42NjktLjQ1Mi4xMDkuMDUxLjQxNy4yMTEuNDYzLjI2Ny4xNDEuMDgyLjI4NC4xNjEuNDQzLjIyNWExLjIyNyAxLjIyNyAwIDAgMCAuNzQ2LjAyNGwuMjg0LS4xMzVhMy45NjcgMy45NjcgMCAwIDAgLjY2Mi0uNjQzLjkwOC45MDggMCAwIDAgLjMwMi0uNjc4LjE5OC4xOTggMCAwIDAgMC0uMTU2LjgxNS44MTUgMCAwIDAgMC0uNDc3eiIvPjwvc3ZnPg==">
{{ org_details.whatsapp_link }}
</a>
{% else %}
<div class="business-card-value">Не указано</div>
{% endif %}
</div>
</div>
<div class="business-card-item">
<div class="business-card-label">Telegram</div>
<div class="business-card-value">
{% if org_details.telegram_link %}
<a href="{{ org_details.telegram_link }}" target="_blank">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iI2ZmZiIgY2xhc3M9ImJpIGJpLXQtZWxlZ3JhbSIgdmlld0JveD0iMCAwIDE2IDE2Ij48cGF0aCBkPSJNMTYuMDAyIDguNjkyYy4wMDItLjg3Ni0uNDQ1LTEuMzM1LTEuMzAzLTEuNjk0LS4zMjctLjEwNy0uNjk0LS4yMzctMS4wODgtLjM2Ny0xLjYzNi0uNTE2LTIuOTQzLTEuMzMtNC4xMy0yLjU0NS0uODkxLS44OC0xLjY0Ny0xLjcxLTIuMzc0LTIuNDE4LS40MTctLjM5My0uNTM3LS42Ni0uNTAyLS44NTEuMDExLS4wNjkuMDc1LS4yNTguMDgyLS4zNDkuMDY2LS44MjktLjMyLS45NzgtMS4xNS0uNzAyLS40ODcuMTU3LS45OTMuMzItMS41MTMuNDc1LS4yMS4wNjItLjM3OC4wOTktLjUuMTItLjU3LjA4OC0xLjE3NS4yNjQtMS43MDkuNDMzLS4zMy4xMTgtLjY3LjI1MS0xLjAyLjM4OC0uNzUuMjczLTEuNTA5LjU0Ni0yLjI3LjgwNi0uNzU4LjI2Mi0xLjQ3NC40NzUtMi4wNjQuNjQtLjUzNC4xNDYtLjkzNy4xNi0xLjIxMi0uMDctLjQ4NS0uNDA5LS45MS0uOTQ2LS40NzYtMS40NTEuMTU1LS4xNy4zNDctLjMyNi41NzYtLjQ2Ny4xNjktLjEwNS4zNjMtLjIwNy41ODItLjMxMy40NjktLjIy.OTI2LS4zNzQgMS4zNjgtLjQ2OS42MzItLjEzIDEuMjcxLS4yMTYgMS45Mi0uMjcxLjI3OS0uMDI0LjU1My0uMDQuODIuMDYuMDYxLS4xNzguMjUzLS41NTYuNTQ3LTEuMTUyLjY4MS0xLjM2NSAxLjQxNy0yLjE4MSAyLjE2Ni0yLjczMi42NzYtLjUwOCAxLjQwNy0uOTUzIDIuMjY2LTEuMjg5LjI2MS0uMTA5LjUyLS4xNDMuNzc4LS4wNzIuOTc0LjI3NSAxLjc2OC41NzIgMi4zNzUuODcxLjMwNS4xNS41NzcuMzEuNzk0LjQ1MS4yMTQuMTQzLjMyNC4yMi4zMjQuMjIuMDg2LS4yNzguMjYzLS42MS40NzYtLjkxMy4wNjItLjA4OC4xMzQtLjE4NS4yMTUtLjI4OC41MTQtLjY2MiAxLjExLS44NzUgMS44MS0uNTMxLjY0NC4zMTEgMS4xNzcuOCAxLjczMiAxLjUyLjQ3NS42ODkuOTUgMS4zNzkgMS40MjUgMi4wNzcuMzYzLjU1LjY4IDEuMDcuOTU3IDEuNTUzLjY1MiAxLjE0OSAxLjEzOCAxLjgxMiAxLjQ1MiAyLjEyNi40NzYuNDg3Ljg2LjgyNyAxLjI0MyAxLjA5Ni43NDEuNTIzIDEuNDg1LjkzNCAyLjIzNSAxLjIxMS43NDcuMjc0IDEuNDU1LjQ4NCAyLjExMy42MzYuNTY3LjEzIDEuMTU0LjE4MiAxLjczLjE1LjcxNC0uMDM1IDEuNDEtLjI0MyAxLjk3LS41Ny41ODEtLjMzOCAxLjA1NS0uODI5IDEuMzk3LTEuMzU1LjExOS0uMTc1LjIwMi0uMzguMjUtLjU4My4wNDctLjE4OS4wNjctLjM4OS4wNi0uNTkzWiIvPjwvc3ZnPg==">
{{ org_details.telegram_link }}
</a>
{% else %}
<div class="business-card-value">Не указано</div>
{% endif %}
</div>
</div>
{% else %}
<p class="no-history">Данные организации не указаны.</p>
{% endif %}
</section>
</div>
</div>
<!-- Invoice Detail Modal -->
<div id="invoiceDetailModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal('invoiceDetailModal')">×</span>
<h2 id="invoiceDetailTitle" class="modal-title"></h2>
<ul id="invoiceDetailList" class="invoice-detail-list">
<!-- Invoice items will be loaded here -->
</ul>
<div id="invoiceDetailTotal" class="invoice-total-display">
<span>Итого:</span>
<span id="invoiceTotalAmount">0.00</span>
</div>
</div>
</div>
<script>
const tg = window.Telegram.WebApp;
let currentUserId = "{{ user.id }}"; // Pass user ID from backend
function applyTheme(themeParams) {
const root = document.documentElement;
const isDark = themeParams.bg_color ? (parseInt(themeParams.bg_color.substring(1, 3), 16) < 128) : true;
root.style.setProperty('--brand-black', themeParams.bg_color || '#101010');
root.style.setProperty('--text-color', themeParams.text_color || '#ffffff');
root.style.setProperty('--text-secondary-color', themeParams.hint_color || '#a0a0a0');
root.style.setProperty('--brand-yellow', themeParams.button_color || '#FFC107');
root.style.setProperty('--card-bg', themeParams.secondary_bg_color || (isDark ? '#1c1c1e' : '#f1f1f1'));
root.style.setProperty('--button-bg', themeParams.button_color || '#FFC107');
root.style.setProperty('--button-text', themeParams.button_text_color || (isDark ? '#000' : '#fff'));
}
function setupTelegram() {
if (!tg || !tg.initData) {
console.error("Telegram WebApp script not loaded or initData is missing.");
document.body.style.visibility = 'visible';
return;
}
tg.ready();
tg.expand();
if (tg.themeParams && Object.keys(tg.themeParams).length > 0) {
applyTheme(tg.themeParams);
}
tg.onEvent('themeChanged', () => applyTheme(tg.themeParams));
// This client-side verification check is secondary to the backend one.
// The backend check is the authoritative source for user identity and validity.
// If user_id_for_test is present, we skip client-side verification and trust the backend already did it
// and redirected with the user_id.
const urlParams = new URLSearchParams(window.location.search);
const userIdFromUrl = urlParams.get('user_id_for_test');
if (!userIdFromUrl) {
// Only send initData for verification if user_id_for_test is NOT in the URL,
// meaning the backend hasn't verified and redirected yet.
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) {
// Backend verification successful, reload with user_id_for_test param
// This is a client-side redirect simulating a server-side one
// to ensure the template renders with the verified user data.
// In a real app, the server would handle this verification and render directly.
const currentUrl = new URL(window.location.href);
currentUrl.searchParams.set('user_id_for_test', data.user_id);
window.location.replace(currentUrl.toString());
} else {
console.warn('Backend verification failed:', data.message);
// Display page content even if verification fails, maybe with limited features or a message
document.body.style.visibility = 'visible';
// Optionally hide sensitive user data sections
// document.getElementById('dashboard-section').innerHTML = '<p>Verification failed. Please open the app via Telegram.</p>';
}
})
.catch(error => {
console.error('Error sending initData for verification:', error);
document.body.style.visibility = 'visible';
// document.getElementById('dashboard-section').innerHTML = '<p>Error during verification. Please try again later.</p>';
});
} else {
// If user_id_for_test is present, the backend already handled verification
// and passed the user ID. We can now reveal the body.
currentUserId = userIdFromUrl; // Update JS variable with actual user ID
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 {
// Fallback greeting if tg.initDataUnsafe is not available immediately
// The template renders the user's first name if available from backend data
const fallbackName = "{{ user.first_name or 'Гость' }}";
greetingElement.textContent = `Привет, ${fallbackName}! 👋`;
}
}
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 = 'block';
}
function closeModal(modalId) {
document.getElementById(modalId).style.display = 'none';
}
function openInvoiceDetailModal(invoiceData) {
document.getElementById('invoiceDetailTitle').textContent = `Накладная #${invoiceData.invoice_id} от ${invoiceData.date_str}`;
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);
});
document.getElementById('invoiceTotalAmount').textContent = parseFloat(invoiceData.total_amount).toFixed(2);
openModal('invoiceDetailModal');
}
function copyPartnerCode(code) {
navigator.clipboard.writeText(code).then(() => {
tg.showPopup({
message: `Партнерский код "${code}" скопирован!`,
ok_button: { text: 'Ок' }
});
}).catch(err => {
console.error('Failed to copy text: ', err);
tg.showPopup({
message: 'Ошибка при копировании кода.',
ok_button: { text: 'Ок' }
});
});
}
async function activatePartnerCode() {
const inputElement = document.getElementById('partnerCodeInput');
const code = inputElement.value.trim();
const statusElement = document.getElementById('activateStatus');
if (!code) {
statusElement.style.color = 'var(--brand-red)';
statusElement.textContent = 'Пожалуйста, введите код.';
return;
}
statusElement.style.color = 'var(--text-secondary-color)';
statusElement.textContent = 'Активация...';
try {
// Use the actual user ID obtained from backend verification
const response = await fetch('/activate_partner_code', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: currentUserId, partner_code: code })
});
const result = await response.json();
if (response.ok) {
statusElement.style.color = '#4CAF50'; // Green color
statusElement.textContent = result.message || 'Код успешно активирован!';
// Reload the page to show the updated 'referred_by' status and hide the activation form
setTimeout(() => { location.reload(); }, 1500);
} else {
statusElement.style.color = 'var(--brand-red)';
statusElement.textContent = result.message || 'Ошибка активации кода.';
}
} catch (error) {
console.error('Activation error:', error);
statusElement.style.color = 'var(--brand-red)';
statusElement.textContent = 'Произошла ошибка сети или сервера.';
}
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.nav-btn').forEach(button => {
button.addEventListener('click', () => {
showSection(button.dataset.target);
});
});
showSection('dashboard-section');
});
if (window.Telegram && window.Telegram.WebApp) {
setupTelegram();
} else {
window.addEventListener('load', setupTelegram, {once: true});
setTimeout(() => {
if (document.body.style.visibility !== 'visible') {
document.body.style.visibility = 'visible';
}
}, 3000); // Fallback visibility if TG WebApp script is slow or fails
}
</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;
--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); }
.controls-bar { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; background: var(--admin-card-bg); padding: var(--padding); border-radius: var(--border-radius); box-shadow: 0 4px 15px var(--admin-shadow); border: 1px solid var(--admin-border); margin-bottom: var(--padding); }
.controls-bar input[type="text"] { flex-grow: 1; padding: 12px 15px; font-size: 1.1em; border-radius: 8px; border: 1px solid var(--admin-border); box-sizing: border-box; min-width: 250px; }
.btn { padding: 12px 20px; font-size: 1em; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background-color 0.2s ease; }
.btn-primary { background-color: var(--admin-primary); color: #000; }
.btn-primary:hover { background-color: var(--admin-primary-dark); }
.btn-delete { background-color: var(--admin-danger); color: white; }
.btn-delete:hover { background-color: #c82333; }
.user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(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 { flex-grow: 1;}
.user-details .name { font-weight: 600; font-size: 1.2em; }
.user-details .username { color: var(--admin-secondary); font-size: 0.9em; }
.user-details .user-ids { font-size: 0.8em; color: var(--admin-secondary); margin-top: 4px;}
.user-details .user-ids span { margin-right: 15px; }
.user-details .referral-info { font-size: 0.8em; color: var(--admin-secondary); margin-top: 4px;}
.user-balances { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; text-align: center; margin-bottom: 1rem; }
.user-balances .label { font-size: 0.9em; color: var(--admin-secondary); }
.user-balances .amount.bonus { font-size: 1.8em; font-weight: 700; color: var(--admin-primary-dark); }
.user-balances .amount.debt { font-size: 1.8em; font-weight: 700; color: var(--admin-danger); }
.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); }
.modal-header .user-identifiers { font-size: 0.9rem; color: var(--admin-secondary); margin-top: 5px; }
.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; }
.calculation-summary { background: #f0f0f0; padding: 1rem; border-radius: 8px; margin-top: 1rem; }
.summary-item { display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-size: 0.95em; }
.summary-item strong { font-weight: 600; }
.history-container { margin-top: 1.5rem; }
.history-container h3 { font-size: 1.2rem; margin-bottom: 1rem; }
.history-list { list-style: none; padding: 0; max-height: 200px; overflow-y: auto; border: 1px solid var(--admin-border); border-radius: 8px; }
.history-item { display: flex; justify-content: space-between; padding: 8px 12px; border-bottom: 1px solid var(--admin-border); }
.history-item:last-child { border-bottom: none; }
.history-item .desc { font-size: 0.9em; }
.history-item .date { font-size: 0.8em; color: var(--admin-secondary); }
.history-item .amount.bonus-accrual { color: var(--admin-success); font-weight: 600; } /* Regular Bonus */
.history-item .amount.bonus-referral { color: #2196F3; font-weight: 600; } /* Referral Bonus */
.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; }
.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; }
/* Tabs for Transaction Modal */
.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;
}
/* Invoice table */
.invoice-items-table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
}
.invoice-items-table th, .invoice-items-table td {
border: 1px solid var(--admin-border);
padding: 8px;
text-align: left;
font-size: 0.9em;
}
.invoice-items-table th {
background-color: #e9ecef;
font-weight: 600;
color: var(--admin-text);
}
.invoice-items-table .total-row td {
font-weight: 700;
background-color: #f0f0f0;
}
.invoice-items-table .action-btn {
background: none;
border: none;
color: var(--admin-danger);
cursor: pointer;
font-size: 1.2em;
}
.invoice-section-summary {
padding: 1rem;
background-color: #f0f0f0;
border-radius: 8px;
margin-top: 1rem;
font-weight: 600;
}
.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;
}
.organization-details-form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.organization-details-form textarea {
min-height: 80px;
resize: vertical;
}
.organization-details-form .form-group-inline {
display: flex;
align-items: center;
gap: 10px;
}
.organization-details-form .form-group-inline input[type="number"] {
width: 100px;
}
</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 debt">{{ summary.users_with_debt }}</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>
</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 }} {{ user.partner_code|lower if user.partner_code }}">
<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 }}</div>
<div class="user-ids">
<span>ID: {{ user.id }}</span>
<span>Партнерский код: {{ user.partner_code | default('Нет') }}</span>
</div>
<div class="referral-info">
Приглашен: {{ user.referred_by | default('Никем') }}
{% if user.referred_users %}
| Пригласил: {{ user.referred_users | join(', ') }}
{% endif %}
</div>
</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="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>
<!-- Transaction/Invoice Modal -->
<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 class="user-identifiers">
<span>ID: <span id="modalUserIdDisplay"></span></span>
<span>Код: <span id="modalUserPartnerCodeDisplay"></span></span>
</div>
<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>
</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="purchaseAmount">Сумма покупки (для начисления)</label>
<input type="number" id="purchaseAmount" step="0.01" placeholder="1500" oninput="updateCalculations()">
</div>
<div class="form-group">
<label for="deductAmount">Списать бонусов</label>
<input type="number" id="deductAmount" step="0.01" placeholder="100" oninput="updateCalculations()">
</div>
</div>
<div class="calculation-summary">
<div class="summary-item"><span>Текущий баланс:</span> <strong id="summaryCurrentBalance">0.00</strong></div>
<div class="summary-item"><span>Будет начислено (2%):</span> <strong id="summaryAccrual">+0.00</strong></div>
<div class="summary-item"><span>Будет списано:</span> <strong id="summaryDeduction">-0.00</strong></div>
<hr>
<div class="summary-item"><strong>Итоговый баланс бонусов:</strong> <strong id="summaryFinalBalance">0.00</strong></div>
</div>
</div>
<div class="form-section">
<h3>Долги</h3>
<div class="form-row">
<div class="form-group">
<label for="addDebtAmount">Добавить долг</label>
<input type="number" id="addDebtAmount" step="0.01" placeholder="500" oninput="updateCalculations()">
</div>
<div class="form-group">
<label for="repayDebtAmount">Погасить долг</label>
<input type="number" id="repayDebtAmount" step="0.01" placeholder="200" oninput="updateCalculations()">
</div>
</div>
<div class="calculation-summary">
<div class="summary-item"><span>Текущий долг:</span> <strong id="summaryCurrentDebt">0.00</strong></div>
<div class="summary-item"><span>Будет добавлено:</span> <strong id="summaryAddDebt">+0.00</strong></div>
<div class="summary-item"><span>Будет погашено:</span> <strong id="summaryRepayDebt">-0.00</strong></div>
<hr>
<div class="summary-item"><strong>Итоговый долг:</strong> <strong id="summaryFinalDebt">0.00</strong></div>
</div>
</div>
<div class="history-container">
<h3>Общая история операций</h3>
<ul id="modalHistoryList" class="history-list"></ul>
</div>
<div class="modal-footer">
<div id="modalStatus" class="status-message"></div>
<button class="btn-submit" onclick="submitTransaction()">Провести операцию</button>
</div>
</div>
<div id="invoice-tab" class="tab-content">
<div class="form-section">
<h3>Добавить новую накладную</h3>
<table class="invoice-items-table" id="newInvoiceItemsTable">
<thead>
<tr>
<th>Товар</th>
<th>Кол-во</th>
<th>Цена за ед.</th>
<th>Сумма</th>
<th></th>
</tr>
</thead>
<tbody>
<!-- New invoice items will be added here -->
</tbody>
<tfoot>
<tr>
<td colspan="3" style="text-align: right;"><strong>Итоговая сумма накладной:</strong></td>
<td id="newInvoiceTotalAmount">0.00</td>
<td></td>
</tr>
</tfoot>
</table>
<button class="btn btn-primary" style="margin-top: 1rem;" onclick="addNewInvoiceItemRow()">Добавить товар</button>
</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>
</div>
<!-- Add Client Modal -->
<div id="addClientModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal('addClientModal')">×</span>
<div class="modal-header">
<h2>Добавить нового клиента</h2>
</div>
<div class="form-group" style="margin-bottom: 1rem;">
<label for="newClientFirstName">Имя</label>
<input type="text" id="newClientFirstName" placeholder="Иван">
</div>
<div class="form-group" style="margin-bottom: 1.5rem;">
<label for="newClientPhone">Номер телефона (уникальный)</label>
<input type="tel" id="newClientPhone" placeholder="+79001234567">
</div>
<div class="modal-footer">
<div id="addClientStatus" class="status-message"></div>
<button class="btn-submit" onclick="submitNewClient()">Сохранить клиента</button>
</div>
</div>
</div>
<!-- Organization Settings Modal -->
<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="organization-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="+79001112233,+79004445566">
</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/79001112233">
</div>
<div class="form-group">
<label for="orgTelegramLink">Ссылка на Telegram</label>
<input type="url" id="orgTelegramLink" placeholder="https://t.me/your_telegram_username">
</div>
<div class="form-group">
<label for="referralPercentage">Процент партнерских бонусов (от суммы начисления приведенному клиенту)</label>
<div class="form-group-inline">
<input type="number" id="referralPercentage" step="0.1" min="0" placeholder="2">
<span>%</span>
</div>
</div>
</div>
<div class="modal-footer">
<div id="orgStatus" class="status-message"></div>
<button class="btn-submit" onclick="saveOrgSettings()">Сохранить настройки</button>
</div>
</div>
</div>
<!-- Invoice Detail Modal (for Admin) -->
<div id="adminInvoiceDetailModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal('adminInvoiceDetailModal')">×</span>
<h2 id="adminInvoiceDetailTitle" class="modal-title"></h2>
<ul id="adminInvoiceDetailList" class="invoice-detail-list">
<!-- Invoice items will be loaded here -->
</ul>
<div id="adminInvoiceDetailTotal" class="invoice-total-display">
<span>Итого:</span>
<span id="adminInvoiceTotalAmount">0.00</span>
</div>
</div>
</div>
<script>
const transactionModal = document.getElementById('transactionModal');
const addClientModal = document.getElementById('addClientModal');
const orgSettingsModal = document.getElementById('orgSettingsModal');
const adminInvoiceDetailModal = document.getElementById('adminInvoiceDetailModal');
let currentUserData = null;
let newInvoiceItems = [];
function searchUsers() {
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
const userCards = document.querySelectorAll('.user-card');
userCards.forEach(card => {
const cardSearchTerm = card.getAttribute('data-search-term');
if (cardSearchTerm.includes(searchTerm)) {
card.style.display = 'flex';
} else {
card.style.display = 'none';
}
});
}
function openTransactionModal(userData) {
currentUserData = userData;
document.getElementById('modalUserId').value = userData.id;
document.getElementById('modalUserIdDisplay').textContent = userData.id;
document.getElementById('modalUserPartnerCodeDisplay').textContent = userData.partner_code || 'Нет';
document.getElementById('modalUserName').textContent = `${userData.first_name || ''} ${userData.last_name || ''}`;
document.getElementById('modalUserUsername').textContent = `@${userData.username || userData.phone_number || ''}`;
document.getElementById('purchaseAmount').value = '';
document.getElementById('deductAmount').value = '';
document.getElementById('addDebtAmount').value = '';
document.getElementById('repayDebtAmount').value = '';
document.getElementById('modalStatus').textContent = '';
document.getElementById('invoiceStatus').textContent = '';
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 combinedHistory = [...bonusHistory, ...debtHistory].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 === 'deduction' ? '-' : '+';
amountClass = item.type === 'deduction' ? 'bonus-deduction' : (item.type === 'referral' ? 'bonus-referral' : 'bonus-accrual');
amountText = `${sign}${parseFloat(item.amount).toFixed(2)}`;
} else { // debt
sign = item.type === 'accrual' ? '+' : '-';
amountClass = item.type === 'accrual' ? 'debt-accrual' : 'debt-payment';
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('referralPercentage').value = data.referral_percentage || '';
document.getElementById('orgStatus').textContent = '';
orgSettingsModal.style.display = 'block';
})
.catch(error => {
console.error('Error fetching organization details:', error);
document.getElementById('orgStatus').style.color = 'var(--admin-danger)';
document.getElementById('orgStatus').textContent = 'Ошибка загрузки данных.';
orgSettingsModal.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;
const currentBalance = parseFloat(currentUserData.bonuses) || 0;
const purchaseAmount = parseFloat(document.getElementById('purchaseAmount').value) || 0;
const deductAmount = parseFloat(document.getElementById('deductAmount').value) || 0;
const accrualAmount = purchaseAmount * 0.02; // Base 2%
let finalDeductAmount = deductAmount;
// Prevent deducting more than current balance
if (deductAmount > currentBalance) {
finalDeductAmount = currentBalance;
document.getElementById('deductAmount').value = finalDeductAmount > 0 ? finalDeductAmount.toFixed(2) : '';
}
const finalBonusBalance = currentBalance + accrualAmount - finalDeductAmount;
document.getElementById('summaryCurrentBalance').textContent = currentBalance.toFixed(2);
document.getElementById('summaryAccrual').textContent = `+${accrualAmount.toFixed(2)}`;
document.getElementById('summaryDeduction').textContent = `-${finalDeductAmount.toFixed(2)}`;
document.getElementById('summaryFinalBalance').textContent = finalBonusBalance.toFixed(2);
const currentDebt = parseFloat(currentUserData.debts) || 0;
const addDebtAmount = parseFloat(document.getElementById('addDebtAmount').value) || 0;
const repayDebtAmount = parseFloat(document.getElementById('repayDebtAmount').value) || 0;
let finalRepayAmount = repayDebtAmount;
// Prevent repaying more than current debt
if (repayDebtAmount > currentDebt) {
finalRepayAmount = currentDebt;
document.getElementById('repayDebtAmount').value = finalRepayAmount > 0 ? finalRepayAmount.toFixed(2) : '';
}
const finalDebt = currentDebt + addDebtAmount - finalRepayAmount;
document.getElementById('summaryCurrentDebt').textContent = currentDebt.toFixed(2);
document.getElementById('summaryAddDebt').textContent = `+${addDebtAmount.toFixed(2)}`;
document.getElementById('summaryRepayDebt').textContent = `-${finalRepayAmount.toFixed(2)}`;
document.getElementById('summaryFinalDebt').textContent = finalDebt.toFixed(2);
}
async function submitTransaction() {
const statusEl = document.getElementById('modalStatus');
statusEl.style.color = 'var(--admin-secondary)';
statusEl.textContent = 'Обработка...';
const userId = document.getElementById('modalUserId').value;
const purchase_amount = parseFloat(document.getElementById('purchaseAmount').value) || 0;
const deduct_amount = parseFloat(document.getElementById('deductAmount').value) || 0;
const add_debt_amount = parseFloat(document.getElementById('addDebtAmount').value) || 0;
const repay_debt_amount = parseFloat(document.getElementById('repayDebtAmount').value) || 0;
if (purchase_amount <= 0 && deduct_amount <= 0 && add_debt_amount <= 0 && repay_debt_amount <= 0) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = 'Введите сумму для любой из операций.';
return;
}
// Re-validate amounts against current user data before submitting
const currentBonus = parseFloat(currentUserData.bonuses) || 0;
const currentDebt = parseFloat(currentUserData.debts) || 0;
if (deduct_amount > currentBonus) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = `Недостаточно бонусов для списания (списание ${deduct_amount.toFixed(2)}, доступно ${currentBonus.toFixed(2)}).`;
return;
}
if (repay_debt_amount > currentDebt) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = `Сумма погашения (${repay_debt_amount.toFixed(2)}) превышает текущий долг (${currentDebt.toFixed(2)}).`;
return;
}
const payload = {
user_id: userId,
purchase_amount: purchase_amount,
deduct_amount: deduct_amount,
add_debt_amount: add_debt_amount,
repay_debt_amount: repay_debt_amount,
};
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 = 'Операция успешно проведена!';
// Reload the page to update the user list and modal data
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 phoneNumbers = phoneNumbersRaw ? phoneNumbersRaw.split(',').map(p => p.trim()).filter(p => p) : []; // Filter empty strings
const referralPercentage = parseFloat(document.getElementById('referralPercentage').value) || 0;
if (referralPercentage < 0) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = 'Процент партнерских бонусов не может быть отрицательным.';
return;
}
const payload = {
name: document.getElementById('orgName').value.trim(),
phone_numbers: phoneNumbers,
address: document.getElementById('orgAddress').value.trim(),
whatsapp_link: document.getElementById('orgWhatsAppLink').value.trim(),
telegram_link: document.getElementById('orgTelegramLink').value.trim(),
referral_percentage: referralPercentage
};
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(() => { location.reload(); }, 1500);
} else {
throw new Error(result.message || 'Произошла ошибка');
}
} catch (error) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = `Ошибка: ${error.message}`;
}
}
async function deleteClient(userId) {
if (!confirm(`Вы уверены, что хотите удалить клиента с ID ${userId}? Это действие необратимо.`)) {
return;
}
try {
const response = await fetch('/admin/delete_client', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: userId })
});
const result = await response.json();
if (response.ok) {
location.reload();
} else {
throw new Error(result.message || 'Не удалось удалить клиента.');
}
} catch (error) {
alert(`Ошибка: ${error.message}`);
}
}
function addNewInvoiceItemRow() {
const tableBody = document.getElementById('newInvoiceItemsTable').getElementsByTagName('tbody')[0];
const newRow = tableBody.insertRow();
const rowIndex = newInvoiceItems.length; // Use the current length for the index
newInvoiceItems.push({
product_name: '',
quantity: 0,
unit_price: 0,
item_total: 0
});
newRow.innerHTML = `
<td><input type="text" placeholder="Название товара" oninput="updateInvoiceItem(${rowIndex}, 'product_name', this.value)"></td>
<td><input type="number" step="1" min="0" placeholder="0" oninput="updateInvoiceItem(${rowIndex}, 'quantity', parseFloat(this.value))"></td>
<td><input type="number" step="0.01" min="0" placeholder="0.00" oninput="updateInvoiceItem(${rowIndex}, 'unit_price', parseFloat(this.value))"></td>
<td class="item-total-display">0.00</td>
<td><button type="button" class="action-btn" onclick="removeInvoiceItemRow(this, ${rowIndex})">🗑️</button></td>
`;
// Focus the new product name input
newRow.querySelector('input[type="text"]').focus();
}
function updateInvoiceItem(index, field, value) {
if (newInvoiceItems[index]) {
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 tableBody = document.getElementById('newInvoiceItemsTable').getElementsByTagName('tbody')[0];
if (tableBody.rows[index]) { // Ensure row still exists
tableBody.rows[index].querySelector('.item-total-display').textContent = itemTotal.toFixed(2);
}
updateNewInvoiceTotal();
}
}
function removeInvoiceItemRow(button, index) {
if (!newInvoiceItems[index]) return; // Item already removed
const tableBody = document.getElementById('newInvoiceItemsTable').getElementsByTagName('tbody')[0];
const row = button.closest('tr');
if (row) {
tableBody.deleteRow(row.rowIndex - 1); // rowIndex is 1-based for tbody rows
// Remove item from array
newInvoiceItems.splice(index, 1);
// Re-index the event listeners on the remaining rows
for (let i = 0; i < tableBody.rows.length; i++) {
const r = tableBody.rows[i];
r.querySelector('input[type="text"]').setAttribute('oninput', `updateInvoiceItem(${i}, 'product_name', this.value)`);
r.querySelector('input[type="number"][step="1"]').setAttribute('oninput', `updateInvoiceItem(${i}, 'quantity', parseFloat(this.value))`);
r.querySelector('input[type="number"][step="0.01"]').setAttribute('oninput', `updateInvoiceItem(${i}, 'unit_price', parseFloat(this.value))`);
r.querySelector('.action-btn').setAttribute('onclick', `removeInvoiceItemRow(this, ${i})`);
}
updateNewInvoiceTotal();
}
}
function updateNewInvoiceTotal() {
let total = 0;
newInvoiceItems.forEach(item => {
total += parseFloat(item.item_total) || 0;
});
document.getElementById('newInvoiceTotalAmount').textContent = total.toFixed(2);
}
function renderNewInvoiceItems() {
const tableBody = document.getElementById('newInvoiceItemsTable').getElementsByTagName('tbody')[0];
tableBody.innerHTML = '';
newInvoiceItems.forEach((item, index) => {
const newRow = tableBody.insertRow();
newRow.innerHTML = `
<td><input type="text" placeholder="Название товара" value="${item.product_name}" oninput="updateInvoiceItem(${index}, 'product_name', this.value)"></td>
<td><input type="number" step="1" min="0" placeholder="0" value="${item.quantity || ''}" oninput="updateInvoiceItem(${index}, 'quantity', parseFloat(this.value))"></td>
<td><input type="number" step="0.01" min="0" placeholder="0.00" value="${item.unit_price || ''}" oninput="updateInvoiceItem(${index}, 'unit_price', parseFloat(this.value))"></td>
<td class="item-total-display">${(item.item_total || 0).toFixed(2)}</td>
<td><button type="button" class="action-btn" onclick="removeInvoiceItemRow(this, ${index})">🗑️</button></td>
`;
});
updateNewInvoiceTotal();
}
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.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 payload = {
user_id: currentUserData.id,
total_amount: totalAmount,
items: itemsToAdd
};
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 = 'Накладная успешно сохранена!';
// Reload the page or update the modal's invoice list
// Simple reload for now:
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);
});
document.getElementById('adminInvoiceTotalAmount').textContent = parseFloat(invoiceData.total_amount).toFixed(2);
openModal('adminInvoiceDetailModal');
}
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(); // Reload the page to update the list
} 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 == adminInvoiceDetailModal) {
closeModal('adminInvoiceDetailModal');
}
}
document.addEventListener('DOMContentLoaded', () => {
// Add at least one row for new invoice input when modal opens
// Don't add initially, only when modal opens or tab is shown?
// Let's add one row when the tab is activated or modal opens for the first time
});
// Add initial row when modal is opened
transactionModal.addEventListener('transitionend', (event) => {
if (event.propertyName === 'display' && transactionModal.style.display === 'block') {
// Check if on invoice tab and no items exist
if (document.getElementById('invoice-tab').classList.contains('active') && newInvoiceItems.length === 0) {
//addNewInvoiceItemRow(); // Add an initial row
}
}
});
// Or trigger on tab click if it's the invoice tab
document.querySelectorAll('.tab-btn').forEach(button => {
button.addEventListener('click', () => {
if (button.dataset.tab === 'invoice-tab') {
// Add an initial row if the items list is currently empty
if (newInvoiceItems.length === 0) {
addNewInvoiceItemRow();
}
}
});
});
</script>
</body>
</html>
"""
@app.route('/')
def index():
user_id_str = request.args.get('user_id_for_test')
all_data = load_visitor_data()
user_data = {}
if user_id_str and user_id_str in all_data and user_id_str != "organization_details":
user_data = all_data[user_id_str]
user_data['id'] = user_id_str # Ensure 'id' key is present
# Prepare combined history for display
bonus_history = user_data.get('history', [])
for item in bonus_history:
item['transaction_type'] = 'bonus'
debt_history = user_data.get('debt_history', [])
for item in debt_history:
item['transaction_type'] = 'debt' # Type 'accrual' for debt means debt increased, 'payment' means debt decreased
combined_history = sorted(
bonus_history + debt_history,
key=lambda x: x['date'],
reverse=True
)
user_data['combined_history'] = combined_history
user_data['invoices'] = user_data.get('invoices', [])
user_data['partner_code'] = user_data.get('partner_code') # Pass partner code
user_data['referred_by'] = user_data.get('referred_by') # Pass referred_by
else:
# Default empty user data if ID not found or not provided
user_data = {
"id": "N/A",
"first_name": "Гость",
"bonuses": 0,
"debts": 0,
"history": [],
"debt_history": [],
"combined_history": [],
"invoices": [],
"partner_code": None,
"referred_by": None
}
org_details = all_data.get('organization_details', {})
return render_template_string(TEMPLATE, user=user_data, org_details=org_details)
@app.route('/verify', methods=['POST'])
def verify_data():
try:
req_data = request.get_json()
init_data_str = req_data.get('initData')
if not init_data_str:
return jsonify({"status": "error", "message": "Missing initData"}), 400
user_data_parsed, is_valid = verify_telegram_data(init_data_str)
user_info_dict = {}
if user_data_parsed and 'user' in user_data_parsed:
try:
user_json_str = unquote(user_data_parsed['user'][0])
user_info_dict = json.loads(user_json_str)
except Exception as e:
logging.error(f"Could not parse user JSON from initData: {e}")
user_info_dict = {}
if is_valid:
tg_user_id = user_info_dict.get('id')
if tg_user_id:
now = datetime.now(BISHKEK_TZ)
all_data = load_visitor_data() # Get current state of all data
existing_user_key = None
for key, user_data_item in all_data.items():
if key == "organization_details": continue
if str(user_data_item.get('telegram_id')) == str(tg_user_id):
existing_user_key = key
break
user_id_to_save = existing_user_key
if existing_user_key:
# Update existing user's TG info and visited time
user_entry = all_data[existing_user_key]
user_entry.update({
'first_name': user_info_dict.get('first_name', user_entry.get('first_name')),
'last_name': user_info_dict.get('last_name', user_entry.get('last_name')),
'username': user_info_dict.get('username', user_entry.get('username')),
'photo_url': user_info_dict.get('photo_url', user_entry.get('photo_url')),
'language_code': user_info_dict.get('language_code', user_entry.get('language_code')),
'is_premium': user_info_dict.get('is_premium', user_entry.get('is_premium', False)),
'visited_at': now.timestamp(),
'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S')
})
# Ensure partner_code exists if somehow missing
if 'partner_code' not in user_entry or not user_entry['partner_code']:
user_entry['partner_code'] = generate_unique_id(all_data)
else:
# Create new user entry
new_user_id = generate_unique_id(all_data)
user_entry = {
'id': new_user_id, # Store the generated unique ID
'telegram_id': tg_user_id,
'first_name': user_info_dict.get('first_name'),
'last_name': user_info_dict.get('last_name'),
'username': user_info_dict.get('username'),
'photo_url': user_info_dict.get('photo_url'),
'language_code': user_info_dict.get('language_code'),
'is_premium': user_info_dict.get('is_premium', False),
'phone_number': None,
'visited_at': now.timestamp(),
'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'),
'bonuses': 0,
'history': [],
'debts': 0,
'debt_history': [],
'invoices': [],
'partner_code': generate_unique_id(all_data), # Generate partner code on creation
'referred_by': None,
'referred_users': []
}
user_id_to_save = new_user_id
all_data[user_id_to_save] = user_entry # Update the global cache
save_visitor_data(all_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 in parsed data"}), 400
else:
logging.warning(f"Verification failed. InitData: {init_data_str}")
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('/activate_partner_code', methods=['POST'])
def activate_partner_code():
try:
data = request.get_json()
user_id = data.get('user_id') # User activating the code
partner_code_to_activate = data.get('partner_code') # Code entered by user
if not user_id or not partner_code_to_activate:
return jsonify({"status": "error", "message": "Необходимо указать ID пользователя и код."}), 400
user_id_str = str(user_id)
partner_code_to_activate = str(partner_code_to_activate).strip()
all_data = load_visitor_data()
if user_id_str not in all_data or user_id_str == "organization_details":
return jsonify({"status": "error", "message": "Пользователь не найден."}), 404
activator_user = all_data[user_id_str]
if activator_user.get('referred_by'):
return jsonify({"status": "error", "message": "Вы уже активировали партнерский код ранее."}), 400
if activator_user.get('partner_code') == partner_code_to_activate:
return jsonify({"status": "error", "message": "Нельзя активировать свой собственный код."}), 400
# Find the referrer user by their partner_code
referrer_user = None
referrer_user_id = None
for uid, udata in all_data.items():
if uid == "organization_details": continue
if udata.get('partner_code') == partner_code_to_activate:
referrer_user = udata
referrer_user_id = uid
break
if not referrer_user:
return jsonify({"status": "error", "message": "Партнерский код не найден."}), 404
# Perform the activation
activator_user['referred_by'] = partner_code_to_activate
if 'referred_users' not in referrer_user or not isinstance(referrer_user['referred_users'], list):
referrer_user['referred_users'] = []
if user_id_str not in referrer_user['referred_users']:
referrer_user['referred_users'].append(user_id_str)
all_data[user_id_str] = activator_user
all_data[referrer_user_id] = referrer_user # Update referrer in cache
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "Партнерский код успешно активирован!"}), 200
except Exception as e:
logging.exception("Error in /activate_partner_code endpoint")
return jsonify({"status": "error", "message": "Внутренняя ошибка сервера."}), 500
@app.route('/admin')
def admin_panel():
all_data = load_visitor_data()
users_list = []
for user_id, user_data in all_data.items():
if user_id == "organization_details":
continue
user_data['id'] = user_id # Ensure ID is in the dict for template access
users_list.append(user_data)
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)
users_with_debt = sum(1 for u in users_list if u.get('debts', 0) > 0)
summary_stats = {
"total_users": total_users,
"total_bonuses": total_bonuses,
"total_debts": total_debts,
"users_with_debt": users_with_debt
}
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
all_data = load_visitor_data() # Load current state
# Check for existing phone number or Telegram ID
for key, user in all_data.items():
if key == "organization_details": continue
if user.get('phone_number') == phone_number or (user.get('telegram_id') is not None and user.get('phone_number') == phone_number):
return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409
now = datetime.now(BISHKEK_TZ)
new_id = generate_unique_id(all_data) # Generate unique client ID and partner code check
new_partner_code = generate_unique_id(all_data) # Ensure unique partner code separately
new_client = {
'id': new_id,
'telegram_id': None,
'first_name': first_name,
'last_name': None,
'username': None,
'photo_url': None,
'language_code': 'ru',
'is_premium': False,
'phone_number': phone_number,
'visited_at': now.timestamp(),
'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'),
'bonuses': 0,
'history': [],
'debts': 0,
'debt_history': [],
'invoices': [],
'partner_code': new_partner_code,
'referred_by': None,
'referred_users': []
}
with _data_lock:
all_data[new_id] = new_client # Update the global cache directly
save_visitor_data(all_data) # Save the entire cache
return jsonify({"status": "ok", "message": "Client added successfully", "user_id": new_id}), 201
except Exception as e:
logging.exception("Error in /admin/add_client endpoint")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/admin/add_transaction', methods=['POST'])
def add_transaction():
try:
data = request.get_json()
user_id = data.get('user_id')
purchase_amount = round(float(data.get('purchase_amount', 0)), 2)
deduct_amount = round(float(data.get('deduct_amount', 0)), 2)
add_debt_amount = round(float(data.get('add_debt_amount', 0)), 2)
repay_debt_amount = round(float(data.get('repay_debt_amount', 0)), 2)
if not user_id:
return jsonify({"status": "error", "message": "User ID is required"}), 400
user_id_str = str(user_id)
all_data = load_visitor_data()
if user_id_str not in all_data or user_id_str == "organization_details":
return jsonify({"status": "error", "message": "User not found"}), 404
user = all_data[user_id_str]
now = datetime.now(BISHKEK_TZ)
now_iso = now.isoformat()
now_str = now.strftime('%Y-%m-%d %H:%M:%S')
# --- Validation against current balance/debt ---
current_bonuses = user.get('bonuses', 0)
current_debts = user.get('debts', 0)
if deduct_amount > current_bonuses:
return jsonify({"status": "error", "message": f"Недостаточно бонусов для списания (списание {deduct_amount:.2f}, доступно {current_bonuses:.2f})."}), 400
if repay_debt_amount > current_debts:
return jsonify({"status": "error", "message": f"Сумма погашения ({repay_debt_amount:.2f}) превышает текущий долг ({current_debts:.2f})."}), 400
# --- End Validation ---
# --- Process Bonus Operations ---
accrual_amount = round(purchase_amount * 0.02, 2) # Base 2% accrual
user['bonuses'] = round(current_bonuses + accrual_amount - deduct_amount, 2)
if 'history' not in user or not isinstance(user['history'], list):
user['history'] = []
if accrual_amount > 0:
user['history'].append({
"type": "accrual", "amount": accrual_amount,
"description": f"Начисление с покупки {purchase_amount:.2f}",
"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
})
# --- End Bonus Operations ---
# --- Process Referral Bonus (if applicable) ---
if accrual_amount > 0: # Only give referral bonus if the referred user accrued bonuses
referred_by_code = user.get('referred_by')
if referred_by_code:
referrer_user = None
referrer_user_id = None
for uid, udata in all_data.items():
if uid == "organization_details": continue
if udata.get('partner_code') == referred_by_code:
referrer_user = udata
referrer_user_id = uid
break
if referrer_user:
# Get referral percentage from organization details
org_details = all_data.get('organization_details', {})
referral_percentage = float(org_details.get('referral_percentage', 2.0)) # Default 2%
if referral_percentage > 0:
referral_bonus_amount = round(accrual_amount * (referral_percentage / 100), 2)
if referral_bonus_amount > 0:
referrer_user['bonuses'] = round(referrer_user.get('bonuses', 0) + referral_bonus_amount, 2)
if 'history' not in referrer_user or not isinstance(referrer_user['history'], list):
referrer_user['history'] = []
referrer_user['history'].append({
"type": "referral", "amount": referral_bonus_amount,
"description": f"Бонус за приглашение клиента ID {user_id_str}",
"date": now_iso, "date_str": now_str
})
logging.info(f"Referral bonus {referral_bonus_amount} added to user {referrer_user_id} (referred by {referred_by_code}) from purchase by {user_id_str}")
# Ensure referrer user data is updated in the main all_data dict
all_data[referrer_user_id] = referrer_user
else:
logging.info(f"Referral bonus percentage is 0. Skipping referral bonus for {referrer_user_id}.")
else:
logging.warning(f"Referrer user with code {referred_by_code} not found for user {user_id_str}. Cannot add referral bonus.")
# --- End Referral Bonus ---
# --- Process Debt Operations ---
user['debts'] = round(user.get('debts', 0) + add_debt_amount - repay_debt_amount, 2)
if 'debt_history' not in user or not isinstance(user['debt_history'], list):
user['debt_history'] = []
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
})
# --- End Debt Operations ---
all_data[user_id_str] = user # Ensure user data is updated in the main all_data dict
save_visitor_data(all_data) # Save the entire cache
return jsonify({
"status": "ok", "message": "Transaction successful",
"new_balance": user['bonuses'], "new_debt": user['debts']
}), 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 = data.get('user_id')
total_amount = round(float(data.get('total_amount', 0)), 2)
items = data.get('items', [])
if not user_id:
return jsonify({"status": "error", "message": "User ID is required"}), 400
if not items:
return jsonify({"status": "error", "message": "Необходимо добавить товары в накладную."}), 400
user_id_str = str(user_id)
all_data = load_visitor_data()
if user_id_str not in all_data or user_id_str == "organization_details":
return jsonify({"status": "error", "message": "User not found"}), 404
user = all_data[user_id_str]
now = datetime.now(BISHKEK_TZ)
now_iso = now.isoformat()
now_str = now.strftime('%Y-%m-%d %H:%M:%S')
invoice_id = str(uuid.uuid4().hex[:8]).upper()
processed_items = []
for item in items:
p_name = item.get('product_name')
qty = float(item.get('quantity', 0))
u_price = float(item.get('unit_price', 0))
i_total = round(qty * u_price, 2)
processed_items.append({
"product_name": p_name,
"quantity": qty,
"unit_price": u_price,
"item_total": i_total
})
# Re-calculate total based on processed items to prevent manipulation
calculated_total = round(sum(item['item_total'] for item in processed_items), 2)
new_invoice = {
"invoice_id": invoice_id,
"date": now_iso,
"date_str": now_str,
"total_amount": calculated_total,
"items": processed_items
}
if 'invoices' not in user or not isinstance(user['invoices'], list):
user['invoices'] = []
user['invoices'].append(new_invoice)
all_data[user_id_str] = user
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "Накладная успешно добавлена!", "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 = data.get('user_id')
invoice_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
user_id_str = str(user_id)
all_data = load_visitor_data()
if user_id_str not in all_data or user_id_str == "organization_details":
return jsonify({"status": "error", "message": "User not found"}), 404
user = all_data[user_id_str]
if 'invoices' not in user or not isinstance(user['invoices'], list):
return jsonify({"status": "error", "message": "User has no invoices"}), 404
original_invoice_count = len(user['invoices'])
user['invoices'] = [inv for inv in user['invoices'] if str(inv.get('invoice_id')) != str(invoice_id)] # Ensure string comparison
if len(user['invoices']) == original_invoice_count:
return jsonify({"status": "error", "message": "Накладная не найдена для этого пользователя."}), 404
all_data[user_id_str] = user
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "Накладная успешно удалена!"}), 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:
data = request.get_json()
user_id = data.get('user_id')
if not user_id:
return jsonify({"status": "error", "message": "User ID is required"}), 400
user_id_str = str(user_id)
all_data = load_visitor_data()
with _data_lock:
if user_id_str not in all_data or user_id_str == "organization_details":
return jsonify({"status": "error", "message": "User not found"}), 404
user_to_delete = all_data[user_id_str]
if user_to_delete.get('telegram_id') is not None:
return jsonify({"status": "error", "message": "Невозможно удалить клиента, связанного с Telegram."}), 403
# Handle referral links before deleting
deleted_user_partner_code = user_to_delete.get('partner_code')
# 1. Find users referred by the deleted user and clear their 'referred_by'
users_referred_by_deleted = [uid for uid, udata in all_data.items()
if uid != "organization_details" and udata.get('referred_by') == deleted_user_partner_code]
for uid in users_referred_by_deleted:
if uid in all_data and uid != "organization_details":
all_data[uid]['referred_by'] = None
logging.info(f"Cleared referred_by for user {uid} (referred by {user_id_str})")
# 2. Find the user who referred the deleted user and remove this user from their 'referred_users' list
deleted_user_was_referred_by = user_to_delete.get('referred_by')
if deleted_user_was_referred_by:
for uid, udata in all_data.items():
if uid == "organization_details": continue
if udata.get('partner_code') == deleted_user_was_referred_by:
if 'referred_users' in udata and user_id_str in udata['referred_users']:
udata['referred_users'].remove(user_id_str)
logging.info(f"Removed user {user_id_str} from referred_users of referrer {uid}")
break # Assuming partner codes are unique, stop after finding referrer
# Now delete the user
del all_data[user_id_str]
try:
save_visitor_data(all_data)
except Exception as e:
logging.error(f"Error saving data after deletion: {e}")
return jsonify({"status": "error", "message": "Не удалось сохранить данные после удаления."}), 500
return jsonify({"status": "ok", "message": "Клиент успешно удален!"}), 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:
all_data = load_visitor_data()
org_details = all_data.get('organization_details', {})
# Ensure referral percentage exists and is a number
org_details['referral_percentage'] = float(org_details.get('referral_percentage', 2.0))
# Ensure phone_numbers is a list
if not isinstance(org_details.get('phone_numbers'), list):
org_details['phone_numbers'] = []
return jsonify(org_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()
referral_percentage = float(data.get("referral_percentage", 2.0))
if referral_percentage < 0:
return jsonify({"status": "error", "message": "Процент партнерских бонусов не может быть отрицательным."}), 400
phone_numbers = data.get("phone_numbers", [])
if not isinstance(phone_numbers, list):
phone_numbers = [] # Ensure it's a list
new_org_details = {
"name": data.get("name", "").strip(),
"phone_numbers": phone_numbers,
"address": data.get("address", "").strip(),
"whatsapp_link": data.get("whatsapp_link", "").strip(),
"telegram_link": data.get("telegram_link", "").strip(),
"referral_percentage": referral_percentage # Save as float
}
all_data = load_visitor_data()
all_data['organization_details'] = new_org_details
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "Настройки организации успешно сохранены!"}), 200
except Exception as e:
logging.exception("Error saving organization details")
return jsonify({"status": "error", "message": str(e)}), 500
if __name__ == '__main__':
print("--- BONUS SYSTEM SERVER ---")
print(f"Server starting on http://{HOST}:{PORT}")
if not HF_TOKEN_READ or not HF_TOKEN_WRITE:
print("WARNING: Hugging Face token(s) not set. Backup/restore functionality will be limited.")
else:
print("Attempting initial data download from Hugging Face...")
download_data_from_hf()
load_visitor_data()
print("WARNING: The /admin route is NOT protected. Implement proper authentication for production.")
if HF_TOKEN_WRITE:
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
backup_thread.start()
print("Periodic backup thread started (every hour).")
print("--- Server Ready ---")
app.run(host=HOST, port=PORT, debug=False)