Spaces:
Running
Running
| #!/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, timedelta | |
| 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 = {} | |
| def get_bishkek_time(): | |
| return datetime.now(timezone(timedelta(hours=6))) | |
| 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_bishkek_time().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info("Bonus data successfully uploaded to Hugging Face.") | |
| except Exception as e: | |
| logging.error(f"Error uploading data to Hugging Face: {e}") | |
| def upload_data_to_hf_async(): | |
| upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True) | |
| upload_thread.start() | |
| def periodic_backup(): | |
| if not HF_TOKEN_WRITE: | |
| logging.info("Periodic backup disabled: HF_TOKEN_WRITE not set.") | |
| return | |
| while True: | |
| time.sleep(3600) | |
| logging.info("Initiating periodic backup...") | |
| upload_data_to_hf() | |
| def verify_telegram_data(init_data_str): | |
| try: | |
| parsed_data = parse_qs(init_data_str) | |
| received_hash = parsed_data.pop('hash', [None])[0] | |
| if not received_hash: | |
| return None, False | |
| data_check_list = [] | |
| for key, value in sorted(parsed_data.items()): | |
| data_check_list.append(f"{key}={value[0]}") | |
| data_check_string = "\n".join(data_check_list) | |
| secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest() | |
| calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() | |
| if calculated_hash == received_hash: | |
| auth_date = int(parsed_data.get('auth_date', [0])[0]) | |
| current_time = int(time.time()) | |
| if current_time - auth_date > 86400: | |
| logging.warning(f"Telegram InitData is older than 24 hours (Auth Date: {auth_date}, Current: {current_time}).") | |
| return parsed_data, True | |
| else: | |
| logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}") | |
| return parsed_data, False | |
| except Exception as e: | |
| logging.error(f"Error verifying Telegram data: {e}") | |
| return None, False | |
| TEMPLATE = """ | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no, user-scalable=no, viewport-fit=cover"> | |
| <title>Bonus</title> | |
| <script src="https://telegram.org/js/telegram-web-app.js"></script> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap" rel="stylesheet"> | |
| <style> | |
| :root { | |
| --brand-yellow: #FFC107; | |
| --brand-black: #101010; | |
| --brand-red: #F44336; | |
| --card-bg: #1c1c1e; | |
| --text-color: #ffffff; | |
| --text-secondary-color: #a0a0a0; | |
| --border-radius: 16px; | |
| --padding-m: 16px; | |
| --padding-l: 24px; | |
| --font-family: 'Manrope', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; | |
| --shadow-color: rgba(255, 193, 7, 0.15); | |
| --shadow-glow: 0 0 35px var(--shadow-color); | |
| --shadow-color-red: rgba(244, 67, 54, 0.15); | |
| --shadow-glow-red: 0 0 35px var(--shadow-color-red); | |
| } | |
| * { 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; | |
| } | |
| .history-section { | |
| background-color: var(--card-bg); | |
| border-radius: var(--border-radius); | |
| padding: var(--padding-l); | |
| } | |
| .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: #4CAF50; } | |
| .history-amount.deduction { color: #F44336; } | |
| .no-history { | |
| text-align: center; | |
| color: var(--text-secondary-color); | |
| padding: 2rem 0; | |
| } | |
| .action-buttons { | |
| display: flex; | |
| gap: var(--padding-m); | |
| margin-top: var(--padding-m); | |
| } | |
| .btn-action { | |
| background-color: var(--brand-yellow); | |
| color: var(--brand-black); | |
| padding: 12px 20px; | |
| border: none; | |
| border-radius: 12px; | |
| font-size: 1.1em; | |
| font-weight: 700; | |
| cursor: pointer; | |
| flex: 1; | |
| text-align: center; | |
| text-decoration: none; | |
| transition: background-color 0.2s, transform 0.2s; | |
| } | |
| .btn-action:hover { | |
| background-color: #e0a800; | |
| transform: translateY(-2px); | |
| } | |
| </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> | |
| <div class="action-buttons"> | |
| <a href="{{ url_for('view_invoice', user_id=user.id) }}" class="btn-action">Мои накладные</a> | |
| <a href="{{ url_for('view_company_info') }}" class="btn-action">Визитка</a> | |
| </div> | |
| <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> | |
| <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); | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| COMPANY_INFO_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>Визитка Компании</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; | |
| } | |
| * { 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; | |
| min-height: 100vh; | |
| } | |
| .container { | |
| max-width: 600px; | |
| margin: 0 auto; | |
| display: flex; | |
| flex-direction: column; | |
| gap: var(--padding-m); | |
| background: var(--card-bg); | |
| border-radius: var(--border-radius); | |
| padding: var(--padding-l); | |
| } | |
| .header { | |
| text-align: center; | |
| margin-bottom: var(--padding-m); | |
| border-bottom: 1px solid rgba(255, 255, 255, 0.1); | |
| padding-bottom: var(--padding-m); | |
| } | |
| .logo { | |
| font-size: 2.5em; | |
| font-weight: 800; | |
| color: var(--text-color); | |
| letter-spacing: -1px; | |
| } | |
| .logo span { color: var(--brand-yellow); } | |
| .company-name { | |
| font-size: 1.8em; | |
| font-weight: 700; | |
| margin-top: 8px; | |
| } | |
| .contact-info { | |
| display: flex; | |
| flex-direction: column; | |
| gap: 12px; | |
| text-align: left; | |
| } | |
| .contact-item { | |
| display: flex; | |
| align-items: center; | |
| gap: 12px; | |
| } | |
| .contact-item i { | |
| color: var(--brand-yellow); | |
| font-size: 1.4em; | |
| width: 24px; /* Align icons */ | |
| text-align: center; | |
| } | |
| .contact-item span { | |
| font-size: 1.1em; | |
| flex-grow: 1; | |
| } | |
| .contact-item a { | |
| color: var(--text-color); | |
| text-decoration: none; | |
| font-weight: 500; | |
| } | |
| .social-links { | |
| display: flex; | |
| justify-content: center; | |
| gap: 20px; | |
| margin-top: var(--padding-m); | |
| } | |
| .social-links a { | |
| color: var(--text-secondary-color); | |
| font-size: 2em; | |
| transition: color 0.2s ease; | |
| } | |
| .social-links a:hover { | |
| color: var(--brand-yellow); | |
| } | |
| .back-button { | |
| display: block; | |
| width: fit-content; | |
| margin: var(--padding-l) auto 0; | |
| background-color: var(--brand-yellow); | |
| color: var(--brand-black); | |
| padding: 12px 25px; | |
| border: none; | |
| border-radius: 12px; | |
| font-size: 1.1em; | |
| font-weight: 700; | |
| cursor: pointer; | |
| text-decoration: none; | |
| transition: background-color 0.2s, transform 0.2s; | |
| } | |
| .back-button:hover { | |
| background-color: #e0a800; | |
| transform: translateY(-2px); | |
| } | |
| </style> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <header class="header"> | |
| <div class="logo">BONUS<span>.</span></div> | |
| <h1 class="company-name">{{ company_info.name }}</h1> | |
| </header> | |
| <section class="contact-info"> | |
| <div class="contact-item"> | |
| <i class="fas fa-phone"></i> | |
| <span>Телефон</span> | |
| <a href="tel:{{ company_info.phone1 }}">{{ company_info.phone1 }}</a> | |
| </div> | |
| {% if company_info.phone2 %} | |
| <div class="contact-item"> | |
| <i class="fas fa-phone"></i> | |
| <span>Телефон</span> | |
| <a href="tel:{{ company_info.phone2 }}">{{ company_info.phone2 }}</a> | |
| </div> | |
| {% endif %} | |
| {% if company_info.whatsapp %} | |
| <div class="contact-item"> | |
| <i class="fab fa-whatsapp"></i> | |
| <span>WhatsApp</span> | |
| <a href="https://wa.me/{{ company_info.whatsapp.lstrip('+') }}" target="_blank">{{ company_info.whatsapp }}</a> | |
| </div> | |
| {% endif %} | |
| {% if company_info.telegram %} | |
| <div class="contact-item"> | |
| <i class="fab fa-telegram-plane"></i> | |
| <span>Telegram</span> | |
| <a href="https://t.me/{{ company_info.telegram.lstrip('@') }}" target="_blank">@{{ company_info.telegram.lstrip('@') }}</a> | |
| </div> | |
| {% endif %} | |
| <div class="contact-item"> | |
| <i class="fas fa-map-marker-alt"></i> | |
| <span>Адрес</span> | |
| <span>{{ company_info.address }}</span> | |
| </div> | |
| </section> | |
| <div class="social-links"> | |
| {% if company_info.website %} | |
| <a href="{{ company_info.website }}" target="_blank"><i class="fas fa-globe"></i></a> | |
| {% endif %} | |
| {% if company_info.facebook %} | |
| <a href="{{ company_info.facebook }}" target="_blank"><i class="fab fa-facebook-f"></i></a> | |
| {% endif %} | |
| {% if company_info.instagram %} | |
| <a href="{{ company_info.instagram }}" target="_blank"><i class="fab fa-instagram"></i></a> | |
| {% endif %} | |
| {% if company_info.tiktok %} | |
| <a href="{{ company_info.tiktok }}" target="_blank"><i class="fab fa-tiktok"></i></a> | |
| {% endif %} | |
| </div> | |
| <a href="{{ url_for('index', user_id_for_test=user_id) }}" class="back-button">Назад</a> | |
| </div> | |
| <script> | |
| const tg = window.Telegram.WebApp; | |
| function applyTheme(themeParams) { | |
| const root = document.documentElement; | |
| 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 || '#1c1c1e'); | |
| } | |
| function setupTelegram() { | |
| tg.ready(); | |
| tg.expand(); | |
| if (tg.themeParams && Object.keys(tg.themeParams).length > 0) { | |
| applyTheme(tg.themeParams); | |
| } | |
| tg.onEvent('themeChanged', () => applyTheme(tg.themeParams)); | |
| } | |
| if (window.Telegram && window.Telegram.WebApp) { | |
| setupTelegram(); | |
| } else { | |
| window.addEventListener('load', setupTelegram, {once: true}); | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| INVOICE_LIST_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>Мои накладные</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; | |
| } | |
| * { 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; | |
| min-height: 100vh; | |
| } | |
| .container { | |
| max-width: 600px; | |
| margin: 0 auto; | |
| display: flex; | |
| flex-direction: column; | |
| gap: var(--padding-m); | |
| background: var(--card-bg); | |
| border-radius: var(--border-radius); | |
| padding: var(--padding-l); | |
| } | |
| .header { | |
| text-align: center; | |
| margin-bottom: var(--padding-m); | |
| border-bottom: 1px solid rgba(255, 255, 255, 0.1); | |
| padding-bottom: var(--padding-m); | |
| } | |
| .logo { | |
| font-size: 2.5em; | |
| font-weight: 800; | |
| color: var(--text-color); | |
| letter-spacing: -1px; | |
| } | |
| .logo span { color: var(--brand-yellow); } | |
| .title { | |
| font-size: 1.8em; | |
| font-weight: 700; | |
| margin-top: 8px; | |
| margin-bottom: var(--padding-m); | |
| } | |
| .invoice-list { | |
| list-style: none; | |
| padding: 0; | |
| margin: 0; | |
| } | |
| .invoice-item { | |
| background: linear-gradient(145deg, #2a2a2a, #1c1c1c); | |
| border-radius: var(--border-radius); | |
| padding: var(--padding-m); | |
| margin-bottom: var(--padding-m); | |
| display: flex; | |
| flex-direction: column; | |
| gap: 8px; | |
| border: 1px solid rgba(255, 193, 7, 0.2); | |
| } | |
| .invoice-header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| font-weight: 600; | |
| } | |
| .invoice-date { | |
| font-size: 0.9em; | |
| color: var(--text-secondary-color); | |
| } | |
| .invoice-total { | |
| font-size: 1.2em; | |
| font-weight: 700; | |
| color: var(--brand-yellow); | |
| } | |
| .invoice-details { | |
| margin-top: 10px; | |
| padding-top: 10px; | |
| border-top: 1px dashed rgba(255, 255, 255, 0.2); | |
| font-size: 0.9em; | |
| color: var(--text-secondary-color); | |
| } | |
| .no-invoices { | |
| text-align: center; | |
| color: var(--text-secondary-color); | |
| padding: 2rem 0; | |
| } | |
| .back-button { | |
| display: block; | |
| width: fit-content; | |
| margin: var(--padding-l) auto 0; | |
| background-color: var(--brand-yellow); | |
| color: var(--brand-black); | |
| padding: 12px 25px; | |
| border: none; | |
| border-radius: 12px; | |
| font-size: 1.1em; | |
| font-weight: 700; | |
| cursor: pointer; | |
| text-decoration: none; | |
| transition: background-color 0.2s, transform 0.2s; | |
| } | |
| .back-button:hover { | |
| background-color: #e0a800; | |
| transform: translateY(-2px); | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <header class="header"> | |
| <div class="logo">BONUS<span>.</span></div> | |
| <h1 class="title">Мои накладные</h1> | |
| </header> | |
| {% if invoices %} | |
| <ul class="invoice-list"> | |
| {% for invoice in invoices %} | |
| <li class="invoice-item"> | |
| <div class="invoice-header"> | |
| <span>Накладная №{{ invoice.id }}</span> | |
| <span class="invoice-date">{{ invoice.created_at_str }}</span> | |
| </div> | |
| <div class="invoice-details"> | |
| {% for item in invoice.items %} | |
| {{ item.product_name }} - {{ item.quantity }} шт. x {{ "%.2f"|format(item.unit_price) }} = {{ "%.2f"|format(item.total_price) }}<br> | |
| {% endfor %} | |
| </div> | |
| <div class="invoice-total">Итого: {{ "%.2f"|format(invoice.total_amount) }}</div> | |
| </li> | |
| {% endfor %} | |
| </ul> | |
| {% else %} | |
| <p class="no-invoices">Накладных пока нет.</p> | |
| {% endif %} | |
| <a href="{{ url_for('index', user_id_for_test=user_id) }}" class="back-button">Назад</a> | |
| </div> | |
| <script> | |
| const tg = window.Telegram.WebApp; | |
| function applyTheme(themeParams) { | |
| const root = document.documentElement; | |
| 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 || '#1c1c1e'); | |
| } | |
| function setupTelegram() { | |
| tg.ready(); | |
| tg.expand(); | |
| if (tg.themeParams && Object.keys(tg.themeParams).length > 0) { | |
| applyTheme(tg.themeParams); | |
| } | |
| tg.onEvent('themeChanged', () => applyTheme(tg.themeParams)); | |
| } | |
| if (window.Telegram && window.Telegram.WebApp) { | |
| setupTelegram(); | |
| } else { | |
| window.addEventListener('load', setupTelegram, {once: true}); | |
| } | |
| </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 { 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; } | |
| .company-info-section { border: 1px solid var(--admin-border); border-radius: 8px; padding: 1.5rem; margin-bottom: 1.5rem; } | |
| .company-info-section h3 { margin-top: 0; font-size: 1.3em; color: var(--admin-primary); margin-bottom: 1rem; } | |
| .company-form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem; margin-bottom: 1.5rem; } | |
| .company-form-group { display: flex; flex-direction: column; } | |
| .company-form-group label { margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9em; } | |
| .company-form-group input, .company-form-group textarea { padding: 10px; font-size: 1rem; border: 1px solid var(--admin-border); border-radius: 8px; width: 100%; box-sizing: border-box; } | |
| .company-form-group textarea { resize: vertical; min-height: 60px; } | |
| .company-btn-save { | |
| display: block; | |
| width: fit-content; | |
| padding: 12px 25px; | |
| background-color: var(--admin-success); | |
| color: white; | |
| border: none; | |
| border-radius: 8px; | |
| font-size: 1.1em; | |
| font-weight: 600; | |
| cursor: pointer; | |
| transition: background-color 0.2s; | |
| } | |
| .company-btn-save:hover { background-color: #157347; } | |
| .invoice-management-section { border: 1px solid var(--admin-border); border-radius: 8px; padding: 1.5rem; margin-bottom: 1.5rem; } | |
| .invoice-management-section h3 { margin-top: 0; font-size: 1.3em; color: var(--admin-primary); margin-bottom: 1rem; } | |
| .invoice-form-row { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem; align-items: flex-end; } | |
| .invoice-form-group { display: flex; flex-direction: column; margin-bottom: 1rem; } | |
| .invoice-form-group label { margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9em; } | |
| .invoice-form-group input { padding: 10px; font-size: 1rem; border: 1px solid var(--admin-border); border-radius: 8px; width: 100%; box-sizing: border-box; } | |
| .invoice-item-controls { display: flex; align-items: center; gap: 0.5rem; margin-top: 1rem; } | |
| .invoice-item-controls button { padding: 8px 12px; font-size: 0.9em; border-radius: 6px; border: none; cursor: pointer; } | |
| .btn-add-item { background-color: var(--admin-primary); color: #000; } | |
| .btn-add-item:hover { background-color: var(--admin-primary-dark); } | |
| .btn-remove-item { background-color: var(--admin-danger); color: white; } | |
| .btn-remove-item:hover { background-color: #c82333; } | |
| .invoice-calculation-summary { background: #f0f0f0; padding: 1rem; border-radius: 8px; margin-top: 1rem; } | |
| .invoice-summary-item { display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-size: 0.95em; } | |
| .invoice-summary-item strong { font-weight: 600; } | |
| .invoice-modal-footer { margin-top: 1.5rem; display: flex; justify-content: flex-end; align-items: center; gap: 1rem;} | |
| .invoice-btn-submit { padding: 12px 25px; font-size: 1.1em; border-radius: 8px; border: none; font-weight: 600; cursor: pointer; background-color: var(--admin-success); color: white; } | |
| .invoice-btn-submit:hover { background-color: #157347; } | |
| </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> | |
| </div> | |
| <div class="company-info-section"> | |
| <h3>Информация о компании</h3> | |
| <div class="company-form-row"> | |
| <div class="company-form-group"> | |
| <label for="companyName">Название компании</label> | |
| <input type="text" id="companyName" value="{{ company_info.name }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyPhone1">Телефон 1</label> | |
| <input type="text" id="companyPhone1" value="{{ company_info.phone1 }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyPhone2">Телефон 2</label> | |
| <input type="text" id="companyPhone2" value="{{ company_info.phone2 }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyWhatsapp">WhatsApp (с +)</label> | |
| <input type="text" id="companyWhatsapp" value="{{ company_info.whatsapp }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyTelegram">Telegram (с @)</label> | |
| <input type="text" id="companyTelegram" value="{{ company_info.telegram }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyAddress">Адрес</label> | |
| <textarea id="companyAddress">{{ company_info.address }}</textarea> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyWebsite">Сайт</label> | |
| <input type="text" id="companyWebsite" value="{{ company_info.website }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyFacebook">Facebook</label> | |
| <input type="text" id="companyFacebook" value="{{ company_info.facebook }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyInstagram">Instagram</label> | |
| <input type="text" id="companyInstagram" value="{{ company_info.instagram }}"> | |
| </div> | |
| <div class="company-form-group"> | |
| <label for="companyTiktok">TikTok</label> | |
| <input type="text" id="companyTiktok" value="{{ company_info.tiktok }}"> | |
| </div> | |
| </div> | |
| <button class="company-btn-save" onclick="saveCompanyInfo()">Сохранить информацию о компании</button> | |
| <div id="companyInfoStatus" class="status-message" style="margin-top: 10px;"></div> | |
| </div> | |
| <div class="invoice-management-section"> | |
| <h3>Создание накладной</h3> | |
| <div id="invoiceItemsContainer"> | |
| <div class="invoice-form-row"> | |
| <div class="invoice-form-group"> | |
| <label>Клиент (ID или Телефон)</label> | |
| <input type="text" class="client-lookup-input" placeholder="Введите ID или телефон клиента"> | |
| <div class="client-lookup-results" style="position: absolute; background: white; border: 1px solid #ccc; max-height: 150px; overflow-y: auto; z-index: 1002; width: calc(100% - 2px); display: none;"></div> | |
| <input type="hidden" class="client-id-input" value=""> | |
| </div> | |
| <div class="invoice-form-group"> | |
| <label>Товар</label> | |
| <input type="text" class="product-name-input" placeholder="Название товара"> | |
| </div> | |
| <div class="invoice-form-group"> | |
| <label>Кол-во</label> | |
| <input type="number" class="product-quantity-input" placeholder="1" min="1" value="1"> | |
| </div> | |
| <div class="invoice-form-group"> | |
| <label>Цена за ед.</label> | |
| <input type="number" class="product-price-input" placeholder="0.00"> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="invoice-item-controls"> | |
| <button class="btn btn-add-item" onclick="addItemRow()">+ Добавить товар</button> | |
| </div> | |
| <div class="invoice-calculation-summary"> | |
| <div class="invoice-summary-item"><span>Всего товаров:</span> <strong id="invoiceSummaryTotalItems">0</strong></div> | |
| <div class="invoice-summary-item"><span>Общая сумма:</span> <strong id="invoiceSummaryTotalAmount">0.00</strong></div> | |
| </div> | |
| <div class="invoice-modal-footer"> | |
| <div id="invoiceStatus" class="status-message"></div> | |
| <button class="invoice-btn-submit" onclick="submitInvoice()">Создать накладную</button> | |
| </div> | |
| </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="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> | |
| <script> | |
| const transactionModal = document.getElementById('transactionModal'); | |
| const addClientModal = document.getElementById('addClientModal'); | |
| let currentUserData = null; | |
| function searchUsers() { | |
| const searchTerm = document.getElementById('searchInput').value.toLowerCase(); | |
| const userCards = document.querySelectorAll('.user-card'); | |
| userCards.forEach(card => { | |
| const cardSearchTerm = card.getAttribute('data-search-term'); | |
| if (cardSearchTerm.includes(searchTerm)) { | |
| card.style.display = 'flex'; | |
| } else { | |
| card.style.display = 'none'; | |
| } | |
| }); | |
| } | |
| function openTransactionModal(userData) { | |
| currentUserData = userData; | |
| document.getElementById('modalUserId').value = userData.id; | |
| document.getElementById('modalUserName').textContent = `${userData.first_name || ''} ${userData.last_name || ''}`; | |
| document.getElementById('modalUserUsername').textContent = `@${userData.username || 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' ? '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 = `${sign}${parseFloat(item.amount).toFixed(2)} (долг)`; | |
| } | |
| li.innerHTML = ` | |
| <div> | |
| <div class="desc">${item.description}</div> | |
| <div class="date">${item.date_str}</div> | |
| </div> | |
| <div class="amount ${amountClass}">${amountText}</div> | |
| `; | |
| historyList.appendChild(li); | |
| }); | |
| } else { | |
| historyList.innerHTML = '<li style="text-align:center; padding: 1rem; color: var(--admin-secondary);">Нет истории</li>'; | |
| } | |
| updateCalculations(); | |
| transactionModal.style.display = 'block'; | |
| } | |
| function openAddClientModal() { | |
| document.getElementById('newClientFirstName').value = ''; | |
| document.getElementById('newClientPhone').value = ''; | |
| document.getElementById('addClientStatus').textContent = ''; | |
| addClientModal.style.display = 'block'; | |
| } | |
| function closeModal(modalId) { | |
| document.getElementById(modalId).style.display = 'none'; | |
| if (modalId === 'transactionModal') { | |
| currentUserData = null; | |
| } | |
| } | |
| 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 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 saveCompanyInfo() { | |
| const statusEl = document.getElementById('companyInfoStatus'); | |
| statusEl.style.color = 'var(--admin-secondary)'; | |
| statusEl.textContent = 'Сохранение...'; | |
| const companyInfo = { | |
| name: document.getElementById('companyName').value, | |
| phone1: document.getElementById('companyPhone1').value, | |
| phone2: document.getElementById('companyPhone2').value, | |
| whatsapp: document.getElementById('companyWhatsapp').value, | |
| telegram: document.getElementById('companyTelegram').value, | |
| address: document.getElementById('companyAddress').value, | |
| website: document.getElementById('companyWebsite').value, | |
| facebook: document.getElementById('companyFacebook').value, | |
| instagram: document.getElementById('companyInstagram').value, | |
| tiktok: document.getElementById('companyTiktok').value | |
| }; | |
| fetch('/admin/save_company_info', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(companyInfo) | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.status === 'ok') { | |
| statusEl.style.color = 'var(--admin-success)'; | |
| statusEl.textContent = 'Информация сохранена!'; | |
| } else { | |
| throw new Error(data.message || 'Произошла ошибка при сохранении.'); | |
| } | |
| }) | |
| .catch(error => { | |
| statusEl.style.color = 'var(--admin-danger)'; | |
| statusEl.textContent = `Ошибка: ${error.message}`; | |
| }); | |
| } | |
| let invoiceItemCount = 0; | |
| function addItemRow() { | |
| const container = document.getElementById('invoiceItemsContainer'); | |
| invoiceItemCount++; | |
| const newItemRow = document.createElement('div'); | |
| newItemRow.className = 'invoice-form-row'; | |
| newItemRow.setAttribute('data-item-id', invoiceItemCount); | |
| newItemRow.innerHTML = ` | |
| <div class="invoice-form-group"> | |
| <label>Клиент (ID или Телефон)</label> | |
| <input type="text" class="client-lookup-input" placeholder="Введите ID или телефон клиента" oninput="lookupClient(this)"> | |
| <div class="client-lookup-results" style="position: absolute; background: white; border: 1px solid #ccc; max-height: 150px; overflow-y: auto; z-index: 1002; width: calc(100% - 2px); display: none;"></div> | |
| <input type="hidden" class="client-id-input" value=""> | |
| </div> | |
| <div class="invoice-form-group"> | |
| <label>Товар</label> | |
| <input type="text" class="product-name-input" placeholder="Название товара"> | |
| </div> | |
| <div class="invoice-form-group"> | |
| <label>Кол-во</label> | |
| <input type="number" class="product-quantity-input" placeholder="1" min="1" value="1" oninput="updateInvoiceTotals()"> | |
| </div> | |
| <div class="invoice-form-group"> | |
| <label>Цена за ед.</label> | |
| <input type="number" class="product-price-input" placeholder="0.00" oninput="updateInvoiceTotals()"> | |
| </div> | |
| <div class="invoice-form-group"> | |
| <label>Сумма</label> | |
| <input type="text" class="invoice-item-total" placeholder="0.00" readonly> | |
| </div> | |
| <div class="invoice-item-controls"> | |
| <button class="btn-remove-item" onclick="removeItemRow(this)">Удалить</button> | |
| </div> | |
| `; | |
| container.appendChild(newItemRow); | |
| } | |
| function removeItemRow(button) { | |
| const row = button.closest('.invoice-form-row'); | |
| row.remove(); | |
| updateInvoiceTotals(); | |
| } | |
| function lookupClient(inputElement) { | |
| const searchTerm = inputElement.value.trim(); | |
| const resultsContainer = inputElement.nextElementSibling; | |
| const clientIdInput = inputElement.nextElementSibling.nextElementSibling; | |
| resultsContainer.innerHTML = ''; | |
| resultsContainer.style.display = 'none'; | |
| clientIdInput.value = ''; | |
| inputElement.style.borderColor = var(--admin-border); | |
| if (searchTerm.length < 2) { | |
| return; | |
| } | |
| fetch(`/admin/lookup_client?q=${encodeURIComponent(searchTerm)}`) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.users && data.users.length > 0) { | |
| data.users.forEach(user => { | |
| const div = document.createElement('div'); | |
| div.style.padding = '8px'; | |
| div.style.cursor = 'pointer'; | |
| div.style.borderBottom = '1px solid #eee'; | |
| div.textContent = `${user.first_name || user.username || ''} (${user.id})`; | |
| div.onclick = () => { | |
| inputElement.value = user.first_name || user.username || ''; | |
| clientIdInput.value = user.id; | |
| resultsContainer.style.display = 'none'; | |
| inputElement.style.borderColor = 'var(--admin-success)'; | |
| }; | |
| resultsContainer.appendChild(div); | |
| }); | |
| resultsContainer.style.display = 'block'; | |
| } | |
| }) | |
| .catch(error => console.error('Error looking up client:', error)); | |
| } | |
| function updateInvoiceTotals() { | |
| let totalItems = 0; | |
| let totalAmount = 0; | |
| const itemRows = document.querySelectorAll('#invoiceItemsContainer .invoice-form-row'); | |
| itemRows.forEach(row => { | |
| const quantityInput = row.querySelector('.product-quantity-input'); | |
| const priceInput = row.querySelector('.product-price-input'); | |
| const totalInput = row.querySelector('.invoice-item-total'); | |
| const quantity = parseFloat(quantityInput.value) || 0; | |
| const price = parseFloat(priceInput.value) || 0; | |
| const itemTotal = quantity * price; | |
| totalInput.value = itemTotal.toFixed(2); | |
| totalItems += quantity; | |
| totalAmount += itemTotal; | |
| }); | |
| document.getElementById('invoiceSummaryTotalItems').textContent = totalItems; | |
| document.getElementById('invoiceSummaryTotalAmount').textContent = totalAmount.toFixed(2); | |
| } | |
| function submitInvoice() { | |
| const statusEl = document.getElementById('invoiceStatus'); | |
| statusEl.style.color = 'var(--admin-secondary)'; | |
| statusEl.textContent = 'Обработка...'; | |
| const invoiceItems = []; | |
| const itemRows = document.querySelectorAll('#invoiceItemsContainer .invoice-form-row'); | |
| let validInvoice = true; | |
| itemRows.forEach(row => { | |
| const clientIdInput = row.querySelector('.client-id-input'); | |
| const productNameInput = row.querySelector('.product-name-input'); | |
| const quantityInput = row.querySelector('.product-quantity-input'); | |
| const priceInput = row.querySelector('.product-price-input'); | |
| const clientId = clientIdInput.value; | |
| const productName = productNameInput.value.trim(); | |
| const quantity = parseFloat(quantityInput.value); | |
| const unitPrice = parseFloat(priceInput.value); | |
| if (!clientId) { | |
| productNameInput.style.borderColor = 'var(--admin-danger)'; | |
| statusEl.style.color = 'var(--admin-danger)'; | |
| statusEl.textContent = 'Укажите клиента для каждой позиции.'; | |
| validInvoice = false; | |
| return; | |
| } | |
| if (!productName || !quantity || !unitPrice || quantity <= 0 || unitPrice < 0) { | |
| productNameInput.style.borderColor = 'var(--admin-danger)'; | |
| quantityInput.style.borderColor = 'var(--admin-danger)'; | |
| priceInput.style.borderColor = 'var(--admin-danger)'; | |
| statusEl.style.color = 'var(--admin-danger)'; | |
| statusEl.textContent = 'Заполните все поля товара корректно.'; | |
| validInvoice = false; | |
| return; | |
| } | |
| invoiceItems.push({ | |
| client_id: clientId, | |
| product_name: productName, | |
| quantity: quantity, | |
| unit_price: unitPrice | |
| }); | |
| }); | |
| if (!validInvoice) return; | |
| if (invoiceItems.length === 0) { | |
| statusEl.style.color = 'var(--admin-danger)'; | |
| statusEl.textContent = 'Добавьте хотя бы один товар.'; | |
| return; | |
| } | |
| const payload = { items: invoiceItems }; | |
| fetch('/admin/create_invoice', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(payload) | |
| }) | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.status === 'ok') { | |
| statusEl.style.color = 'var(--admin-success)'; | |
| statusEl.textContent = 'Накладная успешно создана!'; | |
| setTimeout(() => { location.reload(); }, 1500); | |
| } else { | |
| throw new Error(data.message || 'Произошла ошибка при создании накладной.'); | |
| } | |
| }) | |
| .catch(error => { | |
| statusEl.style.color = 'var(--admin-danger)'; | |
| statusEl.textContent = `Ошибка: ${error.message}`; | |
| }); | |
| } | |
| window.onclick = function(event) { | |
| if (event.target == transactionModal) { | |
| closeModal('transactionModal'); | |
| } | |
| if (event.target == addClientModal) { | |
| closeModal('addClientModal'); | |
| } | |
| if (event.target.classList.contains('client-lookup-results')) { | |
| event.stopPropagation(); | |
| } | |
| } | |
| </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": [] | |
| } | |
| return render_template_string(TEMPLATE, user=user_data, user_id=user_id_str) | |
| def view_company_info(): | |
| user_id_str = request.args.get('user_id_for_test') | |
| current_data = load_visitor_data() | |
| company_info = current_data.get('company_info', {}) | |
| user_data_for_template = {} | |
| if user_id_str and user_id_str in current_data: | |
| user_data_for_template = {"id": user_id_str} | |
| else: | |
| user_data_for_template = {"id": None} | |
| return render_template_string(COMPANY_INFO_TEMPLATE, company_info=company_info, user_id=user_id_str) | |
| def view_invoice(user_id): | |
| current_data = load_visitor_data() | |
| user_data = current_data.get(user_id, {}) | |
| invoices = user_data.get('invoices', []) | |
| for invoice in invoices: | |
| invoice_date = invoice.get('date') | |
| if invoice_date: | |
| try: | |
| dt_object = datetime.fromisoformat(invoice_date) | |
| invoice['created_at_str'] = dt_object.strftime('%Y-%m-%d %H:%M:%S') | |
| except ValueError: | |
| invoice['created_at_str'] = invoice_date | |
| items = invoice.get('items', []) | |
| for item in items: | |
| item_price = item.get('unit_price', 0) | |
| item_quantity = item.get('quantity', 0) | |
| item['total_price'] = item_price * item_quantity | |
| total_invoice_amount = sum(item['total_price'] for item in items) | |
| invoice['total_amount'] = total_invoice_amount | |
| return render_template_string(INVOICE_LIST_TEMPLATE, invoices=invoices, user_id=user_id) | |
| 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_bishkek_time() | |
| 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(): | |
| if user_id == 'company_info': 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) | |
| company_info = current_data.get('company_info', {}) | |
| 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, company_info=company_info) | |
| def save_company_info(): | |
| try: | |
| data = request.get_json() | |
| company_info = { | |
| 'name': data.get('name'), | |
| 'phone1': data.get('phone1'), | |
| 'phone2': data.get('phone2'), | |
| 'whatsapp': data.get('whatsapp'), | |
| 'telegram': data.get('telegram'), | |
| 'address': data.get('address'), | |
| 'website': data.get('website'), | |
| 'facebook': data.get('facebook'), | |
| 'instagram': data.get('instagram'), | |
| 'tiktok': data.get('tiktok') | |
| } | |
| all_data = load_visitor_data() | |
| all_data['company_info'] = company_info | |
| save_visitor_data({}) | |
| return jsonify({"status": "ok", "message": "Company info saved successfully"}), 200 | |
| except Exception as e: | |
| logging.exception("Error in /admin/save_company_info endpoint") | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| def lookup_client(): | |
| query = request.args.get('q', '').strip() | |
| if not query: | |
| return jsonify({"users": []}) | |
| all_data = load_visitor_data() | |
| results = [] | |
| for user_id, user_data in all_data.items(): | |
| if user_id == 'company_info': continue | |
| match = False | |
| if query.lower() in str(user_id).lower(): match = True | |
| if user_data.get('first_name') and query.lower() in user_data['first_name'].lower(): match = True | |
| if user_data.get('last_name') and query.lower() in user_data['last_name'].lower(): match = True | |
| if user_data.get('username') and query.lower() in user_data['username'].lower(): match = True | |
| if user_data.get('phone_number') and query in user_data['phone_number']: match = True | |
| if match: | |
| results.append({ | |
| "id": user_id, | |
| "first_name": user_data.get('first_name'), | |
| "last_name": user_data.get('last_name'), | |
| "username": user_data.get('username'), | |
| "phone_number": user_data.get('phone_number') | |
| }) | |
| if len(results) >= 5: break | |
| return jsonify({"users": results}) | |
| def create_invoice(): | |
| try: | |
| data = request.get_json() | |
| items_data = data.get('items', []) | |
| if not items_data: | |
| return jsonify({"status": "error", "message": "Накладная не может быть пустой."}), 400 | |
| all_data = load_visitor_data() | |
| invoice_id_counter = all_data.get('invoice_id_counter', 0) | |
| new_invoice_id = invoice_id_counter + 1 | |
| processed_items = [] | |
| total_amount = 0 | |
| now = get_bishkek_time() | |
| now_iso = now.isoformat() | |
| now_str = now.strftime('%Y-%m-%d %H:%M:%S') | |
| for item_data in items_data: | |
| client_id = item_data.get('client_id') | |
| product_name = item_data.get('product_name') | |
| quantity = float(item_data.get('quantity', 0)) | |
| unit_price = float(item_data.get('unit_price', 0)) | |
| if not client_id or not product_name or quantity <= 0 or unit_price < 0: | |
| return jsonify({"status": "error", "message": f"Некорректные данные для товара: {product_name or 'Неизвестно'}"}), 400 | |
| if client_id not in all_data or client_id == 'company_info': | |
| return jsonify({"status": "error", "message": f"Клиент с ID '{client_id}' не найден."}), 404 | |
| item_total_price = quantity * unit_price | |
| processed_items.append({ | |
| "product_name": product_name, | |
| "quantity": quantity, | |
| "unit_price": unit_price, | |
| "total_price": item_total_price | |
| }) | |
| total_amount += item_total_price | |
| new_invoice = { | |
| "id": str(new_invoice_id), | |
| "date": now_iso, | |
| "items": processed_items, | |
| "total_amount": total_amount | |
| } | |
| client_invoices = all_data[client_id].setdefault('invoices', []) | |
| client_invoices.append(new_invoice) | |
| all_data['invoice_id_counter'] = new_invoice_id | |
| save_visitor_data({}) | |
| return jsonify({"status": "ok", "message": "Накладная успешно создана.", "invoice_id": new_invoice_id}), 201 | |
| except Exception as e: | |
| logging.exception("Error in /admin/create_invoice endpoint") | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| 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_id == 'company_info': continue | |
| if user.get('phone_number') == phone_number: | |
| return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409 | |
| now = get_bishkek_time() | |
| 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 or user_id_str == 'company_info': | |
| return jsonify({"status": "error", "message": "User not found"}), 404 | |
| user = all_data[user_id_str] | |
| now = get_bishkek_time() | |
| 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": "Списание бонусов", | |
| "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": "Добавление долга", | |
| "date": now_iso, "date_str": now_str | |
| }) | |
| if repay_debt_amount > 0: | |
| user['debt_history'].append({ | |
| "type": "payment", "amount": repay_debt_amount, | |
| "description": "Погашение долга", | |
| "date": now_iso, "date_str": now_str | |
| }) | |
| save_visitor_data({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 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 or user_id_str == 'company_info': | |
| 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) |