Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| 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, timezone | |
| import logging | |
| import threading | |
| import random | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from huggingface_hub.utils import RepositoryNotFoundError | |
| BOT_TOKEN = os.getenv("BOT_TOKEN", "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") | |
| app = Flask(__name__) | |
| logging.basicConfig(level=logging.INFO) | |
| app.secret_key = os.urandom(24) | |
| _data_lock = threading.Lock() | |
| visitor_data_cache = {} | |
| KYRGYZSTAN_TIMEZONE = timezone(timedelta(hours=6)) # UTC+6 for Bishkek | |
| def get_current_time_kyrgyzstan(): | |
| return datetime.now(KYRGYZSTAN_TIMEZONE) | |
| def generate_unique_id(all_data): | |
| while True: | |
| new_id = str(random.randint(10000, 99999)) | |
| if new_id not in all_data: | |
| return new_id | |
| def download_data_from_hf(): | |
| global visitor_data_cache | |
| if not HF_TOKEN_READ: | |
| logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.") | |
| return False | |
| try: | |
| logging.info(f"Attempting to download {HF_DATA_FILE_PATH} from {REPO_ID}...") | |
| hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=HF_DATA_FILE_PATH, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| local_dir_use_symlinks=False, | |
| force_download=True, | |
| etag_timeout=10 | |
| ) | |
| logging.info("Data file successfully downloaded from Hugging Face.") | |
| with _data_lock: | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as f: | |
| visitor_data_cache = json.load(f) | |
| logging.info("Successfully loaded downloaded data into cache.") | |
| except (FileNotFoundError, json.JSONDecodeError) as e: | |
| logging.error(f"Error reading downloaded data file: {e}. Starting with empty cache.") | |
| visitor_data_cache = {} | |
| return True | |
| except RepositoryNotFoundError: | |
| logging.error(f"Hugging Face repository '{REPO_ID}' not found. Cannot download data.") | |
| except Exception as e: | |
| logging.error(f"Error downloading data from Hugging Face: {e}") | |
| return False | |
| def load_visitor_data(): | |
| global visitor_data_cache | |
| with _data_lock: | |
| if not visitor_data_cache: | |
| try: | |
| with open(DATA_FILE, 'r', encoding='utf-8') as f: | |
| visitor_data_cache = json.load(f) | |
| logging.info("Visitor data loaded from local JSON.") | |
| except FileNotFoundError: | |
| logging.warning(f"{DATA_FILE} not found locally. Starting with empty data.") | |
| visitor_data_cache = {} | |
| except json.JSONDecodeError: | |
| logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.") | |
| visitor_data_cache = {} | |
| except Exception as e: | |
| logging.error(f"Unexpected error loading visitor data: {e}") | |
| visitor_data_cache = {} | |
| return visitor_data_cache | |
| def save_visitor_data(data): | |
| with _data_lock: | |
| try: | |
| visitor_data_cache.update(data) | |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4) | |
| logging.info(f"Visitor data successfully saved to {DATA_FILE}.") | |
| upload_data_to_hf_async() | |
| except Exception as e: | |
| logging.error(f"Error saving visitor data: {e}") | |
| def upload_data_to_hf(): | |
| if not HF_TOKEN_WRITE: | |
| logging.warning("HF_TOKEN_WRITE not set. Skipping Hugging Face upload.") | |
| return | |
| if not os.path.exists(DATA_FILE): | |
| logging.warning(f"{DATA_FILE} does not exist. Skipping upload.") | |
| return | |
| try: | |
| api = HfApi() | |
| with _data_lock: | |
| file_content_exists = os.path.getsize(DATA_FILE) > 0 | |
| if not file_content_exists: | |
| logging.warning(f"{DATA_FILE} is empty. Skipping upload.") | |
| return | |
| logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}/{HF_DATA_FILE_PATH}...") | |
| api.upload_file( | |
| path_or_fileobj=DATA_FILE, | |
| path_in_repo=HF_DATA_FILE_PATH, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Update bonus data {get_current_time_kyrgyzstan().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; | |
| --brand-green: #4CAF50; | |
| --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; | |
| } | |
| .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; | |
| } | |
| .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; | |
| } | |
| .navigation-buttons { | |
| display: grid; | |
| grid-template-columns: repeat(3, 1fr); | |
| gap: var(--padding-m); | |
| margin-top: var(--padding-m); | |
| } | |
| .nav-button { | |
| background-color: var(--card-bg); | |
| border-radius: var(--border-radius); | |
| padding: var(--padding-m); | |
| text-align: center; | |
| cursor: pointer; | |
| transition: background-color 0.2s ease, transform 0.2s ease; | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| justify-content: center; | |
| height: 80px; | |
| border: 1px solid rgba(255, 255, 255, 0.05); | |
| } | |
| .nav-button:hover { | |
| background-color: #2a2a2c; | |
| transform: translateY(-3px); | |
| } | |
| .nav-button-icon { | |
| font-size: 1.8em; | |
| margin-bottom: 8px; | |
| color: var(--brand-yellow); | |
| } | |
| .nav-button-text { | |
| font-size: 0.9em; | |
| font-weight: 500; | |
| color: var(--text-secondary-color); | |
| } | |
| .history-section { | |
| background-color: var(--card-bg); | |
| border-radius: var(--border-radius); | |
| padding: var(--padding-l); | |
| margin-top: var(--padding-m); | |
| } | |
| .history-title { | |
| font-size: 1.4em; | |
| font-weight: 700; | |
| margin-bottom: var(--padding-m); | |
| padding-bottom: var(--padding-m); | |
| border-bottom: 1px solid rgba(255, 255, 255, 0.1); | |
| } | |
| .history-list { | |
| list-style: none; | |
| padding: 0; | |
| margin: 0; | |
| max-height: 35vh; | |
| overflow-y: auto; | |
| } | |
| .history-item { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 14px 4px; | |
| border-bottom: 1px solid rgba(255, 255, 255, 0.05); | |
| } | |
| .history-item:last-child { border-bottom: none; } | |
| .history-details { display: flex; flex-direction: column; } | |
| .history-description { font-size: 1em; font-weight: 500; } | |
| .history-date { font-size: 0.8em; color: var(--text-secondary-color); margin-top: 4px; } | |
| .history-amount { font-size: 1.1em; font-weight: 700; } | |
| .history-amount.accrual { color: var(--brand-green); } | |
| .history-amount.deduction { color: var(--brand-red); } | |
| .no-history { | |
| text-align: center; | |
| color: var(--text-secondary-color); | |
| padding: 2rem 0; | |
| } | |
| .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.5); | |
| backdrop-filter: blur(5px); | |
| -webkit-backdrop-filter: blur(5px); | |
| padding: 20px; | |
| box-sizing: border-box; | |
| } | |
| .modal-content { | |
| background-color: var(--card-bg); | |
| margin: 20px auto; | |
| padding: var(--padding-l); | |
| border: 1px solid rgba(255, 255, 255, 0.05); | |
| border-radius: var(--border-radius); | |
| width: 100%; | |
| max-width: 700px; | |
| box-shadow: 0 0 30px rgba(255, 193, 7, 0.1); | |
| } | |
| .modal-header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| margin-bottom: var(--padding-m); | |
| padding-bottom: var(--padding-m); | |
| border-bottom: 1px solid rgba(255, 255, 255, 0.1); | |
| } | |
| .modal-header h2 { | |
| font-size: 1.5em; | |
| font-weight: 700; | |
| color: var(--brand-yellow); | |
| } | |
| .modal-close { | |
| font-size: 2em; | |
| cursor: pointer; | |
| color: var(--text-secondary-color); | |
| line-height: 1; | |
| } | |
| .modal-close:hover { | |
| color: var(--text-color); | |
| } | |
| .invoice-section { | |
| background-color: var(--card-bg); | |
| border-radius: var(--border-radius); | |
| padding: var(--padding-m); | |
| margin-bottom: var(--padding-m); | |
| border: 1px solid rgba(255, 255, 255, 0.05); | |
| } | |
| .invoice-title { | |
| font-size: 1.3em; | |
| font-weight: 700; | |
| margin-bottom: var(--padding-m); | |
| color: var(--brand-yellow); | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| } | |
| .invoice-date { | |
| font-size: 0.9em; | |
| color: var(--text-secondary-color); | |
| } | |
| .invoice-item { | |
| display: flex; | |
| justify-content: space-between; | |
| padding: 10px 0; | |
| border-bottom: 1px dashed rgba(255, 255, 255, 0.1); | |
| font-size: 0.95em; | |
| } | |
| .invoice-item:last-child { | |
| border-bottom: none; | |
| } | |
| .invoice-item .name { flex-grow: 1; margin-right: 10px; } | |
| .invoice-item .quantity { min-width: 50px; text-align: right; margin-right: 10px; } | |
| .invoice-item .price { min-width: 80px; text-align: right; } | |
| .invoice-total { | |
| text-align: right; | |
| font-size: 1.2em; | |
| font-weight: 700; | |
| margin-top: var(--padding-m); | |
| padding-top: var(--padding-m); | |
| border-top: 1px solid rgba(255, 255, 255, 0.1); | |
| } | |
| .no-invoices { | |
| text-align: center; | |
| color: var(--text-secondary-color); | |
| padding: 2rem 0; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <header class="header"> | |
| <div class="logo">BONUS<span>.</span></div> | |
| <p id="greeting" class="welcome-text">Добро пожаловать!</p> | |
| </header> | |
| <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="navigation-buttons"> | |
| <div class="nav-button" onclick="openModal('businessCardModal')"> | |
| <div class="nav-button-icon">🏢</div> | |
| <div class="nav-button-text">Визитка</div> | |
| </div> | |
| <div class="nav-button" onclick="openModal('invoicesModal')"> | |
| <div class="nav-button-icon">📄</div> | |
| <div class="nav-button-text">Накладные</div> | |
| </div> | |
| <div class="nav-button" onclick="openModal('historyModal')"> | |
| <div class="nav-button-icon">⏱️</div> | |
| <div class="nav-button-text">История</div> | |
| </div> | |
| </section> | |
| <section class="history-section"> | |
| <h2 class="history-title">Последние операции</h2> | |
| {% if user.combined_history %} | |
| <ul class="history-list"> | |
| {% for item in user.combined_history[:5] %} | |
| <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> | |
| {% if user.combined_history|length > 5 %} | |
| <p style="text-align: center; margin-top: 16px;"><a href="#" onclick="openModal('historyModal'); return false;" style="color: var(--brand-yellow); text-decoration: none;">Посмотреть всю историю</a></p> | |
| {% endif %} | |
| {% else %} | |
| <p class="no-history">Операций пока не было.</p> | |
| {% endif %} | |
| </section> | |
| </div> | |
| <!-- Business Card Modal --> | |
| <div id="businessCardModal" class="modal"> | |
| <div class="modal-content"> | |
| <div class="modal-header"> | |
| <h2>Визитная карточка</h2> | |
| <span class="modal-close" onclick="closeModal('businessCardModal')">×</span> | |
| </div> | |
| <div class="invoice-section" style="text-align: center;"> | |
| <h3 style="color: var(--brand-yellow); margin-bottom: var(--padding-m);">{{ business_info.name }}</h3> | |
| <p style="color: var(--text-secondary-color); margin-bottom: 8px;">{{ business_info.address }}</p> | |
| <p style="color: var(--text-secondary-color); margin-bottom: 8px;">Тел: {{ business_info.phone1 }}</p> | |
| {% if business_info.phone2 %} | |
| <p style="color: var(--text-secondary-color); margin-bottom: 8px;">Тел: {{ business_info.phone2 }}</p> | |
| {% endif %} | |
| <div style="margin-top: 16px;"> | |
| <a href="tel:{{ business_info.phone1 }}" style="text-decoration: none; margin: 0 8px;"><img src="https://img.icons8.com/ios-glyphs/30/FFC107/phone.png" alt="Call"></a> | |
| {% if business_info.whatsapp %} | |
| <a href="https://wa.me/{{ business_info.whatsapp.replace('+', '') }}" target="_blank" style="text-decoration: none; margin: 0 8px;"><img src="https://img.icons8.com/ios-filled/30/FFC107/whatsapp.png" alt="WhatsApp"></a> | |
| {% endif %} | |
| {% if business_info.telegram_username %} | |
| <a href="https://t.me/{{ business_info.telegram_username.lstrip('@') }}" target="_blank" style="text-decoration: none; margin: 0 8px;"><img src="https://img.icons8.com/ios-filled/30/FFC107/telegram-app.png" alt="Telegram"></a> | |
| {% endif %} | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Invoices Modal --> | |
| <div id="invoicesModal" class="modal"> | |
| <div class="modal-content"> | |
| <div class="modal-header"> | |
| <h2>Мои накладные</h2> | |
| <span class="modal-close" onclick="closeModal('invoicesModal')">×</span> | |
| </div> | |
| {% if user.invoices %} | |
| {% for invoice in user.invoices %} | |
| <div class="invoice-section"> | |
| <div class="invoice-title"> | |
| <span>Накладная #{{ invoice.id }}</span> | |
| <span class="invoice-date">{{ invoice.date_str }}</span> | |
| </div> | |
| {% for item in invoice.items %} | |
| <div class="invoice-item"> | |
| <span class="name">{{ item.name }}</span> | |
| <span class="quantity">{{ item.quantity }} шт.</span> | |
| <span class="price">{{ "%.2f"|format(item.price|float) }}</span> | |
| </div> | |
| {% endfor %} | |
| <div class="invoice-total"> | |
| Итого: {{ "%.2f"|format(invoice.total_amount|float) }} сом | |
| </div> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <p class="no-invoices">У вас пока нет накладных.</p> | |
| {% endif %} | |
| </div> | |
| </div> | |
| <!-- History Modal --> | |
| <div id="historyModal" class="modal"> | |
| <div class="modal-content"> | |
| <div class="modal-header"> | |
| <h2>История операций</h2> | |
| <span class="modal-close" onclick="closeModal('historyModal')">×</span> | |
| </div> | |
| {% 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 %} | |
| </div> | |
| </div> | |
| <script> | |
| const tg = window.Telegram.WebApp; | |
| function applyTheme(themeParams) { | |
| const root = document.documentElement; | |
| const isDark = themeParams.bg_color ? (parseInt(themeParams.bg_color.substring(1, 3), 16) < 128) : true; | |
| root.style.setProperty('--brand-black', themeParams.bg_color || '#101010'); | |
| root.style.setProperty('--text-color', themeParams.text_color || '#ffffff'); | |
| root.style.setProperty('--text-secondary-color', themeParams.hint_color || '#a0a0a0'); | |
| root.style.setProperty('--brand-yellow', themeParams.button_color || '#FFC107'); | |
| root.style.setProperty('--card-bg', themeParams.secondary_bg_color || (isDark ? '#1c1c1e' : '#f1f1f1')); | |
| } | |
| function setupTelegram() { | |
| if (!tg || !tg.initData) { | |
| console.error("Telegram WebApp script not loaded or initData is missing."); | |
| document.body.style.visibility = 'visible'; | |
| return; | |
| } | |
| tg.ready(); | |
| tg.expand(); | |
| if (tg.themeParams && Object.keys(tg.themeParams).length > 0) { | |
| applyTheme(tg.themeParams); | |
| } | |
| tg.onEvent('themeChanged', () => applyTheme(tg.themeParams)); | |
| const urlParams = new URLSearchParams(window.location.search); | |
| const userIdForTest = urlParams.get('user_id_for_test'); | |
| if (!userIdForTest) { | |
| fetch('/verify', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, | |
| body: JSON.stringify({ initData: tg.initData }), | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.status === 'ok' && data.verified && data.user_id) { | |
| window.location.replace('/?user_id_for_test=' + data.user_id); | |
| } else { | |
| console.warn('Backend verification failed:', data.message); | |
| document.body.style.visibility = 'visible'; | |
| } | |
| }) | |
| .catch(error => { | |
| console.error('Error sending initData for verification:', error); | |
| document.body.style.visibility = 'visible'; | |
| }); | |
| } else { | |
| document.body.style.visibility = 'visible'; | |
| } | |
| const user = tg.initDataUnsafe?.user; | |
| const greetingElement = document.getElementById('greeting'); | |
| if (user) { | |
| const name = user.first_name || user.username || 'Гость'; | |
| greetingElement.textContent = `Привет, ${name}! 👋`; | |
| } else { | |
| greetingElement.textContent = `Привет, {{ user.first_name or 'Гость' }}! 👋`; | |
| } | |
| } | |
| if (window.Telegram && window.Telegram.WebApp) { | |
| setupTelegram(); | |
| } else { | |
| window.addEventListener('load', setupTelegram, {once: true}); | |
| setTimeout(() => { | |
| if (document.body.style.visibility !== 'visible') { | |
| document.body.style.visibility = 'visible'; | |
| } | |
| }, 3000); | |
| } | |
| function openModal(modalId) { | |
| const modal = document.getElementById(modalId); | |
| if (modal) { | |
| modal.style.display = 'block'; | |
| } | |
| } | |
| function closeModal(modalId) { | |
| const modal = document.getElementById(modalId); | |
| if (modal) { | |
| modal.style.display = 'none'; | |
| } | |
| } | |
| window.onclick = function(event) { | |
| if (event.target.classList.contains('modal')) { | |
| closeModal(event.target.id); | |
| } | |
| } | |
| </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"], .controls-bar input[type="tel"], .controls-bar input[type="number"] { 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: 200px; } | |
| .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; } | |
| .btn-edit { background-color: var(--admin-secondary); color: white; } | |
| .btn-edit:hover { background-color: #545b62; } | |
| .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-close:hover { color: #777; } | |
| .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: repeat(auto-fill, minmax(250px, 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 { 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; } | |
| .btn-submit:hover { background-color: #157346; } | |
| .status-message { text-align: center; font-weight: 500; flex-grow: 1; text-align: left; } | |
| .invoice-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--padding); margin-top: var(--padding); } | |
| .invoice-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; } | |
| .invoice-card:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08); } | |
| .invoice-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; border-bottom: 1px solid var(--admin-border); padding-bottom: 0.5rem; } | |
| .invoice-header .id { font-weight: 600; font-size: 1.1em; } | |
| .invoice-header .date { color: var(--admin-secondary); font-size: 0.9em; } | |
| .invoice-items-list { list-style: none; padding: 0; margin: 0; border-bottom: 1px solid var(--admin-border); padding-bottom: 0.5rem; margin-bottom: 0.5rem; } | |
| .invoice-item-admin { display: flex; justify-content: space-between; font-size: 0.9em; margin-bottom: 5px; } | |
| .invoice-item-admin .name { flex-grow: 1; margin-right: 10px; } | |
| .invoice-item-admin .quantity, .invoice-item-admin .price { min-width: 60px; text-align: right; } | |
| .invoice-total-admin { text-align: right; font-weight: 600; margin-top: 0.5rem; } | |
| .invoice-actions { margin-top: auto; display: flex; gap: 0.5rem; } | |
| .btn-invoice-delete { background-color: var(--admin-danger); color: white; padding: 8px 15px; font-size: 0.9em; border-radius: 6px; } | |
| .btn-invoice-delete:hover { background-color: #c82333; } | |
| .add-item-row { display: grid; grid-template-columns: 1fr 1fr 1fr auto; gap: 0.5rem; margin-bottom: 0.5rem; align-items: center; } | |
| .add-item-row input { padding: 8px; font-size: 0.9em; border: 1px solid var(--admin-border); border-radius: 6px; } | |
| .add-item-row .btn-add-item { padding: 8px 15px; font-size: 0.9em; border-radius: 6px; background-color: var(--admin-primary); color: #000; border: none; cursor: pointer; } | |
| .add-item-row .btn-add-item:hover { background-color: var(--admin-primary-dark); } | |
| .invoice-calculation-summary { background: #f0f0f0; padding: 0.75rem; border-radius: 6px; margin-top: 1rem; } | |
| .summary-item-admin { display: flex; justify-content: space-between; margin-bottom: 0.4rem; font-size: 0.9em; } | |
| .summary-item-admin strong { font-weight: 600; } | |
| .no-invoices-admin { text-align: center; color: var(--admin-secondary); margin-top: 2rem; font-size: 1.1em; } | |
| .company-info-section { background: 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); margin-bottom: var(--padding); } | |
| .company-info-section h3 { margin-top: 0; margin-bottom: 1.5rem; font-size: 1.3em; border-bottom: 1px solid var(--admin-border); padding-bottom: 0.5rem; } | |
| .company-info-section .form-group { margin-bottom: 1rem; } | |
| .company-info-section .form-group label { margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9em; } | |
| .company-info-section .form-group input { padding: 10px; font-size: 1rem; border: 1px solid var(--admin-border); border-radius: 8px; width: 100%; box-sizing: border-box; } | |
| .company-info-section .btn-save-company { display: block; width: fit-content; margin-top: 1.5rem; margin-left: auto; } | |
| </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="openCompanyInfoModal()">Настроить визитку</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> | |
| <button class="btn-manage" onclick='openInvoiceModal({{ user|tojson }})'>Накладные</button> | |
| {% if user.telegram_id == None %} | |
| <button class="btn btn-delete" onclick='deleteClient("{{ user.id }}")'>Удалить клиента</button> | |
| {% endif %} | |
| </div> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| {% else %} | |
| <p class="no-users">Пользователей пока нет.</p> | |
| {% endif %} | |
| </div> | |
| <div id="transactionModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="modal-close" onclick="closeModal('transactionModal')">×</span> | |
| <div class="modal-header"> | |
| <h2 id="modalUserName"></h2> | |
| <div id="modalUserUsername" class="username"></div> | |
| </div> | |
| <input type="hidden" id="modalUserId"> | |
| <div class="form-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> | |
| <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="invoiceModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="modal-close" onclick="closeModal('invoiceModal')">×</span> | |
| <div class="modal-header"> | |
| <h2 id="invoiceModalUserName"></h2> | |
| <div id="invoiceModalUserUsername" class="username"></div> | |
| </div> | |
| <input type="hidden" id="invoiceModalUserId"> | |
| <div id="invoiceStatusMessage" class="status-message" style="margin-bottom: 1rem;"></div> | |
| <div class="form-section"> | |
| <h3>Добавить новую накладную</h3> | |
| <div class="add-item-row"> | |
| <input type="text" id="newItemName" placeholder="Название товара"> | |
| <input type="number" id="newItemQuantity" placeholder="Кол-во" min="1"> | |
| <input type="number" id="newItemPrice" placeholder="Цена за ед." step="0.01"> | |
| <button class="btn-add-item" onclick="addItemToList()">Добавить товар</button> | |
| </div> | |
| <ul id="invoiceItemList" style="list-style: none; padding: 0; margin-top: 1rem;"></ul> | |
| <div class="invoice-calculation-summary"> | |
| <div class="summary-item-admin"><span>Всего товаров:</span> <strong id="itemCountSummary">0</strong></div> | |
| <div class="summary-item-admin"><span>Итоговая сумма:</span> <strong id="invoiceTotalSummary">0.00</strong></div> | |
| </div> | |
| </div> | |
| <div class="history-container"> | |
| <h3>История накладных</h3> | |
| <div id="invoiceHistoryList" class="invoice-grid"></div> | |
| </div> | |
| <div class="modal-footer"> | |
| <button class="btn-submit" onclick="saveInvoice()">Сохранить накладную</button> | |
| </div> | |
| </div> | |
| </div> | |
| <div id="companyInfoModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="modal-close" onclick="closeModal('companyInfoModal')">×</span> | |
| <div class="modal-header"> | |
| <h2>Настройки визитной карточки</h2> | |
| </div> | |
| <div class="company-info-section"> | |
| <div class="form-group"> | |
| <label for="companyName">Название организации</label> | |
| <input type="text" id="companyName" placeholder="Название"> | |
| </div> | |
| <div class="form-group"> | |
| <label for="companyAddress">Адрес</label> | |
| <input type="text" id="companyAddress" placeholder="Адрес"> | |
| </div> | |
| <div class="form-row"> | |
| <div class="form-group"> | |
| <label for="companyPhone1">Телефон 1</label> | |
| <input type="tel" id="companyPhone1" placeholder="+996 XXX XXX XXX"> | |
| </div> | |
| <div class="form-group"> | |
| <label for="companyPhone2">Телефон 2 (опционально)</label> | |
| <input type="tel" id="companyPhone2" placeholder="+996 XXX XXX XXX"> | |
| </div> | |
| </div> | |
| <div class="form-group"> | |
| <label for="companyWhatsapp">WhatsApp (для кнопки, без +)</label> | |
| <input type="tel" id="companyWhatsapp" placeholder="996XXXXXXXXXX"> | |
| </div> | |
| <div class="form-group"> | |
| <label for="companyTelegram">Telegram (для кнопки, с @)</label> | |
| <input type="text" id="companyTelegram" placeholder="@username"> | |
| </div> | |
| <button class="btn btn-primary btn-save-company" onclick="saveCompanyInfo()">Сохранить настройки</button> | |
| </div> | |
| </div> | |
| </div> | |
| <script> | |
| const transactionModal = document.getElementById('transactionModal'); | |
| const addClientModal = document.getElementById('addClientModal'); | |
| const invoiceModal = document.getElementById('invoiceModal'); | |
| const companyInfoModal = document.getElementById('companyInfoModal'); | |
| let currentUserData = null; | |
| let currentInvoiceModalUser = null; | |
| let invoiceItems = []; | |
| 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 = ''; | |
| const historyList = document.getElementById('modalHistoryList'); | |
| historyList.innerHTML = ''; | |
| const bonusHistory = (userData.history || []).map(h => ({...h, transaction_type: 'bonus'})); | |
| const debtHistory = (userData.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' ? 'accrual' : 'deduction'; | |
| amountText = `${sign}${parseFloat(item.amount).toFixed(2)} (бонус)`; | |
| } else { | |
| sign = item.type === 'accrual' ? '+' : '-'; | |
| amountClass = item.type === 'accrual' ? 'deduction' : 'accrual'; | |
| amountText = `${sign}${parseFloat(item.amount).toFixed(2)} (долг)`; | |
| } | |
| li.innerHTML = ` | |
| <div> | |
| <div class="history-description">${item.description}</div> | |
| <div class="history-date">${item.date_str}</div> | |
| </div> | |
| <div class="history-amount ${amountClass}">${amountText}</div> | |
| `; | |
| historyList.appendChild(li); | |
| }); | |
| } else { | |
| historyList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Нет истории</li>'; | |
| } | |
| updateCalculations(); | |
| transactionModal.style.display = 'block'; | |
| } | |
| function openAddClientModal() { | |
| document.getElementById('newClientFirstName').value = ''; | |
| document.getElementById('newClientPhone').value = ''; | |
| document.getElementById('addClientStatus').textContent = ''; | |
| addClientModal.style.display = 'block'; | |
| } | |
| function openInvoiceModal(userData) { | |
| currentInvoiceModalUser = userData; | |
| document.getElementById('invoiceModalUserId').value = userData.id; | |
| document.getElementById('invoiceModalUserName').textContent = `${userData.first_name || ''} ${userData.last_name || ''}`; | |
| document.getElementById('invoiceModalUserUsername').textContent = `@${userData.username || userData.phone_number} | ID: ${userData.id}`; | |
| invoiceItems = []; | |
| refreshInvoiceItemList(); | |
| refreshInvoiceTotal(); | |
| document.getElementById('invoiceStatusMessage').textContent = ''; | |
| document.getElementById('invoiceHistoryList').innerHTML = ''; | |
| const invoiceHistoryList = document.getElementById('invoiceHistoryList'); | |
| if (userData.invoices && userData.invoices.length > 0) { | |
| userData.invoices.forEach(invoice => { | |
| const invoiceCard = document.createElement('div'); | |
| invoiceCard.className = 'invoice-card'; | |
| let itemsHtml = ''; | |
| invoice.items.forEach(item => { | |
| itemsHtml += ` | |
| <div class="invoice-item-admin"> | |
| <span class="name">${item.name}</span> | |
| <span class="quantity">${item.quantity} шт.</span> | |
| <span class="price">${parseFloat(item.price).toFixed(2)}</span> | |
| </div> | |
| `; | |
| }); | |
| invoiceCard.innerHTML = ` | |
| <div class="invoice-header"> | |
| <span class="id">#${invoice.id}</span> | |
| <span class="date">${invoice.date_str}</span> | |
| </div> | |
| <ul class="invoice-items-list">${itemsHtml}</ul> | |
| <div class="invoice-total-admin">Итого: ${parseFloat(invoice.total_amount).toFixed(2)} сом</div> | |
| <div class="invoice-actions"> | |
| <button class="btn btn-delete btn-invoice-delete" onclick="deleteInvoice('${userData.id}', '${invoice.id}')">Удалить</button> | |
| </div> | |
| `; | |
| invoiceHistoryList.appendChild(invoiceCard); | |
| }); | |
| } else { | |
| invoiceHistoryList.innerHTML = '<p class="no-invoices-admin">Нет накладных.</p>'; | |
| } | |
| invoiceModal.style.display = 'block'; | |
| } | |
| function openCompanyInfoModal() { | |
| const companyInfo = JSON.parse(localStorage.getItem('companyInfo') || '{}'); | |
| document.getElementById('companyName').value = companyInfo.name || ''; | |
| document.getElementById('companyAddress').value = companyInfo.address || ''; | |
| document.getElementById('companyPhone1').value = companyInfo.phone1 || ''; | |
| document.getElementById('companyPhone2').value = companyInfo.phone2 || ''; | |
| document.getElementById('companyWhatsapp').value = companyInfo.whatsapp || ''; | |
| document.getElementById('companyTelegram').value = companyInfo.telegram_username || ''; | |
| companyInfoModal.style.display = 'block'; | |
| } | |
| function closeModal(modalId) { | |
| document.getElementById(modalId).style.display = 'none'; | |
| if (modalId === 'transactionModal') { | |
| currentUserData = null; | |
| } | |
| if (modalId === 'invoiceModal') { | |
| currentInvoiceModalUser = null; | |
| invoiceItems = []; | |
| } | |
| } | |
| 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); | |
| } | |
| function addItemToList() { | |
| const name = document.getElementById('newItemName').value.trim(); | |
| const quantity = parseInt(document.getElementById('newItemQuantity').value); | |
| const price = parseFloat(document.getElementById('newItemPrice').value); | |
| if (!name || isNaN(quantity) || quantity <= 0 || isNaN(price) || price < 0) { | |
| alert('Пожалуйста, введите корректные данные для товара.'); | |
| return; | |
| } | |
| invoiceItems.push({ name, quantity, price }); | |
| refreshInvoiceItemList(); | |
| refreshInvoiceTotal(); | |
| document.getElementById('newItemName').value = ''; | |
| document.getElementById('newItemQuantity').value = ''; | |
| document.getElementById('newItemPrice').value = ''; | |
| } | |
| function refreshInvoiceItemList() { | |
| const list = document.getElementById('invoiceItemList'); | |
| list.innerHTML = ''; | |
| invoiceItems.forEach((item, index) => { | |
| const li = document.createElement('li'); | |
| li.className = 'invoice-item-admin'; | |
| li.innerHTML = ` | |
| <span class="name">${item.name}</span> | |
| <span class="quantity">${item.quantity} шт.</span> | |
| <span class="price">${item.price.toFixed(2)}</span> | |
| <button class="btn-delete" style="padding: 5px 10px; font-size: 0.8em;" onclick="removeItemFromList(${index})">Удалить</button> | |
| `; | |
| list.appendChild(li); | |
| }); | |
| } | |
| function removeItemFromList(index) { | |
| invoiceItems.splice(index, 1); | |
| refreshInvoiceItemList(); | |
| refreshInvoiceTotal(); | |
| } | |
| function refreshInvoiceTotal() { | |
| let total = 0; | |
| invoiceItems.forEach(item => { | |
| total += item.quantity * item.price; | |
| }); | |
| document.getElementById('itemCountSummary').textContent = invoiceItems.length; | |
| document.getElementById('invoiceTotalSummary').textContent = total.toFixed(2); | |
| } | |
| async function saveInvoice() { | |
| const userId = document.getElementById('invoiceModalUserId').value; | |
| const statusEl = document.getElementById('invoiceStatusMessage'); | |
| statusEl.style.color = 'var(--admin-secondary)'; | |
| statusEl.textContent = 'Сохранение...'; | |
| if (invoiceItems.length === 0) { | |
| statusEl.style.color = 'var(--admin-danger)'; | |
| statusEl.textContent = 'Добавьте хотя бы один товар в накладную.'; | |
| return; | |
| } | |
| const totalAmount = parseFloat(document.getElementById('invoiceTotalSummary').textContent); | |
| const invoiceData = { | |
| user_id: userId, | |
| items: invoiceItems, | |
| total_amount: totalAmount | |
| }; | |
| try { | |
| const response = await fetch('/admin/add_invoice', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(invoiceData) | |
| }); | |
| 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 deleteInvoice(userId, invoiceId) { | |
| if (!confirm('Вы уверены, что хотите удалить эту накладную?')) 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}`); | |
| } | |
| } | |
| function saveCompanyInfo() { | |
| const companyInfo = { | |
| name: document.getElementById('companyName').value.trim(), | |
| address: document.getElementById('companyAddress').value.trim(), | |
| phone1: document.getElementById('companyPhone1').value.trim(), | |
| phone2: document.getElementById('companyPhone2').value.trim(), | |
| whatsapp: document.getElementById('companyWhatsapp').value.trim(), | |
| telegram_username: document.getElementById('companyTelegram').value.trim() | |
| }; | |
| localStorage.setItem('companyInfo', JSON.stringify(companyInfo)); | |
| alert('Настройки визитной карточки сохранены!'); | |
| closeModal('companyInfoModal'); | |
| } | |
| 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 deleteClient(userId) { | |
| if (!confirm(`Вы уверены, что хотите удалить клиента с ID ${userId}? Это действие необратимо.`)) { | |
| return; | |
| } | |
| try { | |
| const response = await fetch('/admin/delete_client', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ user_id: userId }) | |
| }); | |
| const result = await response.json(); | |
| if (response.ok) { | |
| location.reload(); | |
| } else { | |
| throw new Error(result.message || 'Не удалось удалить клиента.'); | |
| } | |
| } catch (error) { | |
| alert(`Ошибка: ${error.message}`); | |
| } | |
| } | |
| window.onclick = function(event) { | |
| if (event.target.classList.contains('modal')) { | |
| closeModal(event.target.id); | |
| } | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| def index(): | |
| user_id_str = request.args.get('user_id_for_test') | |
| current_data = load_visitor_data() | |
| user_data = {} | |
| if user_id_str and user_id_str in current_data: | |
| user_data = current_data[user_id_str] | |
| user_data['id'] = user_id_str | |
| 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 | |
| else: | |
| user_data = { | |
| "id": "N/A", | |
| "bonuses": 0, | |
| "debts": 0, | |
| "history": [], | |
| "debt_history": [], | |
| "combined_history": [], | |
| "invoices": [], | |
| "first_name": "Гость" | |
| } | |
| return render_template_string(TEMPLATE, user=user_data) | |
| def verify_data(): | |
| try: | |
| req_data = request.get_json() | |
| init_data_str = req_data.get('initData') | |
| if not init_data_str: | |
| return jsonify({"status": "error", "message": "Missing initData"}), 400 | |
| user_data_parsed, is_valid = verify_telegram_data(init_data_str) | |
| user_info_dict = {} | |
| if user_data_parsed and 'user' in user_data_parsed: | |
| try: | |
| user_json_str = unquote(user_data_parsed['user'][0]) | |
| user_info_dict = json.loads(user_json_str) | |
| except Exception as e: | |
| logging.error(f"Could not parse user JSON: {e}") | |
| user_info_dict = {} | |
| if is_valid: | |
| tg_user_id = user_info_dict.get('id') | |
| if tg_user_id: | |
| now = get_current_time_kyrgyzstan() | |
| all_data = load_visitor_data() | |
| existing_user_key = None | |
| for key, user_data_item in all_data.items(): | |
| if str(user_data_item.get('telegram_id')) == str(tg_user_id): | |
| existing_user_key = key | |
| break | |
| if existing_user_key: | |
| user_entry = all_data[existing_user_key] | |
| user_entry.update({ | |
| 'first_name': user_info_dict.get('first_name'), | |
| 'last_name': user_info_dict.get('last_name'), | |
| 'username': user_info_dict.get('username'), | |
| 'photo_url': user_info_dict.get('photo_url'), | |
| 'language_code': user_info_dict.get('language_code'), | |
| 'visited_at': now.timestamp(), | |
| 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S') | |
| }) | |
| user_id_to_save = existing_user_key | |
| else: | |
| new_user_id = generate_unique_id(all_data) | |
| user_entry = { | |
| 'id': new_user_id, | |
| 'telegram_id': tg_user_id, | |
| 'first_name': user_info_dict.get('first_name'), | |
| 'last_name': user_info_dict.get('last_name'), | |
| 'username': user_info_dict.get('username'), | |
| 'photo_url': user_info_dict.get('photo_url'), | |
| 'language_code': user_info_dict.get('language_code'), | |
| 'is_premium': user_info_dict.get('is_premium', False), | |
| 'phone_number': None, | |
| 'visited_at': now.timestamp(), | |
| 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'), | |
| 'bonuses': 0, | |
| 'history': [], | |
| 'debts': 0, | |
| 'debt_history': [], | |
| 'invoices': [] | |
| } | |
| user_id_to_save = new_user_id | |
| save_visitor_data({user_id_to_save: user_entry}) | |
| return jsonify({"status": "ok", "verified": True, "user_id": user_id_to_save}) | |
| else: | |
| return jsonify({"status": "error", "verified": True, "message": "User ID not found in parsed data"}), 400 | |
| else: | |
| logging.warning(f"Verification failed for user: {user_info_dict.get('id')}") | |
| return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403 | |
| except Exception as e: | |
| logging.exception("Error in /verify endpoint") | |
| return jsonify({"status": "error", "message": "Internal server error"}), 500 | |
| def admin_panel(): | |
| current_data = load_visitor_data() | |
| users_list = [] | |
| for user_id, user_data in current_data.items(): | |
| user_data['id'] = user_id | |
| users_list.append(user_data) | |
| 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) | |
| def add_client(): | |
| try: | |
| data = request.get_json() | |
| phone_number = data.get('phone_number') | |
| first_name = data.get('first_name') | |
| if not phone_number or not first_name: | |
| return jsonify({"status": "error", "message": "Имя и номер телефона обязательны."}), 400 | |
| all_data = load_visitor_data() | |
| for user in all_data.values(): | |
| if user.get('phone_number') == phone_number: | |
| return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409 | |
| now = get_current_time_kyrgyzstan() | |
| 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': [] | |
| } | |
| save_visitor_data({new_id: new_client}) | |
| return jsonify({"status": "ok", "message": "Client added successfully"}), 201 | |
| except Exception as e: | |
| logging.exception("Error in /admin/add_client endpoint") | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| 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: | |
| return jsonify({"status": "error", "message": "User not found"}), 404 | |
| user = all_data[user_id_str] | |
| now = get_current_time_kyrgyzstan() | |
| 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'] = user.get('bonuses', 0) + accrual_amount - deduct_amount | |
| if 'history' not in user or not isinstance(user['history'], list): | |
| user['history'] = [] | |
| if accrual_amount > 0: | |
| user['history'].append({ | |
| "type": "accrual", "amount": accrual_amount, | |
| "description": f"Начисление с покупки {purchase_amount:.2f}", | |
| "date": now_iso, "date_str": now_str | |
| }) | |
| if deduct_amount > 0: | |
| user['history'].append({ | |
| "type": "deduction", "amount": deduct_amount, | |
| "description": f"Списание бонусов ({deduct_amount:.2f})", | |
| "date": now_iso, "date_str": now_str | |
| }) | |
| user['debts'] = user.get('debts', 0) + add_debt_amount - repay_debt_amount | |
| 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": f"Добавление долга {add_debt_amount:.2f}", | |
| "date": now_iso, "date_str": now_str | |
| }) | |
| if repay_debt_amount > 0: | |
| user['debt_history'].append({ | |
| "type": "payment", "amount": repay_debt_amount, | |
| "description": f"Погашение долга {repay_debt_amount:.2f}", | |
| "date": now_iso, "date_str": now_str | |
| }) | |
| save_visitor_data({user_id_str: user}) | |
| 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 | |
| def add_invoice(): | |
| try: | |
| data = request.get_json() | |
| user_id = data.get('user_id') | |
| items = data.get('items') | |
| total_amount = float(data.get('total_amount', 0)) | |
| if not user_id or not items: | |
| return jsonify({"status": "error", "message": "User ID and items are required."}), 400 | |
| user_id_str = str(user_id) | |
| all_data = load_visitor_data() | |
| if user_id_str not in all_data: | |
| return jsonify({"status": "error", "message": "User not found."}), 404 | |
| user = all_data[user_id_str] | |
| now = get_current_time_kyrgyzstan() | |
| now_iso = now.isoformat() | |
| now_str = now.strftime('%Y-%m-%d %H:%M:%S') | |
| next_invoice_id = 1 | |
| if user.get('invoices'): | |
| next_invoice_id = max(inv['id'] for inv in user['invoices']) + 1 | |
| new_invoice = { | |
| 'id': next_invoice_id, | |
| 'items': items, | |
| 'total_amount': total_amount, | |
| 'date': now_iso, | |
| 'date_str': now_str | |
| } | |
| if 'invoices' not in user or not isinstance(user['invoices'], list): | |
| user['invoices'] = [] | |
| user['invoices'].append(new_invoice) | |
| save_visitor_data({user_id_str: user}) | |
| return jsonify({"status": "ok", "message": "Invoice added successfully."}), 201 | |
| except Exception as e: | |
| logging.exception("Error in /admin/add_invoice endpoint") | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| def delete_invoice(): | |
| try: | |
| data = request.get_json() | |
| user_id = data.get('user_id') | |
| invoice_id = int(data.get('invoice_id')) | |
| if not user_id or invoice_id is None: | |
| 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: | |
| return jsonify({"status": "error", "message": "User not found."}), 404 | |
| user = all_data[user_id_str] | |
| initial_invoice_count = len(user.get('invoices', [])) | |
| user['invoices'] = [inv for inv in user.get('invoices', []) if inv['id'] != invoice_id] | |
| if len(user['invoices']) == initial_invoice_count: | |
| return jsonify({"status": "error", "message": "Invoice not found for this user."}), 404 | |
| save_visitor_data({user_id_str: user}) | |
| return jsonify({"status": "ok", "message": "Invoice deleted successfully."}), 200 | |
| except Exception as e: | |
| logging.exception("Error in /admin/delete_invoice endpoint") | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| def delete_client(): | |
| try: | |
| data = request.get_json() | |
| user_id = data.get('user_id') | |
| if not user_id: | |
| return jsonify({"status": "error", "message": "User ID is required"}), 400 | |
| user_id_str = str(user_id) | |
| load_visitor_data() | |
| with _data_lock: | |
| if user_id_str not in visitor_data_cache: | |
| return jsonify({"status": "error", "message": "User not found"}), 404 | |
| user_to_delete = visitor_data_cache[user_id_str] | |
| if user_to_delete.get('telegram_id') is not None: | |
| return jsonify({"status": "error", "message": "Cannot delete a Telegram-linked user"}), 403 | |
| del visitor_data_cache[user_id_str] | |
| try: | |
| with open(DATA_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4) | |
| logging.info(f"User {user_id_str} deleted. Data saved to {DATA_FILE}.") | |
| upload_data_to_hf_async() | |
| except Exception as e: | |
| logging.error(f"Error saving data after deletion: {e}") | |
| return jsonify({"status": "error", "message": "Failed to save data after deletion"}), 500 | |
| return jsonify({"status": "ok", "message": "Client deleted successfully"}), 200 | |
| except Exception as e: | |
| logging.exception("Error in /admin/delete_client endpoint") | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| if __name__ == '__main__': | |
| print("--- 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) |