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 = {} def generate_unique_id(all_data): while True: # Generate a 5-digit numeric ID new_id = str(random.randint(10000, 99999)) # Check if this ID exists as a client ID or a partner code 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 = {} # Ensure organization_details and initial user fields exist after loading 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 # Default 2% # Ensure all user entries have required fields (partner_code, referred_by, referred_users, invoices) # This is a migration step for existing data 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) # Generate unique 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 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: # Rebuild referred_users lists based on current referred_by fields temp_referred_users = {} for user_id, user_data in visitor_data_cache.items(): if user_id == "organization_details": continue user_data['referred_users'] = [] # Clear old list referred_by_code = user_data.get('referred_by') if referred_by_code: temp_referred_users.setdefault(referred_by_code, []).append(user_id) # Update the actual referred_users lists 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.") # Clear referred_by for these users if referrer doesn't exist 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 the potentially updated cache after migration and rebuild 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": {}} # Ensure organization_details key exists 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 # Default # Ensure all user entries have required fields on load if not already present 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() # Copy to detect changes if 'partner_code' not in updated_user_data or not updated_user_data['partner_code']: # Generating a unique code here on load might be problematic if called frequently without saving. # Better to ensure it's generated on user creation. If missing, leave as None or generate and mark for save. # Let's ensure generation only happens on creation (verify or add_client). # If it's missing on load, maybe just log a warning or assign None. Let's assign None for now. # The initial download/load function handles generation for missing codes on migration. updated_user_data['partner_code'] = updated_user_data.get('partner_code') # Keep existing or None 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 updated_user_data != user_data: users_to_update[user_id] = updated_user_data # Mark for potential update 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 # Rebuild referred_users lists on every load just to be safe temp_referred_users = {} for user_id, user_data in visitor_data_cache.items(): if user_id == "organization_details": continue user_data['referred_users'] = [] # Clear old list referred_by_code = user_data.get('referred_by') if referred_by_code: temp_referred_users.setdefault(referred_by_code, []).append(user_id) # Update the actual referred_users lists 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.") # Don't clear referred_by here, it's safer to keep the link even if referrer was deleted manually return visitor_data_cache def save_visitor_data(data_to_save): with _data_lock: try: # Ensure visitor_data_cache is the source of truth before saving # In calling code, modifications should happen directly on visitor_data_cache # This function now simply dumps the current state of visitor_data_cache 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: # Check file size *within* the lock just before reading 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) }}

