File size: 7,515 Bytes
3e8a166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# management/tasks.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import requests
import json
import os
import datetime
from celery import shared_task
from django.db import connections, connection
from django.conf import settings
from django.utils import timezone

from .models import (
    Panel,
    AdminLevel2,
    AdminLevel3,
    EndUser,
    Payment,
    CustomUser,
    Subscription,
)
from django.core.management import call_command

# --- Utilities ---
# FIXED: Renamed function to match imports in other files
@shared_task
def send_telegram_message(chat_id, message, bot_token):
    """
    Sends a message to a specific Telegram chat using a bot token.
    """
    if not bot_token:
        print("Telegram bot token is not configured.")
        return

    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": message,
        "parse_mode": "Markdown"
    }
    
    try:
        response = requests.post(url, json=payload)
        response.raise_for_status()
        print(f"Notification sent successfully to chat_id {chat_id}")
    except requests.RequestException as e:
        print(f"Failed to send notification to chat_id {chat_id}: {e}")

# --- Celery Tasks ---
@shared_task(name="management.tasks.schedule_reminders")
def schedule_reminders():
    """
    Celery task to send periodic reminders to admins and users.
    """
    now = timezone.now().date()
    
    # 1. License expiry warnings for AdminLevel2s (resellers)
    three_days_from_now = now + datetime.timedelta(days=3)
    admin_level2s = AdminLevel2.objects.filter(license_expiry_date__lte=three_days_from_now)
    for admin in admin_level2s:
        # Assuming AdminLevel2 is linked to a Panel through its CustomUser owner
        # This part might need adjustment based on the final model structure
        try:
            panel = Panel.objects.get(owner=admin.user)
            if admin.telegram_chat_id and panel.telegram_bot_token:
                message = (
                    f"🚨 **هشدار انقضای لایسنس!**\n\n"
                    f"ادمین {admin.user.username}، لایسنس شما در تاریخ {admin.license_expiry_date} منقضی خواهد شد. لطفاً برای تمدید آن اقدام کنید."
                )
                send_telegram_message(
                    chat_id=admin.telegram_chat_id,
                    message=message,
                    bot_token=panel.telegram_bot_token
                )
        except Panel.DoesNotExist:
            print(f"Panel for admin {admin.user.username} not found.")


@shared_task
def send_payment_receipt_to_admin(payment_id):
    """
    Sends a payment receipt notification to the relevant admin via Telegram.
    """
    try:
        payment = Payment.objects.get(id=payment_id)
        admin = payment.admin
        panel = payment.subscription.panel

        if not admin.admin_level_3.telegram_chat_id or not panel.telegram_bot_token:
            print(f"Admin telegram_chat_id or bot token not found for payment {payment_id}.")
            return

        message = (
            f"🔔 **رسید پرداخت جدید!**\n\n"
            f"یک کاربر ({payment.subscription.end_user.username}) رسید پرداختی را برای تمدید اشتراک ارسال کرده است.\n"
            f"مبلغ: {payment.amount} تومان\n"
            f"توکن پرداخت: `{payment.payment_token}`\n"
            f"لطفا به پنل خود مراجعه کرده و پرداخت را تایید کنید."
        )

        if payment.receipt_image:
            message += f"\n\nتصویر رسید پرداخت آپلود شده است."
        elif payment.receipt_text:
             message += f"\n\nمتن رسید پرداخت: {payment.receipt_text}"
        
        send_telegram_message(
            chat_id=admin.admin_level_3.telegram_chat_id,
            message=message,
            bot_token=panel.telegram_bot_token
        )

    except Payment.DoesNotExist:
        print(f"Payment with id {payment_id} not found.")
    except Exception as e:
        print(f"Error sending payment receipt to admin: {e}")


@shared_task
def send_payment_confirmation_to_user(end_user_id, amount, status):
    """
    Sends a payment confirmation message to the end-user.
    """
    try:
        end_user = EndUser.objects.get(id=end_user_id)
        panel = end_user.panel
        
        if not panel or not panel.telegram_bot_token or not end_user.telegram_chat_id:
            print(f"EndUser panel, bot token or telegram_chat_id not found for user {end_user_id}.")
            return

        if status == 'approved':
            message = (
                f"✅ **پرداخت شما تأیید شد**\n\n"
                f"مبلغ {amount} تومان برای پنل {panel.name} با موفقیت تأیید شد. سرویس شما به زودی فعال خواهد شد."
            )
        else:
            message = (
                f"❌ **پرداخت شما رد شد**\n\n"
                f"پرداخت {amount} تومان برای پنل {panel.name} رد شد. لطفاً رسید معتبر را ارسال کنید."
            )

        send_telegram_message(
            chat_id=end_user.telegram_chat_id,
            message=message,
            bot_token=panel.telegram_bot_token
        )
    except EndUser.DoesNotExist:
        print(f"EndUser with id {end_user_id} not found.")
    except Exception as e:
        print(f"Error sending payment confirmation to user: {e}")

@shared_task(name="management.tasks.check_subscription_expiry")
def check_subscription_expiry():
    """
    Celery task to check subscription expiry and send notifications.
    """
    now = timezone.now().date()
    
    # Send reminder 3 days before expiry
    three_days_from_now = now + datetime.timedelta(days=3)
    expiring_soon_subscriptions = Subscription.objects.filter(
        end_date__date=three_days_from_now,
        status='active'
    )
    
    for sub in expiring_soon_subscriptions:
        if sub.end_user.telegram_chat_id and sub.panel.telegram_bot_token:
            message = (
                f"⏳ **اشتراک شما به زودی منقضی می‌شود!**\n\n"
                f"کاربر {sub.end_user.username}، اشتراک شما در تاریخ {sub.end_date.strftime('%Y-%m-%d')} منقضی خواهد شد. برای تمدید آن از طریق بات اقدام کنید."
            )
            send_telegram_message(
                chat_id=sub.end_user.telegram_chat_id,
                message=message,
                bot_token=sub.panel.telegram_bot_token
            )
            
    # Deactivate expired subscriptions
    expired_subscriptions = Subscription.objects.filter(end_date__lte=now, status='active')
    for sub in expired_subscriptions:
        sub.status = 'expired'
        sub.save()
        if sub.end_user.telegram_chat_id and sub.panel.telegram_bot_token:
            message = (
                f"❌ **اشتراک شما منقضی شد!**\n\n"
                f"کاربر {sub.end_user.username}، اشتراک شما منقضی شده است. لطفا برای تمدید اقدام کنید."
            )
            send_telegram_message(
                chat_id=sub.end_user.telegram_chat_id,
                message=message,
                bot_token=sub.panel.telegram_bot_token
            )