diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -11,8 +11,8 @@ from datetime import datetime import logging import threading import random -import pytz # Import pytz for timezone handling -import uuid # For generating unique invoice IDs +import pytz +import uuid from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.utils import RepositoryNotFoundError @@ -27,7 +27,6 @@ HF_DATA_FILE_PATH = "data.json" HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") -# Define Bishkek timezone BISHKEK_TZ = pytz.timezone('Asia/Bishkek') app = Flask(__name__) @@ -35,11 +34,10 @@ logging.basicConfig(level=logging.INFO) app.secret_key = os.urandom(24) _data_lock = threading.Lock() -visitor_data_cache = {} # This will store all data, including organization details +visitor_data_cache = {} def generate_unique_id(all_data): while True: - # Check against both client IDs and invoice IDs new_id = str(random.randint(10000, 99999)) if new_id not in all_data: return new_id @@ -80,14 +78,14 @@ def download_data_from_hf(): def load_visitor_data(): global visitor_data_cache with _data_lock: - if not visitor_data_cache: # Only load from file if cache is empty + 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": {}} # Initialize with empty org details + visitor_data_cache = {"organization_details": {}} except json.JSONDecodeError: logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.") visitor_data_cache = {"organization_details": {}} @@ -95,7 +93,6 @@ def load_visitor_data(): 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"] = {} @@ -104,29 +101,7 @@ def load_visitor_data(): def save_visitor_data(data): with _data_lock: try: - # When `data` is a dictionary, update it directly. - # If `data` is a partial update for `visitor_data_cache`, merge it. - # For simplicity, this function now assumes `data` is the complete `visitor_data_cache` - # or a mergeable dictionary that should be applied to the cache before saving. - # Given current usage, it's typically `save_visitor_data({user_id: user_entry})` - # or `save_visitor_data({"organization_details": new_org_details})` etc. - # It should ideally update the global `visitor_data_cache` and then dump it. - - # This line needs to be careful: if `data` is a single user, it overwrites. - # It's better to update specific parts of the cache or always pass the full cache. - # Let's adjust existing call sites to pass the full `all_data` after modification. - # For now, let's assume `data` is what needs to be *merged* into `visitor_data_cache` - # or `data` IS the new `visitor_data_cache`. - - # A more robust approach for `save_visitor_data` would be: - # 1. Take a user_id and user_data to update a specific user - # 2. Take an org_details dict to update org details - # 3. Then, always dump the *entire* `visitor_data_cache`. - - # Simpler change for existing code: - # Ensure `visitor_data_cache` is directly modified by operations, - # and `save_visitor_data` just dumps the current `visitor_data_cache`. - + visitor_data_cache.update(data) with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4) logging.info(f"Visitor data successfully saved to {DATA_FILE}.") @@ -221,6 +196,7 @@ TEMPLATE = """ --brand-yellow: #FFC107; --brand-black: #101010; --brand-red: #F44336; + --brand-green: #4CAF50; --card-bg: #1c1c1e; --text-color: #ffffff; --text-secondary-color: #a0a0a0; @@ -252,23 +228,10 @@ TEMPLATE = """ flex-direction: column; gap: var(--padding-m); } - .header { - text-align: left; - padding: var(--padding-m) 0; - margin-bottom: 0; /* Adjusted for nav buttons */ - } - .logo { - font-size: 2.5em; - font-weight: 800; - color: var(--text-color); - letter-spacing: -1px; - } + .header { text-align: left; padding: var(--padding-m) 0; margin-bottom: 0; } + .logo { font-size: 2.5em; font-weight: 800; color: var(--text-color); letter-spacing: -1px; } .logo span { color: var(--brand-yellow); } - .welcome-text { - font-size: 1em; - color: var(--text-secondary-color); - margin-top: 4px; - } + .welcome-text { font-size: 1em; color: var(--text-secondary-color); margin-top: 4px; } .nav-buttons { display: flex; justify-content: space-around; @@ -278,274 +241,132 @@ TEMPLATE = """ margin-bottom: var(--padding-m); } .nav-btn { - flex-grow: 1; - padding: 10px 15px; - border: none; - border-radius: 12px; - background-color: transparent; - color: var(--text-secondary-color); - font-family: var(--font-family); - font-weight: 600; - font-size: 1em; - cursor: pointer; - transition: background-color 0.2s, color 0.2s; - } - .nav-btn.active { - background-color: var(--brand-yellow); - color: var(--brand-black); - box-shadow: 0 2px 10px rgba(255,193,7,0.3); - } - .content-section { - display: none; /* Hidden by default */ - flex-direction: column; - gap: var(--padding-m); - } - .content-section.active { - display: flex; /* Shown when active */ - } - .card-grid { - display: grid; - grid-template-columns: 1fr 1fr; - gap: var(--padding-m); - } - .bonus-card, .debt-card { + flex-grow: 1; padding: 10px 15px; border: none; border-radius: 12px; + background-color: transparent; color: var(--text-secondary-color); + font-family: var(--font-family); font-weight: 600; font-size: 1em; + cursor: pointer; transition: background-color 0.2s, color 0.2s; + } + .nav-btn.active { background-color: var(--brand-yellow); color: var(--brand-black); box-shadow: 0 2px 10px rgba(255,193,7,0.3); } + .content-section { display: none; flex-direction: column; gap: var(--padding-m); } + .content-section.active { display: flex; } + .card-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--padding-m); } + .bonus-card, .debt-card, .promo-card { background: linear-gradient(145deg, #2a2a2a, #1c1c1c); - border-radius: calc(var(--border-radius) + 8px); - padding: var(--padding-l); - text-align: center; - position: relative; - overflow: hidden; - } - .bonus-card { - box-shadow: var(--shadow-glow); - border: 1px solid rgba(255, 193, 7, 0.2); - } - .debt-card { - box-shadow: var(--shadow-glow-red); - border: 1px solid rgba(244, 67, 54, 0.2); - } - .card-label { - font-size: 1.1em; - font-weight: 500; - color: var(--text-secondary-color); - margin-bottom: 12px; - } - .bonus-amount { - font-size: 3em; - font-weight: 800; - color: var(--brand-yellow); - letter-spacing: -2px; - line-height: 1; + border-radius: calc(var(--border-radius) + 8px); padding: var(--padding-l); + text-align: center; position: relative; overflow: hidden; + } + .bonus-card { box-shadow: var(--shadow-glow); border: 1px solid rgba(255, 193, 7, 0.2); } + .debt-card { box-shadow: var(--shadow-glow-red); border: 1px solid rgba(244, 67, 54, 0.2); } + .promo-card { grid-column: 1 / -1; border: 1px solid rgba(255,255,255,0.1); } + .card-label { font-size: 1.1em; font-weight: 500; color: var(--text-secondary-color); margin-bottom: 12px; } + .bonus-amount, .debt-amount { font-size: 3em; font-weight: 800; letter-spacing: -2px; line-height: 1; } + .bonus-amount { color: var(--brand-yellow); } + .debt-amount { color: var(--brand-red); } + .client-id-card { + background-color: var(--card-bg); border-radius: var(--border-radius); + padding: var(--padding-m); display: flex; justify-content: space-between; align-items: center; } - .debt-amount { - font-size: 3em; - font-weight: 800; - color: var(--brand-red); - letter-spacing: -2px; - line-height: 1; + .client-id-label { font-weight: 500; color: var(--text-secondary-color); } + .client-id-value { + font-size: 1.3em; font-weight: 700; color: var(--brand-yellow); + letter-spacing: 2px; background-color: rgba(255,193,7,0.1); padding: 4px 10px; border-radius: 8px; } - .client-id-card { - background-color: var(--card-bg); - border-radius: var(--border-radius); - padding: var(--padding-m); - display: flex; - justify-content: space-between; - align-items: center; + .promo-code-display { + display: flex; align-items: center; justify-content: center; gap: 12px; + background-color: rgba(0,0,0,0.2); border-radius: 12px; padding: 12px; } - .client-id-label { - font-weight: 500; - color: var(--text-secondary-color); + .promo-code-value { + font-size: 1.5em; font-weight: 700; color: var(--brand-yellow); letter-spacing: 2px; } - .client-id-value { - font-size: 1.3em; - font-weight: 700; - color: var(--brand-yellow); - letter-spacing: 2px; - background-color: rgba(255,193,7,0.1); - padding: 4px 10px; - border-radius: 8px; + .copy-btn { + padding: 8px 16px; font-size: 0.9em; font-weight: 600; color: var(--brand-black); + background-color: var(--brand-yellow); border: none; border-radius: 8px; cursor: pointer; + transition: background-color 0.2s; } + .copy-btn:hover { background-color: #ffd447; } .history-section, .invoices-section, .business-card-section { - background-color: var(--card-bg); - border-radius: var(--border-radius); - padding: var(--padding-l); - display: flex; - flex-direction: column; - gap: var(--padding-m); + background-color: var(--card-bg); border-radius: var(--border-radius); + padding: var(--padding-l); display: flex; flex-direction: column; gap: var(--padding-m); } .history-title, .invoices-title, .business-card-title { - font-size: 1.4em; - font-weight: 700; - padding-bottom: var(--padding-m); + font-size: 1.4em; font-weight: 700; padding-bottom: var(--padding-m); border-bottom: 1px solid rgba(255, 255, 255, 0.1); } - .history-list, .invoices-list { - list-style: none; - padding: 0; - margin: 0; - max-height: 35vh; - overflow-y: auto; - } + .history-list, .invoices-list { list-style: none; padding: 0; margin: 0; max-height: 35vh; overflow-y: auto; } .history-item, .invoice-item { - display: flex; - justify-content: space-between; - align-items: center; - padding: 14px 4px; - border-bottom: 1px solid rgba(255, 255, 255, 0.05); + display: flex; justify-content: space-between; align-items: center; + padding: 14px 4px; border-bottom: 1px solid rgba(255, 255, 255, 0.05); } .history-item:last-child, .invoice-item:last-child { border-bottom: none; } + .invoice-item { cursor: pointer; transition: background-color 0.2s; border-radius: 8px; } + .invoice-item:hover { background-color: rgba(255,255,255,0.05); } .history-details, .invoice-details { display: flex; flex-direction: column; } .history-description, .invoice-description { font-size: 1em; font-weight: 500; } .history-date, .invoice-date { font-size: 0.8em; color: var(--text-secondary-color); margin-top: 4px; } .history-amount, .invoice-amount { font-size: 1.1em; font-weight: 700; } - .history-amount.accrual { color: #4CAF50; } - .history-amount.deduction { color: #F44336; } + .history-amount.accrual { color: var(--brand-green); } + .history-amount.deduction { color: var(--brand-red); } .invoice-amount { color: var(--brand-yellow); } - .no-history, .no-invoices { - text-align: center; - color: var(--text-secondary-color); - padding: 2rem 0; - } - - /* Business Card Styles */ - .business-card-item { - margin-bottom: 10px; - } - .business-card-label { - font-weight: 500; - color: var(--text-secondary-color); - margin-bottom: 4px; - } - .business-card-value { - font-size: 1.1em; - font-weight: 600; - color: var(--text-color); - } - .business-card-value a { - color: var(--brand-yellow); - text-decoration: none; - word-break: break-all; /* For long URLs */ - } - .business-card-value a:hover { - text-decoration: underline; - } - .business-card-phone-list { - list-style: none; - padding: 0; - margin: 0; - } - .business-card-phone-item { - margin-bottom: 5px; - } + .no-history, .no-invoices { text-align: center; color: var(--text-secondary-color); padding: 2rem 0; } + .business-card-item { margin-bottom: 10px; } + .business-card-label { font-weight: 500; color: var(--text-secondary-color); margin-bottom: 4px; } + .business-card-value { font-size: 1.1em; font-weight: 600; color: var(--text-color); } + .business-card-value a { color: var(--brand-yellow); text-decoration: none; word-break: break-all; } + .business-card-value a:hover { text-decoration: underline; } + .business-card-phone-list { list-style: none; padding: 0; margin: 0; } + .business-card-phone-item { margin-bottom: 5px; } .business-card-phone-item a { - display: inline-flex; - align-items: center; - gap: 8px; - color: var(--text-color); - text-decoration: none; - background-color: #2a2a2a; - padding: 8px 12px; - border-radius: 8px; - transition: background-color 0.2s; - } - .business-card-phone-item a:hover { - background-color: #3a3a3a; - } - .business-card-phone-item img { - height: 20px; - width: 20px; + display: inline-flex; align-items: center; gap: 8px; color: var(--text-color); + text-decoration: none; background-color: #2a2a2a; padding: 8px 12px; + border-radius: 8px; transition: background-color 0.2s; } - - /* Invoice Detail Modal */ + .business-card-phone-item a:hover { background-color: #3a3a3a; } + .business-card-phone-item img { height: 20px; width: 20px; } .modal { - display: none; - position: fixed; - z-index: 1000; - left: 0; - top: 0; - width: 100%; - height: 100%; - overflow: auto; - background-color: rgba(0,0,0,0.7); - backdrop-filter: blur(5px); - -webkit-backdrop-filter: blur(5px); + display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; + height: 100%; overflow: auto; background-color: rgba(0,0,0,0.7); + backdrop-filter: blur(5px); -webkit-backdrop-filter: blur(5px); + align-items: center; justify-content: center; } .modal-content { - background-color: var(--card-bg); - margin: 15% auto; - padding: var(--padding-l); - border-radius: var(--border-radius); - max-width: 90%; - width: 500px; - box-shadow: 0 5px 15px rgba(0,0,0,0.5); - position: relative; + background-color: var(--card-bg); margin: auto; padding: var(--padding-l); + border-radius: var(--border-radius); max-width: 90%; width: 500px; + box-shadow: 0 5px 15px rgba(0,0,0,0.5); position: relative; } .modal-close { - color: var(--text-secondary-color); - position: absolute; - top: 10px; - right: 20px; - font-size: 28px; - font-weight: bold; - cursor: pointer; - } - .modal-close:hover, - .modal-close:focus { - color: var(--text-color); - text-decoration: none; - cursor: pointer; - } - .modal-title { - font-size: 1.5em; - font-weight: 700; - margin-bottom: var(--padding-m); - color: var(--brand-yellow); - } - .invoice-detail-list { - list-style: none; - padding: 0; - margin: 0; + color: var(--text-secondary-color); position: absolute; top: 10px; right: 20px; + font-size: 28px; font-weight: bold; cursor: pointer; } + .modal-close:hover, .modal-close:focus { color: var(--text-color); text-decoration: none; cursor: pointer; } + .modal-title { font-size: 1.5em; font-weight: 700; margin-bottom: var(--padding-m); color: var(--brand-yellow); } + .invoice-detail-list, .promo-modal-body { list-style: none; padding: 0; margin: 0; } .invoice-detail-item { - display: flex; - justify-content: space-between; - padding: 10px 0; + display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px dashed rgba(255,255,255,0.1); } - .invoice-detail-item:last-child { - border-bottom: none; - } - .item-name { - font-weight: 500; - flex-basis: 60%; - } - .item-qty-price { - font-size: 0.9em; - color: var(--text-secondary-color); - flex-basis: 20%; - text-align: right; - } - .item-total { - font-weight: 700; - flex-basis: 20%; - text-align: right; - color: var(--brand-yellow); - } + .invoice-detail-item:last-child { border-bottom: none; } + .item-name { font-weight: 500; flex-basis: 60%; } + .item-qty-price { font-size: 0.9em; color: var(--text-secondary-color); flex-basis: 20%; text-align: right; } + .item-total { font-weight: 700; flex-basis: 20%; text-align: right; color: var(--brand-yellow); } .invoice-total-display { - padding-top: var(--padding-m); - border-top: 1px solid rgba(255,255,255,0.2); - margin-top: var(--padding-m); - display: flex; - justify-content: space-between; - font-size: 1.2em; - font-weight: 700; - } - .invoice-total-display span:first-child { - color: var(--text-color); - } - .invoice-total-display span:last-child { - color: var(--brand-yellow); - } + padding-top: var(--padding-m); border-top: 1px solid rgba(255,255,255,0.2); margin-top: var(--padding-m); + display: flex; justify-content: space-between; font-size: 1.2em; font-weight: 700; + } + .promo-modal-body { text-align: center; } + .promo-modal-body p { color: var(--text-secondary-color); margin-bottom: 1rem; } + .promo-modal-body input { + width: 100%; padding: 14px; margin-bottom: 1rem; font-size: 1.1em; + background-color: #2a2a2a; border: 1px solid #3a3a3a; border-radius: 12px; + color: var(--text-color); text-align: center; letter-spacing: 2px; + } + .promo-modal-actions { display: flex; gap: 1rem; } + .promo-modal-actions button { + flex-grow: 1; padding: 14px; font-size: 1em; font-weight: 700; + border: none; border-radius: 12px; cursor: pointer; transition: all 0.2s; + } + .btn-apply-promo { background-color: var(--brand-yellow); color: var(--brand-black); } + .btn-skip-promo { background-color: transparent; border: 2px solid #3a3a3a; color: var(--text-secondary-color); } + #promoStatus { margin-top: 1rem; font-weight: 500; min-height: 20px; } @@ -554,13 +375,11 @@ TEMPLATE = """

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

