import os from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for import hmac import hashlib import json from urllib.parse import unquote, parse_qs, quote import time from datetime import datetime import logging import threading import random import pytz import uuid from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.utils import RepositoryNotFoundError BOT_TOKEN = os.getenv("BOT_TOKEN", "7835463659:AAGNePbelZIAOeaglyQi1qulOqnjs4BGQn4") HOST = '0.0.0.0' PORT = 7860 DATA_FILE = 'data.json' REPO_ID = "flpolprojects/examplebonus" HF_DATA_FILE_PATH = "data.json" HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") ALMATY_TZ = pytz.timezone('Asia/Almaty') app = Flask(__name__) logging.basicConfig(level=logging.INFO) app.secret_key = os.urandom(24) _data_lock = threading.Lock() visitor_data_cache = {} def generate_unique_id(all_data): while True: new_id = str(random.randint(10000, 99999)) if new_id not in all_data: return new_id def download_data_from_hf(): global visitor_data_cache if not HF_TOKEN_READ: logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.") return False try: logging.info(f"Attempting to download {HF_DATA_FILE_PATH} from {REPO_ID}...") hf_hub_download( repo_id=REPO_ID, filename=HF_DATA_FILE_PATH, repo_type="dataset", token=HF_TOKEN_READ, local_dir=".", local_dir_use_symlinks=False, force_download=True, etag_timeout=10 ) logging.info("Data file successfully downloaded from Hugging Face.") with _data_lock: try: with open(DATA_FILE, 'r', encoding='utf-8') as f: visitor_data_cache = json.load(f) logging.info("Successfully loaded downloaded data into cache.") except (FileNotFoundError, json.JSONDecodeError) as e: logging.error(f"Error reading downloaded data file: {e}. Starting with empty cache.") visitor_data_cache = {} return True except RepositoryNotFoundError: logging.error(f"Hugging Face repository '{REPO_ID}' not found. Cannot download data.") return False except Exception as e: logging.error(f"Error downloading data from Hugging Face: {e}") return False def load_visitor_data(): global visitor_data_cache with _data_lock: if not visitor_data_cache: try: with open(DATA_FILE, 'r', encoding='utf-8') as f: visitor_data_cache = json.load(f) logging.info("Visitor data loaded from local JSON.") except FileNotFoundError: logging.warning(f"{DATA_FILE} not found locally. Starting with empty data.") visitor_data_cache = {} except json.JSONDecodeError: logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.") visitor_data_cache = {} except Exception as e: logging.error(f"Unexpected error loading visitor data: {e}") visitor_data_cache = {} if "organization_details" not in visitor_data_cache: visitor_data_cache["organization_details"] = {} if "bonus_program_settings" not in visitor_data_cache: visitor_data_cache["bonus_program_settings"] = { "invoice_bonus_percentage": 2, "referral_promo_bonus": 50, "referrer_first_purchase_percentage": 5 } def save_visitor_data(): try: with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4) logging.info(f"Visitor data successfully saved to {DATA_FILE}.") upload_data_to_hf_async() except Exception as e: logging.error(f"Error saving visitor data: {e}") def upload_data_to_hf(): if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN_WRITE not set. Skipping Hugging Face upload.") return if not os.path.exists(DATA_FILE): logging.warning(f"{DATA_FILE} does not exist. Skipping upload.") return try: api = HfApi() with _data_lock: if not os.path.getsize(DATA_FILE) > 0: logging.warning(f"{DATA_FILE} is empty. Skipping upload.") return logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}/{HF_DATA_FILE_PATH}...") api.upload_file( path_or_fileobj=DATA_FILE, path_in_repo=HF_DATA_FILE_PATH, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, commit_message=f"Update bonus data {datetime.now(ALMATY_TZ).strftime('%Y-%m-%d %H:%M:%S')}" ) logging.info("Bonus data successfully uploaded to Hugging Face.") except Exception as e: logging.error(f"Error uploading data to Hugging Face: {e}") def upload_data_to_hf_async(): upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True) upload_thread.start() def periodic_backup(): if not HF_TOKEN_WRITE: logging.info("Periodic backup disabled: HF_TOKEN_WRITE not set.") return while True: time.sleep(3600) logging.info("Initiating periodic backup...") upload_data_to_hf() def verify_telegram_data(init_data_str): try: parsed_data = parse_qs(init_data_str) received_hash = parsed_data.pop('hash', [None])[0] if not received_hash: return None, False data_check_list = [f"{key}={value[0]}" for key, value in sorted(parsed_data.items())] data_check_string = "\n".join(data_check_list) secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest() calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() if calculated_hash == received_hash: auth_date = int(parsed_data.get('auth_date', [0])[0]) if (int(time.time()) - auth_date) > 86400: logging.warning(f"Telegram InitData is older than 24 hours.") return parsed_data, True else: logging.warning(f"Data verification failed.") return parsed_data, False except Exception as e: logging.error(f"Error verifying Telegram data: {e}") return None, False TEMPLATE = """ Bonus

