diff --git "a/Soola.txt" "b/Soola.txt" new file mode 100644--- /dev/null +++ "b/Soola.txt" @@ -0,0 +1,2721 @@ + +import os +from flask import Flask, request, Response, render_template_string, jsonify, redirect, url_for +import hmac +import hashlib +import json +from urllib.parse import unquote, parse_qs, quote +import time +from datetime import datetime +import logging +import threading +import random +import pytz +import uuid + +from huggingface_hub import HfApi, hf_hub_download +from huggingface_hub.utils import RepositoryNotFoundError + +BOT_TOKEN = os.getenv("BOT_TOKEN", "7835463659:AAGNePbelZIAOeaglyQi1qulOqnjs4BGQn4") +HOST = '0.0.0.0' +PORT = 7860 +DATA_FILE = 'data.json' + +REPO_ID = "flpolprojects/examplebonus" +HF_DATA_FILE_PATH = "data.json" +HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") +HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") + +BISHKEK_TZ = pytz.timezone('Asia/Bishkek') + +app = Flask(__name__) +logging.basicConfig(level=logging.INFO) +app.secret_key = os.urandom(24) + +_data_lock = threading.Lock() +visitor_data_cache = {} +pending_star_invoices = {} + + +def generate_unique_id(all_data): + while True: + new_id = str(random.randint(10000, 99999)) + is_duplicate = False + for user_id, user_data in all_data.items(): + if user_id == "organization_details": continue + if user_id == new_id or user_data.get('partner_code') == new_id: + is_duplicate = True + break + if not is_duplicate: + return new_id + +def download_data_from_hf(): + global visitor_data_cache + if not HF_TOKEN_READ: + logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.") + return False + try: + logging.info(f"Attempting to download {HF_DATA_FILE_PATH} from {REPO_ID}...") + hf_hub_download( + repo_id=REPO_ID, + filename=HF_DATA_FILE_PATH, + repo_type="dataset", + token=HF_TOKEN_READ, + local_dir=".", + local_dir_use_symlinks=False, + force_download=True, + etag_timeout=10 + ) + logging.info("Data file successfully downloaded from Hugging Face.") + with _data_lock: + try: + with open(DATA_FILE, 'r', encoding='utf-8') as f: + visitor_data_cache = json.load(f) + logging.info("Successfully loaded downloaded data into cache.") + except (FileNotFoundError, json.JSONDecodeError) as e: + logging.error(f"Error reading downloaded data file: {e}. Starting with empty cache.") + visitor_data_cache = {} + + if "organization_details" not in visitor_data_cache: + visitor_data_cache["organization_details"] = {} + if 'referral_percentage' not in visitor_data_cache["organization_details"]: + visitor_data_cache["organization_details"]['referral_percentage'] = 2.0 + + users_to_update = {} + for user_id, user_data in visitor_data_cache.items(): + if user_id == "organization_details": continue + updated_user_data = user_data.copy() + + if 'partner_code' not in updated_user_data or not updated_user_data['partner_code']: + updated_user_data['partner_code'] = generate_unique_id(visitor_data_cache) + if 'referred_by' not in updated_user_data: + updated_user_data['referred_by'] = None + if 'referred_users' not in updated_user_data or not isinstance(updated_user_data['referred_users'], list): + updated_user_data['referred_users'] = [] + if 'invoices' not in updated_user_data or not isinstance(updated_user_data['invoices'], list): + updated_user_data['invoices'] = [] + if 'bonus_coins' not in updated_user_data: + updated_user_data['bonus_coins'] = 0 + if 'bonus_coin_history' not in updated_user_data or not isinstance(updated_user_data.get('bonus_coin_history'), list): + updated_user_data['bonus_coin_history'] = [] + + if updated_user_data != user_data: + users_to_update[user_id] = updated_user_data + + for user_id, user_data in users_to_update.items(): + visitor_data_cache[user_id] = user_data + logging.info(f"Migrated user data for ID {user_id}") + + if users_to_update: + temp_referred_users = {} + for user_id, user_data in visitor_data_cache.items(): + if user_id == "organization_details": continue + user_data['referred_users'] = [] + referred_by_code = user_data.get('referred_by') + if referred_by_code: + temp_referred_users.setdefault(referred_by_code, []).append(user_id) + + for referrer_code, referred_ids in temp_referred_users.items(): + found_referrer = False + for user_id, user_data in visitor_data_cache.items(): + if user_id == "organization_details": continue + if user_data.get('partner_code') == referrer_code: + user_data['referred_users'] = referred_ids + found_referrer = True + break + if not found_referrer: + logging.warning(f"Referrer with code {referrer_code} not found for referred users {referred_ids}. Clearing referred_by.") + for referred_id in referred_ids: + if referred_id in visitor_data_cache and referred_id != "organization_details": + visitor_data_cache[referred_id]['referred_by'] = None + + logging.info("Rebuilt referred_users lists.") + save_visitor_data(visitor_data_cache) + + return True + except RepositoryNotFoundError: + logging.error(f"Hugging Face repository '{REPO_ID}' not found. Cannot download data.") + except Exception as e: + logging.error(f"Error downloading data from Hugging Face: {e}") + return False + +def load_visitor_data(): + global visitor_data_cache + with _data_lock: + if not visitor_data_cache: + try: + with open(DATA_FILE, 'r', encoding='utf-8') as f: + visitor_data_cache = json.load(f) + logging.info("Visitor data loaded from local JSON.") + except FileNotFoundError: + logging.warning(f"{DATA_FILE} not found locally. Starting with empty data.") + visitor_data_cache = {"organization_details": {}} + except json.JSONDecodeError: + logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.") + visitor_data_cache = {"organization_details": {}} + except Exception as e: + logging.error(f"Unexpected error loading visitor data: {e}") + visitor_data_cache = {"organization_details": {}} + + if "organization_details" not in visitor_data_cache: + visitor_data_cache["organization_details"] = {} + if 'referral_percentage' not in visitor_data_cache["organization_details"]: + visitor_data_cache["organization_details"]['referral_percentage'] = 2.0 + + users_to_update = {} + for user_id, user_data in visitor_data_cache.items(): + if user_id == "organization_details": continue + updated_user_data = user_data.copy() + + if 'partner_code' not in updated_user_data or not updated_user_data['partner_code']: + updated_user_data['partner_code'] = updated_user_data.get('partner_code') + if 'referred_by' not in updated_user_data: + updated_user_data['referred_by'] = None + if 'referred_users' not in updated_user_data or not isinstance(updated_user_data['referred_users'], list): + updated_user_data['referred_users'] = [] + if 'invoices' not in updated_user_data or not isinstance(updated_user_data['invoices'], list): + updated_user_data['invoices'] = [] + if 'debt_history' not in updated_user_data or not isinstance(updated_user_data['debt_history'], list): + updated_user_data['debt_history'] = [] + if 'history' not in updated_user_data or not isinstance(updated_user_data['history'], list): + updated_user_data['history'] = [] + if 'bonus_coins' not in updated_user_data: + updated_user_data['bonus_coins'] = 0 + if 'bonus_coin_history' not in updated_user_data or not isinstance(updated_user_data.get('bonus_coin_history'), list): + updated_user_data['bonus_coin_history'] = [] + + + if updated_user_data != user_data: + users_to_update[user_id] = updated_user_data + + if users_to_update: + logging.warning(f"Missing keys in {len(users_to_update)} user entries. Updating cache but not saving automatically.") + for user_id, updated_data in users_to_update.items(): + visitor_data_cache[user_id] = updated_data + + temp_referred_users = {} + for user_id, user_data in visitor_data_cache.items(): + if user_id == "organization_details": continue + user_data['referred_users'] = [] + referred_by_code = user_data.get('referred_by') + if referred_by_code: + temp_referred_users.setdefault(referred_by_code, []).append(user_id) + + for referrer_code, referred_ids in temp_referred_users.items(): + found_referrer = False + for user_id, user_data in visitor_data_cache.items(): + if user_id == "organization_details": continue + if user_data.get('partner_code') == referrer_code: + user_data['referred_users'] = referred_ids + found_referrer = True + break + if not found_referrer: + logging.warning(f"Referrer with code {referrer_code} not found during referred_users rebuild.") + + return visitor_data_cache + +def save_visitor_data(data_to_save): + with _data_lock: + try: + with open(DATA_FILE, 'w', encoding='utf-8') as f: + json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4) + 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 {datetime.now(BISHKEK_TZ).strftime('%Y-%m-%d %H:%M:%S')}" + ) + logging.info("Bonus data successfully uploaded to Hugging Face.") + except Exception as e: + logging.error(f"Error uploading data to Hugging Face: {e}") + +def upload_data_to_hf_async(): + upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True) + upload_thread.start() + +def periodic_backup(): + if not HF_TOKEN_WRITE: + logging.info("Periodic backup disabled: HF_TOKEN_WRITE not set.") + return + while True: + time.sleep(3600) + logging.info("Initiating periodic backup...") + upload_data_to_hf() + +def verify_telegram_data(init_data_str): + try: + parsed_data = parse_qs(init_data_str) + received_hash = parsed_data.pop('hash', [None])[0] + + if not received_hash: + return None, False + + data_check_list = [] + for key, value in sorted(parsed_data.items()): + data_check_list.append(f"{key}={value[0]}") + data_check_string = "\n".join(data_check_list) + + secret_key = hmac.new("WebAppData".encode(), BOT_TOKEN.encode(), hashlib.sha256).digest() + calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() + + if calculated_hash == received_hash: + auth_date = int(parsed_data.get('auth_date', [0])[0]) + current_time = int(time.time()) + if current_time - auth_date > 86400: + logging.warning(f"Telegram InitData is older than 24 hours (Auth Date: {auth_date}, Current: {current_time}).") + return parsed_data, True + else: + logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}") + return parsed_data, False + except Exception as e: + logging.error(f"Error verifying Telegram data: {e}") + return None, False + +TEMPLATE = """ + + + + + + Bonus + + + + + + + +
+
+ +

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

+
+ + + +
+
+
+

Ваши бонусы

+

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

+
+
+

Ваш долг

+

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

+
+
+ +
+

Ваши BonusCoin

+
+

{{ "%.0f"|format(user.bonus_coins|float) }} ⭐

+ +
+

Используйте Telegram Stars для покупки BonusCoin (1 Star = 1 BonusCoin).

+
+ +
+

Ваш ID клиента

+

{{ user.id }}

+
+ +
+

Ваш партнерский код

+
+ {{ user.partner_code | default('Нет кода') }} + {% if user.partner_code %} + + {% endif %} +
+
+ +
+

Вас пригласил

+

{{ user.referred_by | default('Никто') }}

+
+ + {% if not user.referred_by %} +
+

Активировать партнерский код

+
+ + +
+

+
+ {% endif %} + +
+

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

+ {% if user.combined_history %} +
    + {% for item in user.combined_history %} +
  • +
    + {{ item.description }} + {{ item.date_str }} +
    + {% if item.transaction_type == 'bonus' %} + + {{ '+' if item.type in ['accrual', 'referral'] else '-' }}{{ "%.2f"|format(item.amount|float) }} + + {% elif item.transaction_type == 'debt' %} + + {{ '+' 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 %} +
+
Название организации
+
{{ org_details.name | default('Не указано') }}
+
+
+
Номера телефонов
+ {% if org_details.phone_numbers %} + + {% else %} +
Не указано
+ {% endif %} +
+
+
Адрес
+
{{ org_details.address | default('Не указано') }}
+
+
+
WhatsApp
+
+ {% if org_details.whatsapp_link %} + + + {{ org_details.whatsapp_link }} + + {% else %} +
Не указано
+ {% endif %} +
+
+
+
Telegram
+
+ {% if org_details.telegram_link %} + + + {{ org_details.telegram_link }} + + {% else %} +
Не указано
+ {% endif %} +
+
+ {% else %} +

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

+ {% endif %} +
+
+
+ + + + + + +""" + +ADMIN_TEMPLATE = """ + + + + + + Bonus Admin + + + + + + +
+

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

+
+
+
{{ summary.total_users }}
+
Всего клиентов
+
+
+
{{ "%.2f"|format(summary.total_bonuses|float) }}
+
Всего бонусов
+
+
+
{{ "%.2f"|format(summary.total_debts|float) }}
+
Всего долгов
+
+
+
{{ summary.users_with_debt }}
+
Клиенты с долгом
+
+
+ +
+ + + +
+ + {% if users %} +
+ {% for user in users|sort(attribute='visited_at', reverse=true) %} +
+ +
+
+
Бонусы
+
{{ "%.2f"|format(user.bonuses|float) }}
+
+
+
Долг
+
{{ "%.2f"|format(user.debts|float if user.debts else 0) }}
+
+
+
BonusCoin
+
{{ "%.0f"|format(user.bonus_coins|float) }} ⭐
+
+
+ +
+ {% endfor %} +
+ {% else %} +

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

+ {% endif %} +
+ + + + + + + + + + + + +""" + +@app.route('/') +def index(): + user_id_str = request.args.get('user_id_for_test') + all_data = load_visitor_data() + user_data = {} + + if user_id_str and user_id_str in all_data and user_id_str != "organization_details": + user_data = all_data[user_id_str] + user_data['id'] = user_id_str + + bonus_history = user_data.get('history', []) + for item in bonus_history: + item['transaction_type'] = 'bonus' + debt_history = user_data.get('debt_history', []) + for item in debt_history: + item['transaction_type'] = 'debt' + + combined_history = sorted(bonus_history + debt_history, key=lambda x: x['date'], reverse=True) + user_data['combined_history'] = combined_history + user_data['invoices'] = user_data.get('invoices', []) + user_data['partner_code'] = user_data.get('partner_code') + user_data['referred_by'] = user_data.get('referred_by') + user_data['bonus_coins'] = user_data.get('bonus_coins', 0) + else: + user_data = { + "id": "N/A", "first_name": "Гость", "bonuses": 0, "debts": 0, + "history": [], "debt_history": [], "combined_history": [], + "invoices": [], "partner_code": None, "referred_by": None, + "bonus_coins": 0 + } + + org_details = all_data.get('organization_details', {}) + return render_template_string(TEMPLATE, user=user_data, org_details=org_details) + +@app.route('/verify', methods=['POST']) +def verify_data(): + try: + req_data = request.get_json() + init_data_str = req_data.get('initData') + if not init_data_str: + return jsonify({"status": "error", "message": "Missing initData"}), 400 + + user_data_parsed, is_valid = verify_telegram_data(init_data_str) + user_info_dict = {} + if user_data_parsed and 'user' in user_data_parsed: + try: + user_json_str = unquote(user_data_parsed['user'][0]) + user_info_dict = json.loads(user_json_str) + except Exception as e: + logging.error(f"Could not parse user JSON from initData: {e}") + user_info_dict = {} + + if is_valid: + tg_user_id = user_info_dict.get('id') + if tg_user_id: + now = datetime.now(BISHKEK_TZ) + all_data = load_visitor_data() + existing_user_key = None + for key, user_data_item in all_data.items(): + if key == "organization_details": continue + if str(user_data_item.get('telegram_id')) == str(tg_user_id): + existing_user_key = key + break + user_id_to_save = existing_user_key + + if existing_user_key: + user_entry = all_data[existing_user_key] + user_entry.update({ + 'first_name': user_info_dict.get('first_name', user_entry.get('first_name')), + 'last_name': user_info_dict.get('last_name', user_entry.get('last_name')), + 'username': user_info_dict.get('username', user_entry.get('username')), + 'photo_url': user_info_dict.get('photo_url', user_entry.get('photo_url')), + 'language_code': user_info_dict.get('language_code', user_entry.get('language_code')), + 'is_premium': user_info_dict.get('is_premium', user_entry.get('is_premium', False)), + 'visited_at': now.timestamp(), + 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S') + }) + if 'partner_code' not in user_entry or not user_entry['partner_code']: + user_entry['partner_code'] = generate_unique_id(all_data) + 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': [], 'partner_code': generate_unique_id(all_data), + 'referred_by': None, 'referred_users': [], + 'bonus_coins': 0, 'bonus_coin_history': [] + } + user_id_to_save = new_user_id + + all_data[user_id_to_save] = user_entry + save_visitor_data(all_data) + return jsonify({"status": "ok", "verified": True, "user_id": user_id_to_save}) + else: + return jsonify({"status": "error", "verified": True, "message": "User ID not found in parsed data"}), 400 + else: + logging.warning(f"Verification failed. InitData: {init_data_str}") + return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403 + except Exception as e: + logging.exception("Error in /verify endpoint") + return jsonify({"status": "error", "message": "Internal server error"}), 500 + +@app.route('/create_star_invoice', methods=['POST']) +def create_star_invoice(): + try: + data = request.get_json() + user_id = data.get('user_id') + stars_to_spend = int(data.get('stars_amount', 0)) + + if not user_id or stars_to_spend <= 0: + return jsonify({"status": "error", "message": "Некорректный запрос. Укажите user_id и положительное количество звезд."}), 400 + + invoice_id = f"bonuscoin_{user_id}_{int(time.time())}_{uuid.uuid4().hex[:6]}" + + pending_star_invoices[invoice_id] = { + "user_id": user_id, + "amount": stars_to_spend, + "created_at": time.time() + } + + return jsonify({"status": "ok", "invoice_id": invoice_id}) + except Exception as e: + logging.exception("Error creating star invoice") + return jsonify({"status": "error", "message": "Внутренняя ошибка сервера при создании счета."}), 500 + +@app.route('/confirm_star_payment', methods=['POST']) +def confirm_star_payment(): + try: + data = request.get_json() + invoice_id = data.get('invoice_id') + user_id = data.get('user_id') + + if not invoice_id or not user_id: + return jsonify({"status": "error", "message": "Некорректный запрос."}), 400 + + pending_invoice = pending_star_invoices.pop(invoice_id, None) + + if not pending_invoice: + return jsonify({"status": "error", "message": "Счет не найден или уже был обработан."}), 404 + + if str(pending_invoice["user_id"]) != str(user_id): + logging.error(f"User ID mismatch on invoice confirmation. Expected {pending_invoice['user_id']}, got {user_id}") + return jsonify({"status": "error", "message": "Ошибка безопасности: ID пользователя не совпадает."}), 403 + + amount_to_credit = pending_invoice["amount"] + + all_data = load_visitor_data() + user = all_data.get(user_id) + + if not user: + return jsonify({"status": "error", "message": "Пользователь не найден."}), 404 + + now = datetime.now(BISHKEK_TZ) + now_iso = now.isoformat() + now_str = now.strftime('%Y-%m-%d %H:%M:%S') + + user['bonus_coins'] = user.get('bonus_coins', 0) + amount_to_credit + if 'bonus_coin_history' not in user or not isinstance(user.get('bonus_coin_history'), list): + user['bonus_coin_history'] = [] + + user['bonus_coin_history'].append({ + "type": "purchase", + "amount": amount_to_credit, + "description": f"Покупка за {amount_to_credit} Telegram Stars", + "date": now_iso, + "date_str": now_str, + "invoice_id": invoice_id + }) + + all_data[user_id] = user + save_visitor_data(all_data) + + return jsonify({"status": "ok", "message": f"Успешно зачислено {amount_to_credit} BonusCoin!"}), 200 + except Exception as e: + logging.exception("Error confirming star payment") + return jsonify({"status": "error", "message": "Внутренняя ошибка сервера при зачислении."}), 500 + +@app.route('/activate_partner_code', methods=['POST']) +def activate_partner_code(): + try: + data = request.get_json() + user_id = data.get('user_id') + partner_code_to_activate = data.get('partner_code') + + if not user_id or not partner_code_to_activate: + return jsonify({"status": "error", "message": "Необходимо указать ID пользователя и код."}), 400 + + user_id_str = str(user_id) + partner_code_to_activate = str(partner_code_to_activate).strip() + all_data = load_visitor_data() + + if user_id_str not in all_data or user_id_str == "organization_details": + return jsonify({"status": "error", "message": "Пользователь не найден."}), 404 + + activator_user = all_data[user_id_str] + if activator_user.get('referred_by'): + return jsonify({"status": "error", "message": "Вы уже активировали партнерский код ранее."}), 400 + if activator_user.get('partner_code') == partner_code_to_activate: + return jsonify({"status": "error", "message": "Нельзя активировать свой собственный код."}), 400 + + referrer_user = None + referrer_user_id = None + for uid, udata in all_data.items(): + if uid == "organization_details": continue + if udata.get('partner_code') == partner_code_to_activate: + referrer_user = udata + referrer_user_id = uid + break + + if not referrer_user: + return jsonify({"status": "error", "message": "Партнерский код не найден."}), 404 + + activator_user['referred_by'] = partner_code_to_activate + if 'referred_users' not in referrer_user or not isinstance(referrer_user['referred_users'], list): + referrer_user['referred_users'] = [] + if user_id_str not in referrer_user['referred_users']: + referrer_user['referred_users'].append(user_id_str) + + all_data[user_id_str] = activator_user + all_data[referrer_user_id] = referrer_user + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Партнерский код успешно активирован!"}), 200 + except Exception as e: + logging.exception("Error in /activate_partner_code endpoint") + return jsonify({"status": "error", "message": "Внутренняя ошибка сервера."}), 500 + +@app.route('/admin') +def admin_panel(): + all_data = load_visitor_data() + users_list = [] + for user_id, user_data in all_data.items(): + if user_id == "organization_details": + continue + user_data['id'] = user_id + users_list.append(user_data) + + total_users = len(users_list) + total_bonuses = sum(u.get('bonuses', 0) for u in users_list) + total_debts = sum(u.get('debts', 0) for u in users_list) + users_with_debt = sum(1 for u in users_list if u.get('debts', 0) > 0) + summary_stats = { + "total_users": total_users, "total_bonuses": total_bonuses, + "total_debts": total_debts, "users_with_debt": users_with_debt + } + return render_template_string(ADMIN_TEMPLATE, users=users_list, summary=summary_stats) + +@app.route('/admin/add_client', methods=['POST']) +def add_client(): + try: + data = request.get_json() + phone_number = data.get('phone_number') + first_name = data.get('first_name') + if not phone_number or not first_name: + return jsonify({"status": "error", "message": "Имя и номер телефона обязательны."}), 400 + + all_data = load_visitor_data() + for key, user in all_data.items(): + if key == "organization_details": continue + if user.get('phone_number') == phone_number or (user.get('telegram_id') is not None and user.get('phone_number') == phone_number): + return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409 + + now = datetime.now(BISHKEK_TZ) + new_id = generate_unique_id(all_data) + new_partner_code = 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': [], + 'partner_code': new_partner_code, 'referred_by': None, 'referred_users': [], + 'bonus_coins': 0, 'bonus_coin_history': [] + } + with _data_lock: + all_data[new_id] = new_client + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Client added successfully", "user_id": new_id}), 201 + except Exception as e: + logging.exception("Error in /admin/add_client endpoint") + return jsonify({"status": "error", "message": str(e)}), 500 + +@app.route('/admin/add_transaction', methods=['POST']) +def add_transaction(): + try: + data = request.get_json() + user_id = data.get('user_id') + purchase_amount = round(float(data.get('purchase_amount', 0)), 2) + deduct_amount = round(float(data.get('deduct_amount', 0)), 2) + add_debt_amount = round(float(data.get('add_debt_amount', 0)), 2) + repay_debt_amount = round(float(data.get('repay_debt_amount', 0)), 2) + if not user_id: + return jsonify({"status": "error", "message": "User ID is required"}), 400 + + user_id_str = str(user_id) + all_data = load_visitor_data() + if user_id_str not in all_data or user_id_str == "organization_details": + return jsonify({"status": "error", "message": "User not found"}), 404 + + user = all_data[user_id_str] + now = datetime.now(BISHKEK_TZ) + now_iso = now.isoformat() + now_str = now.strftime('%Y-%m-%d %H:%M:%S') + + current_bonuses = user.get('bonuses', 0) + current_debts = user.get('debts', 0) + if deduct_amount > current_bonuses: + return jsonify({"status": "error", "message": f"Недостаточно бонусов для списания (списание {deduct_amount:.2f}, доступно {current_bonuses:.2f})."}), 400 + if repay_debt_amount > current_debts: + return jsonify({"status": "error", "message": f"Сумма погашения ({repay_debt_amount:.2f}) превышает текущий долг ({current_debts:.2f})."}), 400 + + accrual_amount = round(purchase_amount * 0.02, 2) + user['bonuses'] = round(current_bonuses + accrual_amount - deduct_amount, 2) + if 'history' not in user or not isinstance(user['history'], list): + user['history'] = [] + if accrual_amount > 0: + user['history'].append({"type": "accrual", "amount": accrual_amount, "description": f"Начисление с покупки {purchase_amount:.2f}", "date": now_iso, "date_str": now_str}) + if deduct_amount > 0: + user['history'].append({"type": "deduction", "amount": deduct_amount, "description": "Списание бонусов", "date": now_iso, "date_str": now_str}) + + if accrual_amount > 0: + referred_by_code = user.get('referred_by') + if referred_by_code: + referrer_user, referrer_user_id = (None, None) + for uid, udata in all_data.items(): + if uid != "organization_details" and udata.get('partner_code') == referred_by_code: + referrer_user, referrer_user_id = udata, uid + break + if referrer_user: + org_details = all_data.get('organization_details', {}) + referral_percentage = float(org_details.get('referral_percentage', 2.0)) + if referral_percentage > 0: + referral_bonus_amount = round(accrual_amount * (referral_percentage / 100), 2) + if referral_bonus_amount > 0: + referrer_user['bonuses'] = round(referrer_user.get('bonuses', 0) + referral_bonus_amount, 2) + if 'history' not in referrer_user or not isinstance(referrer_user['history'], list): referrer_user['history'] = [] + referrer_user['history'].append({"type": "referral", "amount": referral_bonus_amount, "description": f"Бонус за приглашение клиента ID {user_id_str}", "date": now_iso, "date_str": now_str}) + logging.info(f"Referral bonus {referral_bonus_amount} added to user {referrer_user_id} from purchase by {user_id_str}") + all_data[referrer_user_id] = referrer_user + else: + logging.info(f"Referral bonus percentage is 0. Skipping referral bonus for {referrer_user_id}.") + else: + logging.warning(f"Referrer user with code {referred_by_code} not found for user {user_id_str}. Cannot add referral bonus.") + + user['debts'] = round(user.get('debts', 0) + add_debt_amount - repay_debt_amount, 2) + if 'debt_history' not in user or not isinstance(user['debt_history'], list): user['debt_history'] = [] + if add_debt_amount > 0: + user['debt_history'].append({"type": "accrual", "amount": add_debt_amount, "description": "Добавление долга", "date": now_iso, "date_str": now_str}) + if repay_debt_amount > 0: + user['debt_history'].append({"type": "payment", "amount": repay_debt_amount, "description": "Погашение долга", "date": now_iso, "date_str": now_str}) + + all_data[user_id_str] = user + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Transaction successful", "new_balance": user['bonuses'], "new_debt": user['debts']}), 200 + except Exception 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, total_amount, items = (data.get('user_id'), round(float(data.get('total_amount', 0)), 2), data.get('items', [])) + if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400 + if not items: return jsonify({"status": "error", "message": "Необходимо добавить товары в накладную."}), 400 + + user_id_str = str(user_id) + all_data = load_visitor_data() + if user_id_str not in all_data or user_id_str == "organization_details": return jsonify({"status": "error", "message": "User not found"}), 404 + + user = all_data[user_id_str] + now = datetime.now(BISHKEK_TZ) + 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] + calculated_total = round(sum(item['item_total'] for item in processed_items), 2) + new_invoice = {"invoice_id": invoice_id, "date": now.isoformat(), "date_str": now.strftime('%Y-%m-%d %H:%M:%S'), "total_amount": calculated_total, "items": processed_items} + + if 'invoices' not in user or not isinstance(user['invoices'], list): user['invoices'] = [] + user['invoices'].append(new_invoice) + all_data[user_id_str] = user + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Накладная успешно добавлена!", "invoice_id": invoice_id}), 200 + except Exception as e: + logging.exception("Error in /admin/add_invoice endpoint") + return jsonify({"status": "error", "message": str(e)}), 500 + +@app.route('/admin/delete_invoice', methods=['POST']) +def delete_invoice(): + try: + data = request.get_json() + user_id, invoice_id = (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 + + user_id_str = str(user_id) + all_data = load_visitor_data() + if user_id_str not in all_data or user_id_str == "organization_details": return jsonify({"status": "error", "message": "User not found"}), 404 + + user = all_data[user_id_str] + if 'invoices' not in user or not isinstance(user['invoices'], list): return jsonify({"status": "error", "message": "User has no invoices"}), 404 + + original_count = len(user['invoices']) + user['invoices'] = [inv for inv in user['invoices'] if str(inv.get('invoice_id')) != str(invoice_id)] + if len(user['invoices']) == original_count: return jsonify({"status": "error", "message": "Накладная не найдена для этого пользователя."}), 404 + + all_data[user_id_str] = user + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Накладная успешно удалена!"}), 200 + except Exception as e: + logging.exception("Error in /admin/delete_invoice endpoint") + return jsonify({"status": "error", "message": str(e)}), 500 + +@app.route('/admin/delete_client', methods=['POST']) +def delete_client(): + try: + data = request.get_json() + user_id = data.get('user_id') + if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400 + + user_id_str = str(user_id) + all_data = load_visitor_data() + with _data_lock: + if user_id_str not in all_data or user_id_str == "organization_details": return jsonify({"status": "error", "message": "User not found"}), 404 + user_to_delete = all_data[user_id_str] + if user_to_delete.get('telegram_id') is not None: return jsonify({"status": "error", "message": "Невозможно удалить клиента, связанного с Telegram."}), 403 + + deleted_user_partner_code = user_to_delete.get('partner_code') + for uid, udata in all_data.items(): + if uid != "organization_details" and udata.get('referred_by') == deleted_user_partner_code: + all_data[uid]['referred_by'] = None + logging.info(f"Cleared referred_by for user {uid}") + + deleted_user_was_referred_by = user_to_delete.get('referred_by') + if deleted_user_was_referred_by: + for uid, udata in all_data.items(): + if uid != "organization_details" and udata.get('partner_code') == deleted_user_was_referred_by: + if 'referred_users' in udata and user_id_str in udata['referred_users']: + udata['referred_users'].remove(user_id_str) + logging.info(f"Removed user {user_id_str} from referred_users of referrer {uid}") + break + del all_data[user_id_str] + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Клиент успешно удален!"}), 200 + except Exception as e: + logging.exception("Error in /admin/delete_client endpoint") + return jsonify({"status": "error", "message": str(e)}), 500 + +@app.route('/admin/organization_details', methods=['GET']) +def get_organization_details(): + try: + all_data = load_visitor_data() + org_details = all_data.get('organization_details', {}) + org_details['referral_percentage'] = float(org_details.get('referral_percentage', 2.0)) + if not isinstance(org_details.get('phone_numbers'), list): org_details['phone_numbers'] = [] + return jsonify(org_details), 200 + except Exception as e: + logging.exception("Error getting organization details") + return jsonify({"status": "error", "message": str(e)}), 500 + +@app.route('/admin/organization_details', methods=['POST']) +def save_organization_details(): + try: + data = request.get_json() + referral_percentage = float(data.get("referral_percentage", 2.0)) + if referral_percentage < 0: return jsonify({"status": "error", "message": "Процент партнерских бонусов не может быть отрицательным."}), 400 + phone_numbers = data.get("phone_numbers", []) + if not isinstance(phone_numbers, list): phone_numbers = [] + new_org_details = { + "name": data.get("name", "").strip(), + "phone_numbers": phone_numbers, + "address": data.get("address", "").strip(), + "whatsapp_link": data.get("whatsapp_link", "").strip(), + "telegram_link": data.get("telegram_link", "").strip(), + "referral_percentage": referral_percentage + } + all_data = load_visitor_data() + all_data['organization_details'] = new_org_details + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Настройки организации успешно сохранены!"}), 200 + except Exception as e: + logging.exception("Error saving organization details") + return jsonify({"status": "error", "message": str(e)}), 500 + +if __name__ == '__main__': + print("--- BONUS SYSTEM SERVER ---") + print(f"Server starting on http://{HOST}:{PORT}") + if not HF_TOKEN_READ or not HF_TOKEN_WRITE: + print("WARNING: Hugging Face token(s) not set. Backup/restore functionality will be limited.") + else: + print("Attempting initial data download from Hugging Face...") + download_data_from_hf() + load_visitor_data() + print("WARNING: The /admin route is NOT protected. Implement proper authentication for production.") + if HF_TOKEN_WRITE: + backup_thread = threading.Thread(target=periodic_backup, daemon=True) + backup_thread.start() + print("Periodic backup thread started (every hour).") + print("--- Server Ready ---") + app.run(host=HOST, port=PORT, debug=False)