- -
@@ -571,13 +390,19 @@ TEMPLATE = """

Ваш долг

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

+
+

Ваш промокод для друзей

+
+ {{ user.referral_code }} + +
+

Ваш ID клиента

{{ user.id }}

-

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

{% if user.combined_history %} @@ -605,7 +430,6 @@ TEMPLATE = """ {% endif %}
-

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

@@ -626,7 +450,6 @@ TEMPLATE = """ {% endif %}
-

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

@@ -660,10 +483,7 @@ TEMPLATE = """
WhatsApp
{% if org_details.whatsapp_link %} - - - {{ org_details.whatsapp_link }} - + {{ org_details.whatsapp_link }} {% else %}
Не указано
{% endif %} @@ -673,10 +493,7 @@ TEMPLATE = """
Telegram
{% if org_details.telegram_link %} - - - {{ org_details.telegram_link }} - + {{ org_details.telegram_link }} {% else %}
Не указано
{% endif %} @@ -688,24 +505,36 @@ TEMPLATE = """
- - - + {% if is_first_visit %} + + {% endif %} @@ -1794,43 +1378,32 @@ ADMIN_TEMPLATE = """ @app.route('/') def index(): user_id_str = request.args.get('user_id_for_test') - - all_data = load_visitor_data() # Load all data, including organization details + all_data = load_visitor_data() user_data = {} + is_first_visit = False if user_id_str and user_id_str in all_data: 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' + is_first_visit = not user_data.get('has_been_welcomed', False) + 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 - ) + 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', []) # Pass invoices to template + user_data['invoices'] = user_data.get('invoices', []) else: user_data = { - "id": "N/A", - "bonuses": 0, - "debts": 0, - "history": [], - "debt_history": [], - "combined_history": [], - "invoices": [] + "id": "N/A", "bonuses": 0, "debts": 0, "history": [], "debt_history": [], + "combined_history": [], "invoices": [], "referral_code": "N/A" } org_details = all_data.get('organization_details', {}) - - return render_template_string(TEMPLATE, user=user_data, org_details=org_details) + return render_template_string(TEMPLATE, user=user_data, org_details=org_details, is_first_visit=is_first_visit) @app.route('/verify', methods=['POST']) def verify_data(): @@ -1841,7 +1414,6 @@ def verify_data(): 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: @@ -1849,79 +1421,108 @@ def verify_data(): user_info_dict = json.loads(user_json_str) except Exception as e: logging.error(f"Could not parse user JSON: {e}") - user_info_dict = {} - + if is_valid: tg_user_id = user_info_dict.get('id') if tg_user_id: now = datetime.now(BISHKEK_TZ) - all_data = load_visitor_data() # Get current state of all data + all_data = load_visitor_data() - existing_user_key = None - for key, user_data_item in all_data.items(): - # Skip 'organization_details' when iterating through users - if key == "organization_details": - continue - if str(user_data_item.get('telegram_id')) == str(tg_user_id): - existing_user_key = key - break + existing_user_key = next((key for key, user in all_data.items() if key != "organization_details" and str(user.get('telegram_id')) == str(tg_user_id)), None) if existing_user_key: user_entry = all_data[existing_user_key] user_entry.update({ - 'first_name': user_info_dict.get('first_name'), - 'last_name': user_info_dict.get('last_name'), - 'username': user_info_dict.get('username'), - 'photo_url': user_info_dict.get('photo_url'), - 'language_code': user_info_dict.get('language_code'), - 'visited_at': now.timestamp(), - 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S') + '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(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, # No phone number from Telegram initData by default - 'visited_at': now.timestamp(), - 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'), - 'bonuses': 0, - 'history': [], - 'debts': 0, - 'debt_history': [], - 'invoices': [] # Initialize invoices list + '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 } user_id_to_save = new_user_id - all_data[user_id_to_save] = user_entry # Update the global cache - save_visitor_data(all_data) # Save the entire cache - + 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 + return jsonify({"status": "error", "verified": True, "message": "User ID not found"}), 400 else: logging.warning(f"Verification failed for user: {user_info_dict.get('id')}") return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403 - except Exception as e: logging.exception("Error in /verify endpoint") return jsonify({"status": "error", "message": "Internal server error"}), 500 +@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') + all_data = load_visitor_data() + + if not user_id or user_id not in all_data: + return jsonify({"status": "error", "message": "Пользователь не найден."}), 404 + + user = all_data[user_id] + if user.get('has_been_welcomed', False): + return jsonify({"status": "ok", "message": "Вы уже прошли этот шаг."}), 200 + + user['has_been_welcomed'] = True + + if referral_code: + referrer = next((u for u_id, u in all_data.items() if u_id != "organization_details" and u.get('referral_code') == referral_code), None) + + if not referrer: + return jsonify({"status": "error", "message": "Промокод не найден."}), 404 + + if referrer['id'] == user_id: + return jsonify({"status": "error", "message": "Нельзя использовать свой пр��мокод."}), 400 + + user['referred_by'] = referrer['id'] + if 'referrals' not in referrer: referrer['referrals'] = [] + referrer['referrals'].append(user_id) + + all_data[user_id] = user + all_data[referrer['id']] = referrer + save_visitor_data(all_data) + return jsonify({"status": "ok", "message": "Промокод успешно применен!"}), 200 + else: + all_data[user_id] = user + save_visitor_data(all_data) + return jsonify({"status": "ok", "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(): all_data = load_visitor_data() users_list = [] + + # Create a map of user_id to user_name for quick lookup + user_name_map = {uid: f"{ud.get('first_name', '')} {ud.get('last_name', '')}".strip() or f"ID: {uid}" for uid, ud in all_data.items() if uid != "organization_details"} + for user_id, user_data in all_data.items(): - if user_id == "organization_details": # Skip organization details - continue + if user_id == "organization_details": continue user_data['id'] = user_id + + # Add referral info + user_data['referrals_count'] = len(user_data.get('referrals', [])) + referrer_id = user_data.get('referred_by') + user_data['referrer_info'] = user_name_map.get(referrer_id, None) + users_list.append(user_data) total_users = len(users_list) @@ -1930,12 +1531,9 @@ def admin_panel(): 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 + "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']) @@ -1949,121 +1547,60 @@ def add_client(): return jsonify({"status": "error", "message": "Имя и номер телефона обязательны."}), 400 all_data = load_visitor_data() - - # Check for existing phone number, excluding the 'organization_details' key - for key, user in all_data.items(): - if key == "organization_details": - continue - if user.get('phone_number') == phone_number: - return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409 + if any(u.get('phone_number') == phone_number for k, u in all_data.items() if k != "organization_details"): + return jsonify({"status": "error", "message": "Клиент с таким номером телефона уже существует."}), 409 now = datetime.now(BISHKEK_TZ) new_id = generate_unique_id(all_data) - new_client = { - 'id': new_id, - 'telegram_id': None, - 'first_name': first_name, - 'last_name': None, - 'username': None, - 'photo_url': None, - 'language_code': 'ru', - 'is_premium': False, - 'phone_number': phone_number, - 'visited_at': now.timestamp(), - 'visited_at_str': now.strftime('%Y-%m-%d %H:%M:%S'), - 'bonuses': 0, - 'history': [], - 'debts': 0, - 'debt_history': [], - 'invoices': [] # Initialize invoices for new manual 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 } - - all_data[new_id] = new_client # Update the global cache + all_data[new_id] = new_client save_visitor_data(all_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 = data.get('user_id') + user_id = str(data.get('user_id')) purchase_amount = float(data.get('purchase_amount', 0)) deduct_amount = float(data.get('deduct_amount', 0)) add_debt_amount = float(data.get('add_debt_amount', 0)) repay_debt_amount = float(data.get('repay_debt_amount', 0)) - if not user_id: - return jsonify({"status": "error", "message": "User ID is required"}), 400 - - user_id_str = str(user_id) + if not user_id: return jsonify({"status": "error", "message": "User ID is required"}), 400 all_data = load_visitor_data() + if user_id not in all_data: return jsonify({"status": "error", "message": "User not found"}), 404 - 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] + user = all_data[user_id] now = datetime.now(BISHKEK_TZ) - now_iso = now.isoformat() - now_str = now.strftime('%Y-%m-%d %H:%M:%S') - - if deduct_amount > user.get('bonuses', 0): - return jsonify({"status": "error", "message": "Недостаточно бонусов для списания"}), 400 + now_iso, now_str = now.isoformat(), now.strftime('%Y-%m-%d %H:%M:%S') - if repay_debt_amount > user.get('debts', 0): - return jsonify({"status": "error", "message": "Сумма погашения превышает текущий долг"}), 400 + if deduct_amount > user.get('bonuses', 0): return jsonify({"status": "error", "message": "Недостаточно бонусов для списания"}), 400 + if repay_debt_amount > user.get('debts', 0): return jsonify({"status": "error", "message": "Сумма погашения превышает текущий долг"}), 400 - # Bonus operations accrual_amount = purchase_amount * 0.02 user['bonuses'] = round(user.get('bonuses', 0) + 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": round(accrual_amount, 2), - "description": f"Начисление с покупки {round(purchase_amount, 2)}", - "date": now_iso, "date_str": now_str - }) - if deduct_amount > 0: - user['history'].append({ - "type": "deduction", "amount": round(deduct_amount, 2), - "description": "Списание бонусов", - "date": now_iso, "date_str": now_str - }) - - # Debt operations + if 'history' not in user: user['history'] = [] + if accrual_amount > 0: user['history'].append({"type": "accrual", "amount": round(accrual_amount, 2), "description": f"Начисление с покупки {round(purchase_amount, 2)}", "date": now_iso, "date_str": now_str}) + if deduct_amount > 0: user['history'].append({"type": "deduction", "amount": round(deduct_amount, 2), "description": "Списание бонусов", "date": now_iso, "date_str": now_str}) + 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": round(add_debt_amount, 2), - "description": "Добавление долга", - "date": now_iso, "date_str": now_str - }) - if repay_debt_amount > 0: - user['debt_history'].append({ - "type": "payment", "amount": round(repay_debt_amount, 2), - "description": "Погашение долга", - "date": now_iso, "date_str": now_str - }) + if 'debt_history' not in user: user['debt_history'] = [] + if add_debt_amount > 0: user['debt_history'].append({"type": "accrual", "amount": round(add_debt_amount, 2), "description": "Добавление долга", "date": now_iso, "date_str": now_str}) + if repay_debt_amount > 0: user['debt_history'].append({"type": "payment", "amount": round(repay_debt_amount, 2), "description": "Погашение долга", "date": now_iso, "date_str": now_str}) - all_data[user_id_str] = user # Update the global cache + all_data[user_id] = user save_visitor_data(all_data) - - return jsonify({ - "status": "ok", "message": "Transaction successful", - "new_balance": user['bonuses'], "new_debt": user['debts'] - }), 200 - + 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 @@ -2072,58 +1609,30 @@ def add_transaction(): def add_invoice(): try: data = request.get_json() - user_id = data.get('user_id') + user_id = str(data.get('user_id')) total_amount = float(data.get('total_amount', 0)) 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 + 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 not in all_data: return jsonify({"status": "error", "message": "User not found"}), 404 - 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] + user = all_data[user_id] 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() # Generate a short unique ID - - 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 - }) - - new_invoice = { - "invoice_id": invoice_id, - "date": now_iso, - "date_str": now_str, - "total_amount": round(total_amount, 2), - "items": processed_items - } + 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} - if 'invoices' not in user or not isinstance(user['invoices'], list): - user['invoices'] = [] + if 'invoices' not in user: user['invoices'] = [] user['invoices'].append(new_invoice) - all_data[user_id_str] = user + all_data[user_id] = user save_visitor_data(all_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 @@ -2132,72 +1641,40 @@ def add_invoice(): 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, 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 - user_id_str = str(user_id) all_data = load_visitor_data() + if user_id not in all_data: return jsonify({"status": "error", "message": "User not found"}), 404 - 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 + user = all_data[user_id] + if 'invoices' not in user: return jsonify({"status": "error", "message": "User has no invoices"}), 404 - original_invoice_count = len(user['invoices']) + 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_invoice_count: - return jsonify({"status": "error", "message": "Invoice not found for this user"}), 404 + if len(user['invoices']) == original_count: return jsonify({"status": "error", "message": "Invoice not found for this user"}), 404 - all_data[user_id_str] = user + all_data[user_id] = user save_visitor_data(all_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: - 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() # Load current state - - with _data_lock: # Ensure thread-safe modification of cache - 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": "Cannot delete a Telegram-linked user"}), 403 - - del all_data[user_id_str] # Modify the loaded data - - try: - # Save the modified all_data (which is visitor_data_cache) - with open(DATA_FILE, 'w', encoding='utf-8') as f: - json.dump(all_data, f, ensure_ascii=False, indent=4) - logging.info(f"User {user_id_str} deleted. Data saved to {DATA_FILE}.") - upload_data_to_hf_async() - except Exception as e: - logging.error(f"Error saving data after deletion: {e}") - return jsonify({"status": "error", "message": "Failed to save data after deletion"}), 500 + 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: + all_data = load_visitor_data() + if user_id not in all_data: return jsonify({"status": "error", "message": "User not found"}), 404 + if all_data[user_id].get('telegram_id') is not None: return jsonify({"status": "error", "message": "Cannot delete a Telegram-linked user"}), 403 + + del all_data[user_id] + save_visitor_data(all_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 @@ -2206,8 +1683,7 @@ def delete_client(): def get_organization_details(): try: all_data = load_visitor_data() - org_details = all_data.get('organization_details', {}) - return jsonify(org_details), 200 + return jsonify(all_data.get('organization_details', {})), 200 except Exception as e: logging.exception("Error getting organization details") return jsonify({"status": "error", "message": str(e)}), 500 @@ -2217,17 +1693,13 @@ def save_organization_details(): try: data = request.get_json() new_org_details = { - "name": data.get("name", ""), - "phone_numbers": data.get("phone_numbers", []), - "address": data.get("address", ""), - "whatsapp_link": data.get("whatsapp_link", ""), + "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", "") } - all_data = load_visitor_data() all_data['organization_details'] = new_org_details - save_visitor_data(all_data) # Save the entire updated cache - + save_visitor_data(all_data) return jsonify({"status": "ok", "message": "Organization details saved successfully"}), 200 except Exception as e: logging.exception("Error saving organization details") @@ -2241,15 +1713,11 @@ if __name__ == '__main__': else: print("Attempting initial data download from Hugging Face...") download_data_from_hf() - - load_visitor_data() # Ensure data is loaded into cache at startup - + 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) + app.run(host=HOST, port=PORT, debug=False) \ No newline at end of file