Добро пожаловать!

Ваши бонусы

0.00

Ваш долг

{{ "%.2f"|format(user.debts|float) }}

Бонусы с друзей

{{ "%.2f"|format(user.referral_bonuses|float) }}

Ваш промокод для друзей Передай этот промокод другу. При активации он получит {{ "%.0f"|format(bonus_settings.referral_promo_bonus|float) }} бонусов, а ты получишь {{ "%.1f"|format(bonus_settings.referrer_first_purchase_percentage|float) }}% на свой счет "от друзей" с его первой покупки.

{{ user.referral_code }}

Ваш ID клиента

{{ user.id }}

История операций

{% if user.combined_history %}
    {% for item in user.combined_history[:10] %}
  • {% if item.transaction_type == 'bonus' %}
    {{ item.description }} {{ item.date_str }}
    {{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }} {% elif item.transaction_type == 'debt' %}
    {{ item.description }} {{ item.date_str }}
    {{ '-' if item.type == 'payment' else '+' }}{{ "%.2f"|format(item.amount|float) }} {% elif item.transaction_type == 'referral' %}
    {{ item.description }} {{ item.date_str }}
    {{ '+' if item.type == 'accrual' else '-' }}{{ "%.2f"|format(item.amount|float) }} {% endif %}
  • {% endfor %}
{% else %}

Операций пока не было.

{% endif %}

Мои накладные

{% if user.invoices %}
    {% for invoice in user.invoices|sort(attribute='date', reverse=true) %}
  • Накладная #{{ invoice.invoice_id }} {{ invoice.date_str }}
    {{ "%.2f"|format(invoice.total_amount|float) }}
  • {% endfor %}
{% else %}

Накладных пока нет.

{% endif %}

Визитка организации

{% if org_details and (org_details.name or org_details.phone_numbers) %} {% if org_details.name %}
Название организации
{{ org_details.name }}
{% endif %} {% if org_details.phone_numbers %}
Номера телефонов
    {% for phone in org_details.phone_numbers %}
  • {{ phone }}
  • {% endfor %}
{% endif %} {% if org_details.address %}
Адрес
{{ org_details.address }}
{% endif %} {% if org_details.whatsapp_link %} {% endif %} {% if org_details.telegram_link %} {% endif %} {% else %}

Данные организации не указаны.

{% endif %}
{% if is_first_visit %} {% endif %} """ ADMIN_TEMPLATE = """ Bonus Admin

Панель администратора Bonus

{{ summary.total_users }}
Всего клиентов
{{ "%.2f"|format(summary.total_bonuses|float) }}
Всего бонусов
{{ "%.2f"|format(summary.total_debts|float) }}
Всего долгов
{{ "%.2f"|format(summary.total_referral_bonuses|float) }}
Бонусов с друзей
{% if users %}
{% for user in users|sort(attribute='visited_at', reverse=true) %}
{% if user.referrer_info %}
Приведен(а): {{ user.referrer_info }}
{% endif %}
Привел(а) клиентов: {{ user.referrals_count }}
Бонусы
{{ "%.2f"|format(user.bonuses|float) }}
Долг
{{ "%.2f"|format(user.debts|float if user.debts else 0) }}
От друзей
{{ "%.2f"|format(user.referral_bonuses|float if user.referral_bonuses else 0) }}
{% endfor %}
{% else %}