Ваш 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 %}
    {% for phone in org_details.phone_numbers %}
  • {{ phone }}
  • {% endfor %}
{% 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) }}
{% 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 # Ensure 'id' key is present # Prepare combined history for display 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' # Type 'accrual' for debt means debt increased, 'payment' means debt decreased 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') # Pass partner code user_data['referred_by'] = user_data.get('referred_by') # Pass referred_by else: # Default empty user data if ID not found or not provided user_data = { "id": "N/A", "first_name": "Гость", "bonuses": 0, "debts": 0, "history": [], "debt_history": [], "combined_history": [], "invoices": [], "partner_code": None, "referred_by": None } 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() # Get current state of all 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: # Update existing user's TG info and visited time 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') }) # Ensure partner_code exists if somehow missing if 'partner_code' not in user_entry or not user_entry['partner_code']: user_entry['partner_code'] = generate_unique_id(all_data) else: # Create new user entry new_user_id = generate_unique_id(all_data) user_entry = { 'id': new_user_id, # Store the generated unique 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), # Generate partner code on creation 'referred_by': None, 'referred_users': [] } user_id_to_save = new_user_id all_data[user_id_to_save] = user_entry # Update the global cache 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('/activate_partner_code', methods=['POST']) def activate_partner_code(): try: data = request.get_json() user_id = data.get('user_id') # User activating the code partner_code_to_activate = data.get('partner_code') # Code entered by user 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 # Find the referrer user by their partner_code 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 # Perform the activation 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 # Update referrer in cache 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 # Ensure ID is in the dict for template access 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() # Load current state # Check for existing phone number or Telegram ID 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) # Generate unique client ID and partner code check new_partner_code = generate_unique_id(all_data) # Ensure unique partner code separately 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': [] } with _data_lock: all_data[new_id] = new_client # Update the global cache directly save_visitor_data(all_data) # Save the entire cache 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') # --- Validation against current balance/debt --- 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 # --- End Validation --- # --- Process Bonus Operations --- accrual_amount = round(purchase_amount * 0.02, 2) # Base 2% accrual 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 }) # --- End Bonus Operations --- # --- Process Referral Bonus (if applicable) --- if accrual_amount > 0: # Only give referral bonus if the referred user accrued bonuses referred_by_code = user.get('referred_by') if referred_by_code: referrer_user = None referrer_user_id = None for uid, udata in all_data.items(): if uid == "organization_details": continue if udata.get('partner_code') == referred_by_code: referrer_user = udata referrer_user_id = uid break if referrer_user: # Get referral percentage from organization details org_details = all_data.get('organization_details', {}) referral_percentage = float(org_details.get('referral_percentage', 2.0)) # Default 2% 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} (referred by {referred_by_code}) from purchase by {user_id_str}") # Ensure referrer user data is updated in the main all_data dict 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.") # --- End Referral Bonus --- # --- Process Debt Operations --- 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 }) # --- End Debt Operations --- all_data[user_id_str] = user # Ensure user data is updated in the main all_data dict save_visitor_data(all_data) # Save the entire cache 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 = data.get('user_id') total_amount = round(float(data.get('total_amount', 0)), 2) items = data.get('items', []) if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400 if not items: return jsonify({"status": "error", "message": "Необходимо добавить товары в накладную."}), 400 user_id_str = str(user_id) all_data = load_visitor_data() if user_id_str not in all_data or user_id_str == "organization_details": return jsonify({"status": "error", "message": "User not found"}), 404 user = all_data[user_id_str] now = datetime.now(BISHKEK_TZ) now_iso = now.isoformat() now_str = now.strftime('%Y-%m-%d %H:%M:%S') invoice_id = str(uuid.uuid4().hex[:8]).upper() processed_items = [] for item in items: p_name = item.get('product_name') qty = float(item.get('quantity', 0)) u_price = float(item.get('unit_price', 0)) i_total = round(qty * u_price, 2) processed_items.append({ "product_name": p_name, "quantity": qty, "unit_price": u_price, "item_total": i_total }) # Re-calculate total based on processed items to prevent manipulation calculated_total = round(sum(item['item_total'] for item in processed_items), 2) new_invoice = { "invoice_id": invoice_id, "date": now_iso, "date_str": now_str, "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 = data.get('user_id') invoice_id = data.get('invoice_id') if not user_id or not invoice_id: return jsonify({"status": "error", "message": "User ID and Invoice ID are required"}), 400 user_id_str = str(user_id) all_data = load_visitor_data() if user_id_str not in all_data or user_id_str == "organization_details": return jsonify({"status": "error", "message": "User not found"}), 404 user = all_data[user_id_str] if 'invoices' not in user or not isinstance(user['invoices'], list): return jsonify({"status": "error", "message": "User has no invoices"}), 404 original_invoice_count = len(user['invoices']) user['invoices'] = [inv for inv in user['invoices'] if str(inv.get('invoice_id')) != str(invoice_id)] # Ensure string comparison if len(user['invoices']) == original_invoice_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 # Handle referral links before deleting deleted_user_partner_code = user_to_delete.get('partner_code') # 1. Find users referred by the deleted user and clear their 'referred_by' users_referred_by_deleted = [uid for uid, udata in all_data.items() if uid != "organization_details" and udata.get('referred_by') == deleted_user_partner_code] for uid in users_referred_by_deleted: if uid in all_data and uid != "organization_details": all_data[uid]['referred_by'] = None logging.info(f"Cleared referred_by for user {uid} (referred by {user_id_str})") # 2. Find the user who referred the deleted user and remove this user from their 'referred_users' list 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": continue if 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 # Assuming partner codes are unique, stop after finding referrer # Now delete the user del all_data[user_id_str] try: save_visitor_data(all_data) except Exception as e: logging.error(f"Error saving data after deletion: {e}") return jsonify({"status": "error", "message": "Не удалось сохранить данные после удаления."}), 500 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', {}) # Ensure referral percentage exists and is a number org_details['referral_percentage'] = float(org_details.get('referral_percentage', 2.0)) # Ensure phone_numbers is a list 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 = [] # Ensure it's a list 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 # Save as float } 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)