Examplebonus / app.py
Kgshop's picture
Update app.py
0e018d0 verified
import os
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 flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError
from PIL import Image
import io
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.ERROR)
app.secret_key = os.urandom(24)
_data_lock = threading.Lock()
visitor_data_cache = {}
def generate_unique_id(all_data):
while True:
new_id = str(random.randint(10000, 99999))
if new_id not in all_data:
return new_id
def download_data_from_hf():
global visitor_data_cache
if not HF_TOKEN_READ:
return False
try:
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
)
with _data_lock:
try:
with open(DATA_FILE, 'r', encoding='utf-8') as f:
visitor_data_cache = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
visitor_data_cache = {}
return True
except RepositoryNotFoundError:
pass
except Exception:
pass
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)
except FileNotFoundError:
visitor_data_cache = {"organization_details": {}}
except json.JSONDecodeError:
visitor_data_cache = {"organization_details": {}}
except Exception:
visitor_data_cache = {"organization_details": {}}
if "organization_details" not in visitor_data_cache:
visitor_data_cache["organization_details"] = {}
return visitor_data_cache
def save_visitor_data(data):
with _data_lock:
try:
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4)
upload_data_to_hf_async()
except Exception:
pass
def upload_data_to_hf():
if not HF_TOKEN_WRITE:
return
if not os.path.exists(DATA_FILE):
return
try:
api = HfApi()
with _data_lock:
file_content_exists = os.path.getsize(DATA_FILE) > 0
if not file_content_exists:
return
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')}"
)
except Exception:
pass
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:
return
while True:
time.sleep(3600)
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:
pass
return parsed_data, True
else:
pass
return parsed_data, False
except Exception:
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);
}
* { 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 {
background-color: var(--card-bg);
border-radius: var(--border-radius);
padding: var(--padding-m);
display: flex;
justify-content: space-between;
align-items: center;
}
.client-id-label {
font-weight: 500;
color: var(--text-secondary-color);
}
.client-id-value {
font-size: 1.3em;
font-weight: 700;
color: var(--brand-yellow);
letter-spacing: 2px;
background-color: rgba(255,193,7,0.1);
padding: 4px 10px;
border-radius: 8px;
}
.history-section, .invoices-section, .business-card-section, .ton-wallet-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, .ton-wallet-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; }
.history-amount.deduction { color: #F44336; }
.invoice-amount { color: var(--brand-yellow); }
.no-history, .no-invoices {
text-align: center;
color: var(--text-secondary-color);
padding: 2rem 0;
}
.business-card-item, .ton-wallet-item {
margin-bottom: 10px;
}
.business-card-label, .ton-wallet-label {
font-weight: 500;
color: var(--text-secondary-color);
margin-bottom: 4px;
}
.business-card-value, .ton-wallet-value {
font-size: 1.1em;
font-weight: 600;
color: var(--text-color);
}
.business-card-value a, .ton-wallet-value a {
color: var(--brand-yellow);
text-decoration: none;
word-break: break-all;
}
.business-card-value a:hover, .ton-wallet-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;
}
.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);
}
.ton-wallet-connect-btn, .ton-wallet-disconnect-btn {
background-color: var(--brand-yellow);
color: var(--brand-black);
padding: 12px 20px;
border: none;
border-radius: 12px;
font-family: var(--font-family);
font-weight: 700;
font-size: 1.1em;
cursor: pointer;
width: 100%;
box-shadow: 0 4px 15px rgba(255,193,7,0.4);
transition: background-color 0.2s, box-shadow 0.2s;
}
.ton-wallet-disconnect-btn {
background-color: var(--brand-red);
color: var(--text-color);
box-shadow: 0 4px 15px rgba(244,67,54,0.4);
margin-top: 10px;
}
.ton-wallet-connect-btn:hover { background-color: #e0a800; box-shadow: 0 6px 20px rgba(255,193,7,0.5); }
.ton-wallet-disconnect-btn:hover { background-color: #d32f2f; box-shadow: 0 6px 20px rgba(244,67,54,0.5); }
.ton-wallet-details {
background-color: #2a2a2a;
border-radius: var(--border-radius);
padding: var(--padding-m);
margin-top: var(--padding-m);
}
.ton-wallet-detail-item {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid rgba(255,255,255,0.05);
}
.ton-wallet-detail-item:last-child { border-bottom: none; }
.ton-wallet-label-small {
font-size: 0.9em;
color: var(--text-secondary-color);
}
.ton-wallet-value-small {
font-size: 1em;
font-weight: 600;
color: var(--text-color);
word-break: break-all;
text-align: right;
}
.ton-wallet-value-small.balance {
color: var(--brand-yellow);
font-size: 1.2em;
}
.ton-status-message {
text-align: center;
color: var(--text-secondary-color);
margin-top: 10px;
font-size: 0.9em;
}
</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="ton-wallet-section">TON Кошелек</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="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 'deduction' }}">
{{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }}
</span>
{% elif item.transaction_type == 'debt' %}
<span class="history-amount {{ 'deduction' if item.type == 'accrual' else 'accrual' }}">
{{ '+' 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="ton-wallet-section" class="content-section">
<section class="ton-wallet-section">
<h2 class="ton-wallet-title">TON Кошелек</h2>
<div id="tonWalletContent">
<p id="tonStatusMessage" class="ton-status-message">Подключение...</p>
<button id="connectTonWalletBtn" class="ton-wallet-connect-btn" style="display: none;">Подключить TON Кошелек</button>
<div id="walletDetails" class="ton-wallet-details" style="display: none;">
<div class="ton-wallet-detail-item">
<span class="ton-wallet-label-small">Адрес кошелька:</span>
<span id="walletAddress" class="ton-wallet-value-small"></span>
</div>
<div class="ton-wallet-detail-item">
<span class="ton-wallet-label-small">Баланс TON:</span>
<span id="walletBalance" class="ton-wallet-value-small balance"></span>
</div>
</div>
<button id="disconnectTonWalletBtn" class="ton-wallet-disconnect-btn" style="display: none;">Отключить кошелек</button>
</div>
</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,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJjdXJyZW50Q29sb3IiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJtMjIuMDIyIDEuOTY3LTMuMDkgMy41MjNhOC40OCA4LjQ4IDAgMCAwLTEzLjA5OSAwTDEuOTc4IDEuOTY3Yy0uOTc0LTEuMTA3LTIuNTI1LS40MS0yLjUxMiAxLjAzNXYxOC44NjhjLjAwMSAxLjQ0NSAxLjUyOCAyLjEzNiAyLjQ4OCAxLjAzN2wzLjA5LTMuNTIzYTEw.xNi0uNzc4LS4wNzIuOTc0LjI3NSAxLjc2OC41NzIgMi4zNzUuODcxLjMwNS4xNS41NzcuMzEuNzk0LjQ1MS4yMTQuMTQzLjMyNC4yMi4zMjQuMjIuMDg2LS4yNzguMjYzLS42MS40NzYtLjkxMy4wNjItLjA4OC4xMzQtLjE4NS4yMTUtLjI4OC41MTQtLjY2MiAxLjExLS44NzUgMS44MS0uNTMxLjY0NC4zMTEgMS4xNzcuOCAxLjczMiAxLjUyLjQ3NS42ODkuOTUgMS4zNzkgMS40MjUgMi4wNzcuMzYzLjU1LjY4IDEuMDcuOTU3IDEuNTUzLjY1MiAxLjE0OSAxLjEzOCAxLjgxMiAxLjQ1MiAyLjEyNi40NzYuNDg3Ljg2LjgyNyAxLjI0MyAxLjA5Ni43NDEuNTIzIDEuNDg1LjkzNCAyLjIzNSAxLjIxMS43NDcuMjc0IDEuNDU1LjQ4NCAyLjExMy42MzYuNTY3LjEzIDEuMTU0LjE4MiAxLjczLjE1LjcxNC0uMDM1IDEuNDEtLjI0MyAxLjk3LS41Ny41ODEtLjMzOCAxLjA1NS0uODI5IDEuMzk3LTEuMzU1LjExOS0uMTc1LjIwMi0uMzguMjUtLjU4My4wNDctLjE4OS4wNjctLjM4OS4wNi0uNTkzWiIvPjwvc3ZnPg==">
{{ 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,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iI2ZmZiIgY2xhc3M9ImJpIGJpLXdoYXRzYXBwIiB2aWV3Qm94PSIwIDAgMTYgMTYiPjxwYXRoIGQ9Ik0xMy42NzYgMS40NTJBMTAuNTE1IDEw.wOTYtLjE1LjM3Mi0uMjg1LjcwMi0uNDgzLjMxLS40OC41MDktLjUxNS42NjktLjQ1Mi4xMDkuMDUxLjQxNy4yMTEuNDYzLjI2Ny4xNDEuMDgyLjI4NC4xNjEuNDQzLjIyNWExLjIyNyAxLjIyNyAwIDAgMCAuNzQ2LjAyNGwuMjg0LS4xMzVhMy45NjcgMy45NjcgMCAwIDAgLjY2Mi0uNjQzLjkwOC45MDggMCAwIDAgLjMwMi0uNjc4LjE5OC4xOTggMCAwIDAgMC0uMTU2LjgxNS44MTUgMCAwIDAgMC0uNDc3eiIvPjwvc3ZnPg==">
{{ 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,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgZmlsbD0iI2ZmZiIgY2xhc3M9ImJpIGJpLXQtZWxlZ3JhbSIgdmlld0JveD0iMCAwIDE2IDE2Ij48cGF0aCBkPSJNMTYuMDAyIDguNjkyYy4wMDItLjg3Ni0uNDQ1LTEuMzM1LTEuMzAzLTEuNjk0LS4zMjctLjEwNy0uNjk0LS4yMzctMS4wODgtLjM2Ny0xLjYzNi0uNTE2LTIuOTQzLTEuMzMtNC4xMy0yLjU0NS0uODkxLS44OC0xLjY0Ny0xLjcxLTIuMzc0LTIuNDE4LS40MTctLjM5My0uNTM3LS42Ni0uNTAyLS44NTEuMDExLS4wNjkuMDc1LS4yNTguMDgyLS4zNDkuMDY2LS44MjktLjMyLS45NzgtMS4xNS0uNzAyLS40ODcuMTU3LS45OTMuMzItMS41MTMuNDc1LS4yMS4wNjItLjM3OC4wOTktLjUuMTItLjU3LjA4OC0xLjE3NS4yNjQtMS43MDkuNDMzLS4zMy4xMTgtLjY3LjI1MS0xLjAyLjM4OC0uNzUuMjczLTEuNTA5LjU0Ni0yLjI3LjgwNi0uNzg1LjI2Mi0xLjQ3NC40NzUtMi4wNjQuNjQtLjUzNC4xNDYtLjkzNy4xNi0xLjIxMi0uMDctLjQ4NS0uNDA5LS45MS0uOTQ2LS40NzYtMS40NTEuMTU1LS4xNy4zNDctLjMyNi41NzYtLjQ2Ny4xNjktLjEwNS4zNjMtLjIwNy41ODItLjMxMy40NjktLjIyLjkyNi0uMzc0IDEuMzY4LS40NjkuNjMyLS4xMyAxLjI3MS0uMjE2IDEuOTItLjI3MS4yNzktLjAyNC41NTMtLjA0LjgyMy0uMDYuMDYxLS4xNzguMjUzLS41NTYuNTQ3LTEuMTUyLjY4MS0xLjM2NSAxLjQxNy0yLjE4MSAyLjE2Ni0yLjczMi42NzYtLjUwOCAxLjQwNy0uOTUzIDIuMjY2LTEuMjg5LjI2MS0uMTA5LjUyLS4xNDMuNzc4LS4wNzIuOTc0LjI3NSAxLjc2OC41NzIgMi4zNzUuODcxLjMwNS4xNS41NzcuMzEuNzk0LjQ1MS4yMTQuMTQzLjMyNC4yMi4zMjQuMjIuMDg2LS4yNzguMjYzLS42MS40NzYtLjkxMy4wNjItLjA4OC4xMzQtLjE4NS4yMTUtLjI4OC41MTQtLjY2MiAxLjExLS44NzUgMS44MS0uNTMxLjY0NC4zMTEgMS4xNzcuOCAxLjczMiAxLjUyLjQ3NS42ODkuOTUgMS4zNzkgMS40MjUgMi4wNzcuMzYzLjU1LjY4IDEuMDcuOTU3IDEuNTUzLjY1MiAxLjE0OSAxLjEzOCAxLjgxMiAxLjQ1MiAyLjEyNi40NzYuNDg3Ljg2LjgyNyAxLjI0MyAxLjA5Ni43NDEu5Lz48L3N2Zz4=">
{{ 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>
<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">
</ul>
<div id="invoiceDetailTotal" class="invoice-total-display">
<span>Итого:</span>
<span id="invoiceTotalAmount">0.00</span>
</div>
</div>
</div>
<script src="https://unpkg.com/@tonconnect/sdk@2.0.0/dist/ton-connect-sdk.min.js"></script>
<script src="https://unpkg.com/tonweb@0.0.60/dist/tonweb.standalone.min.js"></script>
<script>
const tg = window.Telegram.WebApp;
let userIdForBackend = '{{ user.id }}';
function applyTheme(themeParams) {
const root = document.documentElement;
const isDark = themeParams.bg_color ? (parseInt(themeParams.bg_color.substring(1, 3), 16) < 128) : true;
root.style.setProperty('--brand-black', themeParams.bg_color || '#101010');
root.style.setProperty('--text-color', themeParams.text_color || '#ffffff');
root.style.setProperty('--text-secondary-color', themeParams.hint_color || '#a0a0a0');
root.style.setProperty('--brand-yellow', themeParams.button_color || '#FFC107');
root.style.setProperty('--card-bg', themeParams.secondary_bg_color || (isDark ? '#1c1c1e' : '#f1f1f1'));
}
function setupTelegram() {
if (!tg || !tg.initData) {
document.body.style.visibility = 'visible';
return;
}
tg.ready();
tg.expand();
if (tg.themeParams && Object.keys(tg.themeParams).length > 0) {
applyTheme(tg.themeParams);
}
tg.onEvent('themeChanged', () => applyTheme(tg.themeParams));
const urlParams = new URLSearchParams(window.location.search);
const userIdForTest = urlParams.get('user_id_for_test');
if (!userIdForTest) {
fetch('/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({ initData: tg.initData }),
})
.then(response => response.json())
.then(data => {
if (data.status === 'ok' && data.verified && data.user_id) {
window.location.replace('/?user_id_for_test=' + data.user_id);
} else {
document.body.style.visibility = 'visible';
}
})
.catch(() => {
document.body.style.visibility = 'visible';
});
} else {
document.body.style.visibility = 'visible';
}
const user = tg.initDataUnsafe?.user;
const greetingElement = document.getElementById('greeting');
if (user) {
const name = user.first_name || user.username || 'Гость';
greetingElement.textContent = `Привет, ${name}! 👋`;
} else {
greetingElement.textContent = `Привет, {{ user.first_name or 'Гость' }}! 👋`;
}
}
function showSection(sectionId) {
document.querySelectorAll('.content-section').forEach(section => {
section.classList.remove('active');
});
document.getElementById(sectionId).classList.add('active');
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.classList.remove('active');
});
document.querySelector(`.nav-btn[data-target="${sectionId}"]`).classList.add('active');
}
function openModal(modalId) {
document.getElementById(modalId).style.display = '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');
}
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);
}
let tonConnector = null;
let currentTonAddress = '{{ user.ton_address or "" }}';
let tonWeb = null;
async function initializeTonConnect() {
try {
tonConnector = new TonConnect({
manifest: {
url: window.location.origin,
name: "Bonus System",
iconUrl: window.location.origin + "/static/ton_icon.png",
termsOfServiceUrl: window.location.origin + "/terms",
privacyPolicyUrl: window.location.origin + "/privacy"
}
});
tonWeb = new TonWeb(new TonWeb.HttpProvider('https://toncenter.com/api/v2/jsonRPC', {apiKey: 'YOUR_TONCENTER_API_KEY_HERE'}));
await tonConnector.restoreConnection();
tonConnector.onStatusChange(async walletInfo => {
if (walletInfo) {
currentTonAddress = walletInfo.account.address;
document.getElementById('walletAddress').textContent = currentTonAddress;
document.getElementById('connectTonWalletBtn').style.display = 'none';
document.getElementById('disconnectTonWalletBtn').style.display = 'block';
document.getElementById('walletDetails').style.display = 'block';
document.getElementById('tonStatusMessage').textContent = 'Кошелек подключен.';
await fetchTonBalance(currentTonAddress);
saveTonAddressToBackend(currentTonAddress);
} else {
currentTonAddress = '';
document.getElementById('walletAddress').textContent = 'Не подключен';
document.getElementById('walletBalance').textContent = '0 TON';
document.getElementById('connectTonWalletBtn').style.display = 'block';
document.getElementById('disconnectTonWalletBtn').style.display = 'none';
document.getElementById('walletDetails').style.display = 'none';
document.getElementById('tonStatusMessage').textContent = 'Кошелек не подключен.';
saveTonAddressToBackend('');
}
});
if (tonConnector.connected) {
document.getElementById('tonStatusMessage').textContent = 'Кошелек подключен.';
} else if (currentTonAddress) {
document.getElementById('walletAddress').textContent = currentTonAddress;
document.getElementById('walletDetails').style.display = 'block';
document.getElementById('connectTonWalletBtn').style.display = 'none';
document.getElementById('disconnectTonWalletBtn').style.display = 'block';
document.getElementById('tonStatusMessage').textContent = 'Загрузка данных кошелька...';
await fetchTonBalance(currentTonAddress);
} else {
document.getElementById('tonStatusMessage').textContent = 'Нажмите кнопку, чтобы подключить кошелек.';
document.getElementById('connectTonWalletBtn').style.display = 'block';
}
} catch (e) {
document.getElementById('tonStatusMessage').textContent = 'Ошибка инициализации Ton Connect: ' + e.message;
document.getElementById('connectTonWalletBtn').style.display = 'block';
}
}
async function connectTonWallet() {
if (!tonConnector) {
document.getElementById('tonStatusMessage').textContent = 'Ошибка: Ton Connect не инициализирован.';
return;
}
document.getElementById('tonStatusMessage').textContent = 'Ожидание подключения...';
try {
tonConnector.connect();
} catch (e) {
document.getElementById('tonStatusMessage').textContent = 'Ошибка подключения: ' + e.message;
}
}
async function disconnectTonWallet() {
if (!tonConnector) return;
document.getElementById('tonStatusMessage').textContent = 'Отключение...';
try {
await tonConnector.disconnect();
} catch (e) {
document.getElementById('tonStatusMessage').textContent = 'Ошибка отключения: ' + e.message;
}
}
async function fetchTonBalance(address) {
if (!tonWeb) return;
document.getElementById('walletBalance').textContent = 'Загрузка...';
try {
const wallet = new tonWeb.wallet.create({address: address});
const balanceNano = await tonWeb.getBalance(address);
const balanceTon = tonWeb.utils.fromNano(balanceNano);
document.getElementById('walletBalance').textContent = `${parseFloat(balanceTon).toFixed(4)} TON`;
} catch (e) {
document.getElementById('walletBalance').textContent = 'Ошибка';
document.getElementById('tonStatusMessage').textContent = 'Ошибка получения баланса: ' + e.message;
}
}
async function saveTonAddressToBackend(address) {
try {
const response = await fetch('/save_ton_address', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
user_id: userIdForBackend,
ton_address: address,
initData: tg.initData
}),
});
const result = await response.json();
if (response.ok) {
console.log('TON address saved:', result.message);
} else {
console.error('Failed to save TON address:', result.message);
}
} catch (error) {
console.error('Error saving TON address:', error);
}
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('connectTonWalletBtn').addEventListener('click', connectTonWallet);
document.getElementById('disconnectTonWalletBtn').addEventListener('click', disconnectTonWallet);
initializeTonConnect();
});
</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 .name { font-weight: 600; font-size: 1.2em; }
.user-details .username { color: var(--admin-secondary); font-size: 0.9em; }
.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); }
.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; }
.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; }
.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-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;
}
</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 }}">
<div class="user-info">
<img src="{{ user.photo_url if user.photo_url else 'data:image/svg+xml;charset=UTF-8,%3csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3e%3crect width=%27100%27 height=%27100%27 fill=%27%23e9ecef%27/%3e%3ctext x=%2750%25%27 y=%2755%25%27 dominant-baseline=%27middle%27 text-anchor=%27middle%27 font-size=%2745%27 font-family=%27sans-serif%27 fill=%27%23adb5bd%27%3e?%3c/text%3e%3c/svg%3e' }}" alt="User Avatar">
<div class="user-details">
<div class="name">{{ user.first_name or '' }} {{ user.last_name or '' }}</div>
<div class="username">@{{ user.username if user.username else user.phone_number }} | ID: {{ user.id }}</div>
</div>
</div>
<div class="user-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>
<div id="transactionModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal('transactionModal')">×</span>
<div class="modal-header">
<h2 id="modalUserName"></h2>
<div id="modalUserUsername" class="username"></div>
</div>
<input type="hidden" id="modalUserId">
<div class="tab-buttons">
<button class="tab-btn active" data-tab="bonus-debt-tab">Бонусы и долги</button>
<button class="tab-btn" data-tab="invoice-tab">Накладные</button>
</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" placeholder="1500" oninput="updateCalculations()">
</div>
<div class="form-group">
<label for="deductAmount">Списать бонусов</label>
<input type="number" id="deductAmount" 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" placeholder="500" oninput="updateCalculations()">
</div>
<div class="form-group">
<label for="repayDebtAmount">Погасить долг</label>
<input type="number" id="repayDebtAmount" 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>
</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>
<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>
<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>
<div class="modal-footer">
<div id="orgStatus" class="status-message"></div>
<button class="btn-submit" onclick="saveOrgSettings()">Сохранить настройки</button>
</div>
</div>
</div>
<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">
</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('modalUserName').textContent = `${userData.first_name || ''} ${userData.last_name || ''}`;
document.getElementById('modalUserUsername').textContent = `@${userData.username || userData.phone_number || ''} | ID: ${userData.id}`;
document.getElementById('purchaseAmount').value = '';
document.getElementById('deductAmount').value = '';
document.getElementById('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 === 'accrual' ? '+' : '-';
amountClass = item.type === 'accrual' ? 'bonus-accrual' : 'bonus-deduction';
amountText = `${sign}${parseFloat(item.amount).toFixed(2)}`;
} else {
sign = item.type === 'accrual' ? '+' : '-';
amountClass = item.type === 'accrual' ? 'debt-accrual' : 'debt-payment';
amountText = `${item.type === 'accrual' ? '+' : '-'}${parseFloat(item.amount).toFixed(2)}`;
}
li.innerHTML = `
<div>
<div class="desc">${item.description}</div>
<div class="date">${item.date_str}</div>
</div>
<div class="amount ${amountClass}">${amountText}</div>
`;
historyList.appendChild(li);
});
} else {
historyList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Нет истории</li>';
}
const modalInvoiceList = document.getElementById('modalInvoiceList');
modalInvoiceList.innerHTML = '';
const userInvoices = (currentUserData.invoices || []).sort((a, b) => new Date(b.date) - new Date(a.date));
if (userInvoices.length > 0) {
userInvoices.forEach(invoice => {
const li = document.createElement('li');
li.innerHTML = `
<div class="invoice-info">
Накладная #${invoice.invoice_id}<br>
${invoice.date_str}
</div>
<div style="display: flex; align-items: center;">
<span class="invoice-amount">${parseFloat(invoice.total_amount).toFixed(2)}</span>
<button class="view-btn" onclick='openAdminInvoiceDetailModal(${JSON.stringify(invoice)})'>👁️</button>
<button class="delete-btn" onclick='deleteInvoice("${currentUserData.id}", "${invoice.invoice_id}")'>🗑️</button>
</div>
`;
modalInvoiceList.appendChild(li);
});
} else {
modalInvoiceList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Накладных пока нет.</li>';
}
updateCalculations();
}
function openAddClientModal() {
document.getElementById('newClientFirstName').value = '';
document.getElementById('newClientPhone').value = '';
document.getElementById('addClientStatus').textContent = '';
addClientModal.style.display = 'block';
}
function openOrgSettingsModal() {
fetch('/admin/organization_details')
.then(response => response.json())
.then(data => {
document.getElementById('orgName').value = data.name || '';
document.getElementById('orgPhoneNumbers').value = (data.phone_numbers || []).join(',') || '';
document.getElementById('orgAddress').value = data.address || '';
document.getElementById('orgWhatsAppLink').value = data.whatsapp_link || '';
document.getElementById('orgTelegramLink').value = data.telegram_link || '';
document.getElementById('orgStatus').textContent = '';
orgSettingsModal.style.display = 'block';
})
.catch(() => {
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;
let finalDeductAmount = deductAmount;
if (deductAmount > currentBalance) {
finalDeductAmount = currentBalance;
document.getElementById('deductAmount').value = finalDeductAmount > 0 ? finalDeductAmount.toFixed(2) : '';
}
const finalBalance = currentBalance + accrualAmount - finalDeductAmount;
document.getElementById('summaryCurrentBalance').textContent = currentBalance.toFixed(2);
document.getElementById('summaryAccrual').textContent = `+${accrualAmount.toFixed(2)}`;
document.getElementById('summaryDeduction').textContent = `-${finalDeductAmount.toFixed(2)}`;
document.getElementById('summaryFinalBalance').textContent = finalBalance.toFixed(2);
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;
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 payload = {
user_id: document.getElementById('modalUserId').value,
purchase_amount: parseFloat(document.getElementById('purchaseAmount').value) || 0,
deduct_amount: parseFloat(document.getElementById('deductAmount').value) || 0,
add_debt_amount: parseFloat(document.getElementById('addDebtAmount').value) || 0,
repay_debt_amount: parseFloat(document.getElementById('repayDebtAmount').value) || 0,
};
if (payload.purchase_amount <= 0 && payload.deduct_amount <= 0 && payload.add_debt_amount <= 0 && payload.repay_debt_amount <= 0) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = 'Введите сумму для любой из операций.';
return;
}
try {
const response = await fetch('/admin/add_transaction', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await response.json();
if (response.ok) {
statusEl.style.color = 'var(--admin-success)';
statusEl.textContent = 'Операция успешно проведена!';
setTimeout(() => { location.reload(); }, 1500);
} else {
throw new Error(result.message || 'Произошла ошибка');
}
} catch (error) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = `Ошибка: ${error.message}`;
}
}
async function submitNewClient() {
const statusEl = document.getElementById('addClientStatus');
statusEl.style.color = 'var(--admin-secondary)';
statusEl.textContent = 'Сохранение...';
const payload = {
first_name: document.getElementById('newClientFirstName').value.trim(),
phone_number: document.getElementById('newClientPhone').value.trim(),
};
if (!payload.first_name || !payload.phone_number) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = 'Имя и номер телефона обязательны.';
return;
}
try {
const response = await fetch('/admin/add_client', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const result = await response.json();
if (response.ok) {
statusEl.style.color = 'var(--admin-success)';
statusEl.textContent = 'Клиент успешно добавлен!';
setTimeout(() => { location.reload(); }, 1500);
} else {
throw new Error(result.message || 'Произошла ошибка');
}
} catch (error) {
statusEl.style.color = 'var(--admin-danger)';
statusEl.textContent = `Ошибка: ${error.message}`;
}
}
async function 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()) : [];
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(),
};
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 = tableBody.rows.length - 1;
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 class="action-btn" onclick="removeInvoiceItemRow(this, ${rowIndex})">🗑️</button></td>
`;
}
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];
tableBody.rows[index].querySelector('.item-total-display').textContent = itemTotal.toFixed(2);
updateNewInvoiceTotal();
}
}
function removeInvoiceItemRow(button, index) {
const tableBody = document.getElementById('newInvoiceItemsTable').getElementsByTagName('tbody')[0];
tableBody.deleteRow(button.parentNode.parentNode.rowIndex - 1);
newInvoiceItems.splice(index, 1);
for (let i = 0; i < tableBody.rows.length; i++) {
const row = tableBody.rows[i];
row.querySelector('input[type="text"]').setAttribute('oninput', `updateInvoiceItem(${i}, 'product_name', this.value)`);
row.querySelector('input[type="number'][step="1"]').setAttribute('oninput', `updateInvoiceItem(${i}, 'quantity', parseFloat(this.value))`);
row.querySelector('input[type="number'][step="0.01"]').setAttribute('oninput', `updateInvoiceItem(${i}, 'unit_price', parseFloat(this.value))`);
row.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 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 = 'Накладная успешно сохранена!';
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();
} 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', () => {
addNewInvoiceItemRow();
});
</script>
</body>
</html>
"""
@app.route('/static/ton_icon.png')
def serve_ton_icon():
img = Image.new('RGBA', (100, 100), (0, 0, 0, 0))
byte_arr = io.BytesIO()
img.save(byte_arr, format='PNG')
byte_arr.seek(0)
return Response(byte_arr.getvalue(), mimetype='image/png')
@app.route('/terms')
def terms():
return "<h1>Terms of Service</h1><p>This is a placeholder for your terms of service.</p>"
@app.route('/privacy')
def privacy():
return "<h1>Privacy Policy</h1><p>This is a placeholder for your privacy policy.</p>"
@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:
user_data = all_data[user_id_str]
user_data['id'] = user_id_str
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'
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['ton_address'] = user_data.get('ton_address', '')
else:
user_data = {
"id": "N/A",
"bonuses": 0,
"debts": 0,
"history": [],
"debt_history": [],
"combined_history": [],
"invoices": [],
"ton_address": ""
}
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:
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()
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
if existing_user_key:
user_entry = all_data[existing_user_key]
user_entry.update({
'first_name': user_info_dict.get('first_name'),
'last_name': user_info_dict.get('last_name'),
'username': user_info_dict.get('username'),
'photo_url': user_info_dict.get('photo_url'),
'language_code': user_info_dict.get('language_code'),
'visited_at': now.timestamp(),
'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S')
})
user_id_to_save = existing_user_key
else:
new_user_id = generate_unique_id(all_data)
user_entry = {
'id': new_user_id,
'telegram_id': tg_user_id,
'first_name': user_info_dict.get('first_name'),
'last_name': user_info_dict.get('last_name'),
'username': user_info_dict.get('username'),
'photo_url': user_info_dict.get('photo_url'),
'language_code': user_info_dict.get('language_code'),
'is_premium': user_info_dict.get('is_premium', False),
'phone_number': None,
'visited_at': now.timestamp(),
'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'),
'bonuses': 0,
'history': [],
'debts': 0,
'debt_history': [],
'invoices': [],
'ton_address': ""
}
user_id_to_save = new_user_id
all_data[user_id_to_save] = user_entry
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:
return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 500
@app.route('/save_ton_address', methods=['POST'])
def save_ton_address():
try:
req_data = request.get_json()
internal_user_id = req_data.get('user_id')
ton_address = req_data.get('ton_address')
init_data_str = req_data.get('initData')
if not internal_user_id:
return jsonify({"status": "error", "message": "Internal User ID is required"}), 400
user_data_parsed, is_valid = verify_telegram_data(init_data_str)
if not is_valid:
return jsonify({"status": "error", "message": "Invalid Telegram InitData"}), 403
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:
user_info_dict = {}
telegram_user_id = user_info_dict.get('id')
all_data = load_visitor_data()
user_entry = all_data.get(internal_user_id)
if not user_entry or internal_user_id == "organization_details":
return jsonify({"status": "error", "message": "User not found"}), 404
if user_entry.get('telegram_id') is not None and str(user_entry.get('telegram_id')) != str(telegram_user_id):
return jsonify({"status": "error", "message": "Telegram user ID mismatch or not authorized to update this account"}), 403
user_entry['ton_address'] = ton_address
all_data[internal_user_id] = user_entry
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "TON address updated successfully"}), 200
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 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
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()
for key, user in all_data.items():
if key == "organization_details":
continue
if user.get('phone_number') == phone_number:
return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409
now = datetime.now(BISHKEK_TZ)
new_id = generate_unique_id(all_data)
new_client = {
'id': new_id,
'telegram_id': None,
'first_name': first_name,
'last_name': None,
'username': None,
'photo_url': None,
'language_code': 'ru',
'is_premium': False,
'phone_number': phone_number,
'visited_at': now.timestamp(),
'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'),
'bonuses': 0,
'history': [],
'debts': 0,
'debt_history': [],
'invoices': [],
'ton_address': ""
}
all_data[new_id] = new_client
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "Client added successfully"}), 201
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 500
@app.route('/admin/add_transaction', methods=['POST'])
def add_transaction():
try:
data = request.get_json()
user_id = data.get('user_id')
purchase_amount = float(data.get('purchase_amount', 0))
deduct_amount = float(data.get('deduct_amount', 0))
add_debt_amount = float(data.get('add_debt_amount', 0))
repay_debt_amount = float(data.get('repay_debt_amount', 0))
if not user_id:
return jsonify({"status": "error", "message": "User ID is required"}), 400
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')
if deduct_amount > user.get('bonuses', 0):
return jsonify({"status": "error", "message": "Недостаточно бонусов для списания"}), 400
if repay_debt_amount > user.get('debts', 0):
return jsonify({"status": "error", "message": "Сумма погашения превышает текущий долг"}), 400
accrual_amount = purchase_amount * 0.02
user['bonuses'] = round(user.get('bonuses', 0) + 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": round(accrual_amount, 2),
"description": f"Начисление с покупки {round(purchase_amount, 2)}",
"date": now_iso, "date_str": now_str
})
if deduct_amount > 0:
user['history'].append({
"type": "deduction", "amount": round(deduct_amount, 2),
"description": "Списание бонусов",
"date": now_iso, "date_str": now_str
})
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": round(add_debt_amount, 2),
"description": "Добавление долга",
"date": now_iso, "date_str": now_str
})
if repay_debt_amount > 0:
user['debt_history'].append({
"type": "payment", "amount": round(repay_debt_amount, 2),
"description": "Погашение долга",
"date": now_iso, "date_str": now_str
})
all_data[user_id_str] = user
save_visitor_data(all_data)
return jsonify({
"status": "ok", "message": "Transaction successful",
"new_balance": user['bonuses'], "new_debt": user['debts']
}), 200
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 500
@app.route('/admin/add_invoice', methods=['POST'])
def add_invoice():
try:
data = request.get_json()
user_id = data.get('user_id')
total_amount = float(data.get('total_amount', 0))
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
})
new_invoice = {
"invoice_id": invoice_id,
"date": now_iso,
"date_str": now_str,
"total_amount": round(total_amount, 2),
"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 added successfully", "invoice_id": invoice_id}), 200
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 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 inv.get('invoice_id') != invoice_id]
if len(user['invoices']) == original_invoice_count:
return jsonify({"status": "error", "message": "Invoice not found for this user"}), 404
all_data[user_id_str] = user
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "Invoice deleted successfully"}), 200
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 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": "Cannot delete a Telegram-linked user"}), 403
del all_data[user_id_str]
try:
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(all_data, f, ensure_ascii=False, indent=4)
upload_data_to_hf_async()
except Exception:
return jsonify({"status": "error", "message": "Failed to save data after deletion"}), 500
return jsonify({"status": "ok", "message": "Client deleted successfully"}), 200
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 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', {})
return jsonify(org_details), 200
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 500
@app.route('/admin/organization_details', methods=['POST'])
def save_organization_details():
try:
data = request.get_json()
new_org_details = {
"name": data.get("name", ""),
"phone_numbers": data.get("phone_numbers", []),
"address": data.get("address", ""),
"whatsapp_link": data.get("whatsapp_link", ""),
"telegram_link": data.get("telegram_link", "")
}
all_data = load_visitor_data()
all_data['organization_details'] = new_org_details
save_visitor_data(all_data)
return jsonify({"status": "ok", "message": "Organization details saved successfully"}), 200
except Exception:
return jsonify({"status": "error", "message": "Internal server error"}), 500
if __name__ == '__main__':
if not HF_TOKEN_READ or not HF_TOKEN_WRITE:
pass
else:
download_data_from_hf()
load_visitor_data()
if HF_TOKEN_WRITE:
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
backup_thread.start()
app.run(host=HOST, port=PORT, debug=False)