Пользователей пока нет.

{% endif %}
""" @app.route('/') def index(): user_id_str = request.args.get('user_id_for_test') user_data = {} is_first_visit = False with _data_lock: if user_id_str and user_id_str in visitor_data_cache: user_data = visitor_data_cache[user_id_str] user_data['id'] = user_id_str is_first_visit = not user_data.get('has_been_welcomed', False) bonus_history = user_data.get('history', []) debt_history = user_data.get('debt_history', []) referral_history = user_data.get('referral_bonus_history', []) for item in bonus_history: item['transaction_type'] = 'bonus' for item in debt_history: item['transaction_type'] = 'debt' for item in referral_history: item['transaction_type'] = 'referral' user_data['combined_history'] = sorted(bonus_history + debt_history + referral_history, key=lambda x: datetime.fromisoformat(x['date']), reverse=True) user_data['invoices'] = user_data.get('invoices', []) else: user_data = {"id": "N/A", "bonuses": 0, "debts": 0, "referral_bonuses": 0, "combined_history": [], "invoices": [], "referral_code": "N/A"} org_details = visitor_data_cache.get('organization_details', {}) bonus_settings = visitor_data_cache.get('bonus_program_settings', {}) return render_template_string(TEMPLATE, user=user_data, org_details=org_details, is_first_visit=is_first_visit, bonus_settings=bonus_settings) @app.route('/verify', methods=['POST']) def verify_data(): try: req_data = request.get_json() init_data_str = req_data.get('initData') if not init_data_str: return jsonify({"status": "error", "message": "Missing initData"}), 400 user_data_parsed, is_valid = verify_telegram_data(init_data_str) user_info_dict = {} if user_data_parsed and 'user' in user_data_parsed: try: user_info_dict = json.loads(unquote(user_data_parsed['user'][0])) except Exception as e: logging.error(f"Could not parse user JSON: {e}") if is_valid: tg_user_id = user_info_dict.get('id') if tg_user_id: now = datetime.now(ALMATY_TZ) user_id_to_save = None with _data_lock: existing_user_key = next((k for k, u in visitor_data_cache.items() if k != "organization_details" and str(u.get('telegram_id')) == str(tg_user_id)), None) if existing_user_key: user_entry = visitor_data_cache[existing_user_key] user_entry.update({ 'first_name': user_info_dict.get('first_name'), 'last_name': user_info_dict.get('last_name'), 'username': user_info_dict.get('username'), 'photo_url': user_info_dict.get('photo_url'), 'visited_at': now.timestamp(), 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S') }) user_id_to_save = existing_user_key else: new_user_id = generate_unique_id(visitor_data_cache) user_entry = { 'id': new_user_id, 'telegram_id': tg_user_id, 'first_name': user_info_dict.get('first_name'), 'last_name': user_info_dict.get('last_name'), 'username': user_info_dict.get('username'), 'photo_url': user_info_dict.get('photo_url'), 'is_premium': user_info_dict.get('is_premium', False), 'phone_number': None, 'visited_at': now.timestamp(), 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'), 'bonuses': 0, 'history': [], 'debts': 0, 'debt_history': [], 'invoices': [], 'referral_code': f'PROMO{new_user_id}', 'referred_by': None, 'referrals': [], 'has_been_welcomed': False, 'referral_bonuses': 0, 'referral_bonus_history': [], 'has_made_first_purchase': False, } visitor_data_cache[new_user_id] = user_entry user_id_to_save = new_user_id save_visitor_data() return jsonify({"status": "ok", "verified": True, "user_id": user_id_to_save}) else: return jsonify({"status": "error", "verified": True, "message": "User ID not found"}), 400 else: return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403 except Exception as e: logging.exception("Error in /verify endpoint") return jsonify({"status": "error", "message": "Internal server error"}), 500 @app.route('/submit_referral', methods=['POST']) def submit_referral(): try: data = request.get_json() user_id = str(data.get('user_id')) referral_code = data.get('referral_code') with _data_lock: if not user_id or user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "Пользователь не найден."}), 404 user = visitor_data_cache[user_id] if user.get('has_been_welcomed', False): return jsonify({"status": "ok", "message": "Вы уже прошли этот шаг."}), 200 user['has_been_welcomed'] = True bonus_settings = visitor_data_cache.get('bonus_program_settings', {}) promo_bonus = float(bonus_settings.get('referral_promo_bonus', 0)) if referral_code: referrer_id = next((u_id for u_id, u in visitor_data_cache.items() if u_id not in ["organization_details", "bonus_program_settings"] and u.get('referral_code') == referral_code), None) if not referrer_id: return jsonify({"status": "error", "message": "Промокод не найден."}), 404 if referrer_id == user_id: return jsonify({"status": "error", "message": "Нельзя использовать свой промокод."}), 400 user['referred_by'] = referrer_id referrer = visitor_data_cache[referrer_id] if 'referrals' not in referrer: referrer['referrals'] = [] referrer['referrals'].append(user_id) if promo_bonus > 0: user['bonuses'] = user.get('bonuses', 0) + promo_bonus now = datetime.now(ALMATY_TZ) history_entry = { "type": "accrual", "amount": promo_bonus, "description": "Бонус за промокод", "date": now.isoformat(), "date_str": now.strftime('%Y-%m-%d %H:%M:%S') } if 'history' not in user: user['history'] = [] user['history'].append(history_entry) save_visitor_data() message = "Промокод успешно применен!" if referral_code else "Добро пожаловать!" return jsonify({"status": "ok", "message": message}), 200 except Exception as e: logging.exception("Error in /submit_referral endpoint") return jsonify({"status": "error", "message": "Внутренняя ошибка сервера"}), 500 @app.route('/admin') def admin_panel(): users_list = [] user_name_map = {uid: f"{ud.get('first_name', '')} {ud.get('last_name', '')}".strip() or f"ID: {uid}" for uid, ud in visitor_data_cache.items() if uid not in ["organization_details", "bonus_program_settings"]} for user_id, user_data in visitor_data_cache.items(): if user_id in ["organization_details", "bonus_program_settings"]: continue user_data_copy = user_data.copy() user_data_copy['id'] = user_id user_data_copy['referrals_count'] = len(user_data_copy.get('referrals', [])) referrer_id = user_data_copy.get('referred_by') user_data_copy['referrer_info'] = user_name_map.get(referrer_id, None) users_list.append(user_data_copy) total_users = len(users_list) total_bonuses = sum(u.get('bonuses', 0) for u in users_list) total_debts = sum(u.get('debts', 0) for u in users_list) total_referral_bonuses = sum(u.get('referral_bonuses', 0) for u in users_list) summary_stats = { "total_users": total_users, "total_bonuses": total_bonuses, "total_debts": total_debts, "total_referral_bonuses": total_referral_bonuses } return render_template_string(ADMIN_TEMPLATE, users=users_list, summary=summary_stats) @app.route('/admin/add_client', methods=['POST']) def add_client(): try: data = request.get_json() phone_number = data.get('phone_number') first_name = data.get('first_name') if not phone_number or not first_name: return jsonify({"status": "error", "message": "Имя и номер телефона обязательны."}), 400 with _data_lock: if any(u.get('phone_number') == phone_number for k, u in visitor_data_cache.items() if k not in ["organization_details", "bonus_program_settings"]): return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409 now = datetime.now(ALMATY_TZ) new_id = generate_unique_id(visitor_data_cache) new_client = { 'id': new_id, 'telegram_id': None, 'first_name': first_name, 'last_name': None, 'username': None, 'photo_url': None, 'is_premium': False, 'phone_number': phone_number, 'visited_at': now.timestamp(), 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'), 'bonuses': 0, 'history': [], 'debts': 0, 'debt_history': [], 'invoices': [], 'referral_code': f'PROMO{new_id}', 'referred_by': None, 'referrals': [], 'has_been_welcomed': True, 'referral_bonuses': 0, 'referral_bonus_history': [], 'has_made_first_purchase': False, } visitor_data_cache[new_id] = new_client save_visitor_data() return jsonify({"status": "ok", "message": "Client added successfully"}), 201 except Exception as e: logging.exception("Error in /admin/add_client endpoint") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/add_transaction', methods=['POST']) def add_transaction(): try: data = request.get_json() user_id = str(data.get('user_id')) accrue_amount = float(data.get('accrue_amount', 0)) deduct_amount = float(data.get('deduct_amount', 0)) accrue_referral_amount = float(data.get('accrue_referral_amount', 0)) deduct_referral_amount = float(data.get('deduct_referral_amount', 0)) add_debt_amount = float(data.get('add_debt_amount', 0)) repay_debt_amount = float(data.get('repay_debt_amount', 0)) if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400 with _data_lock: if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404 user = visitor_data_cache[user_id] now = datetime.now(ALMATY_TZ) now_iso, now_str = now.isoformat(), now.strftime('%Y-%m-%d %H:%M:%S') if deduct_amount > user.get('bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно основных бонусов для списания"}), 400 if deduct_referral_amount > user.get('referral_bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно бонусов от друзей для списания"}), 400 if repay_debt_amount > user.get('debts', 0): return jsonify({"status": "error", "message": "Сумма погашения превышает текущий долг"}), 400 if 'history' not in user: user['history'] = [] if 'referral_bonus_history' not in user: user['referral_bonus_history'] = [] if 'debt_history' not in user: user['debt_history'] = [] user['bonuses'] = round(user.get('bonuses', 0) + accrue_amount - deduct_amount, 2) if accrue_amount > 0: user['history'].append({"type": "accrual", "amount": accrue_amount, "description": "Начисление бонусов (админ)", "date": now_iso, "date_str": now_str}) if deduct_amount > 0: user['history'].append({"type": "deduction", "amount": deduct_amount, "description": "Списание бонусов (админ)", "date": now_iso, "date_str": now_str}) user['referral_bonuses'] = round(user.get('referral_bonuses', 0) + accrue_referral_amount - deduct_referral_amount, 2) if accrue_referral_amount > 0: user['referral_bonus_history'].append({"type": "accrual", "amount": accrue_referral_amount, "description": "Начисление бонусов от друзей (админ)", "date": now_iso, "date_str": now_str}) if deduct_referral_amount > 0: user['referral_bonus_history'].append({"type": "deduction", "amount": deduct_referral_amount, "description": "Списание бонусов от друзей (админ)", "date": now_iso, "date_str": now_str}) user['debts'] = round(user.get('debts', 0) + add_debt_amount - repay_debt_amount, 2) if add_debt_amount > 0: user['debt_history'].append({"type": "accrual", "amount": add_debt_amount, "description": "Добавление долга", "date": now_iso, "date_str": now_str}) if repay_debt_amount > 0: user['debt_history'].append({"type": "payment", "amount": repay_debt_amount, "description": "Погашение долга", "date": now_iso, "date_str": now_str}) save_visitor_data() return jsonify({"status": "ok", "message": "Transaction successful"}), 200 except Exception as e: logging.exception("Error in /admin/add_transaction endpoint") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/add_invoice', methods=['POST']) def add_invoice(): try: data = request.get_json() user_id = str(data.get('user_id')) total_amount = float(data.get('total_amount', 0)) items = data.get('items', []) deduct_bonuses = float(data.get('deduct_bonuses', 0)) bonus_source = data.get('bonus_source', 'main') if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400 if not items: return jsonify({"status": "error", "message": "Необходимо добавить товары в накладную."}), 400 with _data_lock: if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404 user = visitor_data_cache[user_id] if bonus_source == 'main' and deduct_bonuses > user.get('bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно основных бонусов для списания."}), 400 if bonus_source == 'referral' and deduct_bonuses > user.get('referral_bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно бонусов от друзей для списания."}), 400 if deduct_bonuses > total_amount: return jsonify({"status": "error", "message": "Сумма списания не может превышать сумму накладной."}), 400 now = datetime.now(ALMATY_TZ) now_iso, now_str = now.isoformat(), now.strftime('%Y-%m-%d %H:%M:%S') invoice_id = str(uuid.uuid4().hex[:8]).upper() processed_items = [{"product_name": item.get('product_name'), "quantity": float(item.get('quantity', 0)), "unit_price": float(item.get('unit_price', 0)), "item_total": round(float(item.get('quantity', 0)) * float(item.get('unit_price', 0)), 2)} for item in items] new_invoice = { "invoice_id": invoice_id, "date": now_iso, "date_str": now_str, "total_amount": round(total_amount, 2), "items": processed_items, "bonuses_deducted": round(deduct_bonuses, 2), "bonus_source_used": bonus_source if deduct_bonuses > 0 else None } if 'invoices' not in user: user['invoices'] = [] user['invoices'].append(new_invoice) if deduct_bonuses > 0: if bonus_source == 'main': user['bonuses'] = round(user.get('bonuses', 0) - deduct_bonuses, 2) if 'history' not in user: user['history'] = [] user['history'].append({"type": "deduction", "amount": deduct_bonuses, "description": f"Оплата по накладной #{invoice_id}", "date": now_iso, "date_str": now_str}) elif bonus_source == 'referral': user['referral_bonuses'] = round(user.get('referral_bonuses', 0) - deduct_bonuses, 2) if 'referral_bonus_history' not in user: user['referral_bonus_history'] = [] user['referral_bonus_history'].append({"type": "deduction", "amount": deduct_bonuses, "description": f"Оплата по накладной #{invoice_id}", "date": now_iso, "date_str": now_str}) bonus_settings = visitor_data_cache.get('bonus_program_settings', {}) invoice_bonus_percentage = float(bonus_settings.get('invoice_bonus_percentage', 0)) if deduct_bonuses <= 0 and invoice_bonus_percentage > 0 and total_amount > 0: bonus_from_invoice = round((total_amount * invoice_bonus_percentage) / 100, 2) if bonus_from_invoice > 0: user['bonuses'] = user.get('bonuses', 0) + bonus_from_invoice if 'history' not in user: user['history'] = [] user['history'].append({"type": "accrual", "amount": bonus_from_invoice, "description": f"Бонус с накладной #{invoice_id}", "date": now_iso, "date_str": now_str}) if not user.get('has_made_first_purchase', False) and total_amount > 0: user['has_made_first_purchase'] = True referrer_id = user.get('referred_by') if referrer_id and referrer_id in visitor_data_cache: referrer = visitor_data_cache[referrer_id] referrer_bonus_percentage = float(bonus_settings.get('referrer_first_purchase_percentage', 0)) if referrer_bonus_percentage > 0: commission = round((total_amount * referrer_bonus_percentage) / 100, 2) if commission > 0: referrer['referral_bonuses'] = referrer.get('referral_bonuses', 0) + commission if 'referral_bonus_history' not in referrer: referrer['referral_bonus_history'] = [] referrer['referral_bonus_history'].append({ "type": "accrual", "amount": commission, "description": f"Бонус от друга {user.get('first_name', 'ID:'+user_id)}", "date": now_iso, "date_str": now_str }) save_visitor_data() return jsonify({"status": "ok", "message": "Invoice added successfully", "invoice_id": invoice_id}), 200 except Exception as e: logging.exception("Error in /admin/add_invoice endpoint") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/delete_invoice', methods=['POST']) def delete_invoice(): try: data = request.get_json() user_id, invoice_id = str(data.get('user_id')), data.get('invoice_id') if not user_id or not invoice_id: return jsonify({"status": "error", "message": "User ID and Invoice ID are required"}), 400 with _data_lock: if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404 user = visitor_data_cache[user_id] if 'invoices' not in user: return jsonify({"status": "error", "message": "User has no invoices"}), 404 original_count = len(user['invoices']) user['invoices'] = [inv for inv in user['invoices'] if inv.get('invoice_id') != invoice_id] if len(user['invoices']) == original_count: return jsonify({"status": "error", "message": "Invoice not found for this user"}), 404 save_visitor_data() return jsonify({"status": "ok", "message": "Invoice deleted successfully"}), 200 except Exception as e: logging.exception("Error in /admin/delete_invoice endpoint") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/delete_client', methods=['POST']) def delete_client(): try: user_id = str(request.get_json().get('user_id')) if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400 with _data_lock: if user_id not in visitor_data_cache: return jsonify({"status": "error", "message": "User not found"}), 404 if visitor_data_cache[user_id].get('telegram_id') is not None: return jsonify({"status": "error", "message": "Cannot delete a Telegram-linked user"}), 403 user_to_delete = visitor_data_cache[user_id] referrer_id = user_to_delete.get('referred_by') if referrer_id and referrer_id in visitor_data_cache: referrer = visitor_data_cache[referrer_id] if 'referrals' in referrer and user_id in referrer['referrals']: referrer['referrals'].remove(user_id) del visitor_data_cache[user_id] save_visitor_data() return jsonify({"status": "ok", "message": "Client deleted successfully"}), 200 except Exception as e: logging.exception("Error in /admin/delete_client endpoint") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/organization_details', methods=['GET']) def get_organization_details(): try: return jsonify(visitor_data_cache.get('organization_details', {})), 200 except Exception as e: logging.exception("Error getting organization details") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/organization_details', methods=['POST']) def save_organization_details(): try: data = request.get_json() with _data_lock: visitor_data_cache['organization_details'] = { "name": data.get("name", ""), "phone_numbers": data.get("phone_numbers", []), "address": data.get("address", ""), "whatsapp_link": data.get("whatsapp_link", ""), "telegram_link": data.get("telegram_link", "") } save_visitor_data() return jsonify({"status": "ok", "message": "Organization details saved successfully"}), 200 except Exception as e: logging.exception("Error saving organization details") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/bonus_settings', methods=['GET']) def get_bonus_settings(): try: return jsonify(visitor_data_cache.get('bonus_program_settings', {})), 200 except Exception as e: logging.exception("Error getting bonus settings") return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/admin/bonus_settings', methods=['POST']) def save_bonus_settings(): try: data = request.get_json() with _data_lock: settings = visitor_data_cache.get('bonus_program_settings', {}) settings['invoice_bonus_percentage'] = float(data.get('invoice_bonus_percentage', 0)) settings['referral_promo_bonus'] = float(data.get('referral_promo_bonus', 0)) settings['referrer_first_purchase_percentage'] = float(data.get('referrer_first_purchase_percentage', 0)) visitor_data_cache['bonus_program_settings'] = settings save_visitor_data() return jsonify({"status": "ok", "message": "Bonus program settings saved"}), 200 except Exception as e: logging.exception("Error saving bonus settings") return jsonify({"status": "error", "message": str(e)}), 500 if __name__ == '__main__': print("--- BONUS SYSTEM SERVER ---") print(f"Server starting on http://{HOST}:{PORT}") print("Attempting to load local data file...") load_visitor_data() if not visitor_data_cache or len(visitor_data_cache) <= 2: print("Local data file not found or is empty.") if HF_TOKEN_READ: print("Attempting to restore data from Hugging Face...") if not download_data_from_hf(): print("Failed to restore from Hugging Face. Starting fresh.") else: print("HF_TOKEN_READ not set. Cannot restore from backup. Starting fresh.") else: user_count = len([k for k in visitor_data_cache if k not in ['organization_details', 'bonus_program_settings']]) print(f"Successfully loaded data for {user_count} users from local file.") print("WARNING: The /admin route is NOT protected. Implement proper authentication for production.") if HF_TOKEN_WRITE: backup_thread = threading.Thread(target=periodic_backup, daemon=True) backup_thread.start() print("Periodic backup thread started (every hour).") else: print("WARNING: HF_TOKEN_WRITE not set. Periodic backups to Hugging Face are disabled.") print("--- Server Ready ---") app.run(host=HOST, port=PORT, debug=False)