#6 Создание обработчика st_request_in_process (DRAFT)

Open
blezz-tech wants to merge 1 commits from blezz-tech/time_for_handlers into ShariX_Open/new_handlers
3 changed files with 169 additions and 1 deletions
  1. 1 1
      handlers/config.py
  2. 75 0
      handlers/jsonAndRequest.py
  3. 93 0
      handlers/st_request_in_process.py

+ 1 - 1
handlers/config.py

@@ -1,5 +1,5 @@
 #rename this file to config.py
-BOTLIST=["open_basic_bot",'status_changer','st_request_done','st_request_wontfix','st_request_assigned','st_request_new']
+BOTLIST=["open_basic_bot",'status_changer','st_request_done','st_request_wontfix','st_request_assigned','st_request_new','st_request_in_process']
 JSERVER="ej.sharix-app.org"
 PASSWORD="12345"
 PORT=5222

+ 75 - 0
handlers/jsonAndRequest.py

@@ -100,6 +100,81 @@ class Ticket_user(object):
         self.created_by, self.assigned_to
     )
 
+class User(object):
+    def __init__(self,
+        group_name,
+        last_login,
+        is_superuser,
+        username,
+        is_staff,
+        is_active,
+        date_joined,
+        middle_name,
+        phone_number,
+        email,
+        avatar,
+        groups,
+        user_permissions,
+        full_name="",
+        last_name="",
+        first_name="",
+    ):
+        self.full_name = full_name
+        self.group_name = group_name
+        self.last_login = last_login
+        self.is_superuser = is_superuser
+        self.username = username
+        self.is_staff = is_staff
+        self.is_active = is_active
+        self.date_joined = date_joined
+        self.last_name = last_name
+        self.first_name = first_name
+        self.middle_name = middle_name
+        self.phone_number = phone_number
+        self.email = email
+        self.avatar = avatar
+        self.groups = groups
+        self.user_permissions = user_permissions
+
+    def  __str__(self):
+        return ', '.join([
+            str(self.full_name),
+            str(self.group_name),
+            str(self.last_login),
+            str(self.is_superuser),
+            str(self.username),
+            str(self.is_staff),
+            str(self.is_active),
+            str(self.date_joined),
+            str(self.last_name),
+            str(self.first_name),
+            str(self.middle_name),
+            str(self.phone_number),
+            str(self.email),
+            str(self.avatar),
+            str(self.groups),
+            str(self.user_permissions)
+        ]) + '\n'
+
+def requestGetUser(auth_token, url):
+    headers = {'Authorization': f'Token {auth_token}'}
+    response = requests.get(url, headers=headers)
+    
+    #response = requests.get(config.API_URL+"/dbsynce/api/orders/", headers=headers)
+    usertext=response.json()
+    print(usertext)
+    user = None
+    if not usertext:
+        print("Empty user")
+        None
+    else:
+        try:
+            user = User(**usertext)
+        except Exception as ex:
+            print(ex)
+    print (user)
+    return user
+
 def requestGetTicket_user(auth_token, url):
     headers = {'Authorization': f'Token {auth_token}'}
     response = requests.get(url, headers=headers)

+ 93 - 0
handlers/st_request_in_process.py

@@ -0,0 +1,93 @@
+import json
+import requests
+import config
+from BotClass import JabberBot
+import hashlib
+from datetime import datetime
+import time
+import threading
+import jsonAndRequest as jsreq
+
+global ticketlist
+
+botname = "st_request_in_process"
+JID = botname + "@" + config.JSERVER
+PORT = config.PORT
+PASSWORD = hashlib.md5((botname + config.PASSWORD).encode('utf-8')).hexdigest()
+
+listen_to = ["st_request_wontfix@ej.sharix-app.org"]
+proceed_to = ["numbers"]
+
+# Новые параметры
+IS_INFINITE_REMINDER = False
+DEFAULT_REMINDER_INTERVAL = 30 * 60  # 30 минут в секундах
+MAX_REMINDERS = 3  # Максимальное количество напоминаний
+DEFAULT_CHECK_INTERVAL = 5 * 60 # Проверка тикетов каждые 5 минут
+
+# Параметры для тестирования
+# MAX_REMINDERS = 2
+# DEFAULT_REMINDER_INTERVAL = 5
+# DEFAULT_CHECK_INTERVAL = 7
+
+tickets_nt = {}
+
+def send_reminder_notification(user, ticket):
+    message = f"Напоминание: необходимо принять решение по тикету {ticket.id}"
+
+    bot.send_notification(user.username + '@' + config.JSERVER, message)
+
+    print(f"Отправлено напоминание пользователю {user.username} о тикете {ticket.id}")
+
+def send_wontfix_notification(user, ticket):
+    message = f"Уведомление: тикет {ticket.id} был отмечен как WONTFIX из-за отсутствия действий"
+
+    bot.send_notification(user.username + '@' + config.JSERVER, message)
+
+    print(f"Отправлено уведомление пользователю {user.username} о WONTFIX для тикета {ticket.id}")
+
+def ticket_worker(user, ticket, start_time):
+    # print(f"\n\n\n{tickets_nt}\n\n\n")
+    if ticket.id not in tickets_nt:
+        tickets_nt[ticket.id] = {
+            "reminders": 0,
+            "last_date_reminder": start_time
+        }
+
+    dtime_notification = start_time - tickets_nt[ticket.id]["last_date_reminder"]
+
+    if dtime_notification.seconds > DEFAULT_REMINDER_INTERVAL:
+        tickets_nt[ticket.id]["reminders"] += 1
+        tickets_nt[ticket.id]["last_date_reminder"] = start_time
+
+        if IS_INFINITE_REMINDER or tickets_nt[ticket.id]['reminders'] <= MAX_REMINDERS:
+            send_reminder_notification(user, ticket)
+        else:
+            del tickets_nt[ticket.id]
+            jsreq.requestPatchTicketUser(token, config.API_URL+f"tickets/api/ticket/{ticket.id}/status", { "status": 149 })
+            send_wontfix_notification(user, ticket)
+        
+    # print(f"\n\n\n{tickets_nt}\n\n\n")
+
+def ticket_list_worker(ticket_list, start_time):
+    tickets=jsreq.requestGetTicket_user(token, config.API_URL+f"tickets/api/ticket_list/{ticket_list.id}")
+    for ticket in tickets:
+        if ticket.status == 131:
+            user = jsreq.requestGetUser(token, config.API_URL+f"api/v1/platform/sharix-users/{ticket.assigned_to}")
+            if user != None:
+                ticket_worker(user, ticket, start_time)
+
+def status_changer():
+    while True:
+        ticket_lists = jsreq.requestGetList(token, config.API_URL + "tickets/api/ticket_list/")
+        for ticket_list in ticket_lists:
+            start_time = datetime.now()
+            # bot.bot_log(f"{botname} {start_time.strftime('%Y-%m-%d')} Тикет {ticketlist.id} в обработке\n")
+            t1 = threading.Thread(target=ticket_list_worker, args=(ticket_list, start_time))
+            t1.start()
+            t1.join()  # Ожидаем завершения обработки тикета
+        time.sleep(DEFAULT_CHECK_INTERVAL)
+
+# Инициализация и запуск бота
+token = jsreq.requestGetToken(config.API_URL + "api/v1/auth/token/login/")
+bot = JabberBot(JID, PASSWORD, PORT)
+bot.start(status_changer)