Эх сурвалжийг харах

Merge branch 'unstable' of blezz-tech/sharix-open-webservice-running into unstable

+ 7 - 0
handlers/bin/test/test.py

@@ -0,0 +1,7 @@
+from core.requesters import TicketRequester
+from config import KEYS
+from pprint import pprint
+
+ticket_requester = TicketRequester(KEYS.OPEN_ACCESS_REQUEST_PENDING)
+
+pprint(ticket_requester.all().json())

+ 4 - 2
handlers/classes/Ticket.py

@@ -1,5 +1,5 @@
 from datetime import datetime
-from config import DEFAULT_INTERVAL_ATTEMPTS
+from config import DEFAULT_INTERVAL_ATTEMPTS, DEFAULT_ASSIGNED_TO_ATTEMPTS
 
 class Ticket(object):
     def __init__(
@@ -17,7 +17,8 @@ class Ticket(object):
             assigned_to=None,
             note=None,
 
-            interval_attempts: int = DEFAULT_INTERVAL_ATTEMPTS
+            interval_attempts: int = DEFAULT_INTERVAL_ATTEMPTS,
+            assigned_to_attempts: int = DEFAULT_ASSIGNED_TO_ATTEMPTS
     ):
         self.id = id
         self.status = status
@@ -33,6 +34,7 @@ class Ticket(object):
         self.note = note
 
         self.interval_attempts = interval_attempts
+        self.assigned_to_attempts = assigned_to_attempts
 
     def __str__(self):
         return "{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}".format(

+ 2 - 1
handlers/config.py

@@ -34,12 +34,13 @@ BOTLIST = [
 JSERVER = "ej.sharix-app.org"
 PASSWORD = "12345"
 PORT = 5222
-API_URL = "https://testopen.sharix-app.org/"
+API_URL = "https://testopen1.sharix-app.org/"
 
 # LOG_DIR = "/var/log/"
 LOG_DIR = "./log/"
 
 DEFAULT_INTERVAL_ATTEMPTS = 10
+DEFAULT_ASSIGNED_TO_ATTEMPTS = 3
 
 class KEYS:
     OPEN_BASIC_BOT = os.getenv('open_basic_bot_key')

+ 39 - 0
handlers/core/requesters.py

@@ -0,0 +1,39 @@
+from classes.Ticket import Ticket
+import config
+import requests
+from typing import List
+
+
+class TicketRequester:
+    def __init__(self, token: str):
+        self.token = token
+
+
+    def patch(self, ticket: Ticket, data: dict) -> Ticket:
+        """ Частичное обновление тикета """
+        url: str = config.API_URL + f"tickets/api/v2/ticket/{ticket.id}/"
+        headers = {'Authorization': f'Api-Key {self.token}'}
+        response = requests.patch(url, json=data, headers=headers)
+        return response
+    
+    def all(self) -> List[Ticket]:
+        """ Получение всех тикетов """
+        url: str = config.API_URL + "tickets/api/v2/ticket/"
+        headers = {'Authorization': f'Api-Key {self.token}'}
+        response = requests.get(url, headers=headers)
+        return response
+
+
+    def put(self, ticket: Ticket, data: dict) -> Ticket:
+        """ Обновление тикета """
+        None
+
+
+    def post(self, ticket: Ticket, data: dict) -> Ticket:
+        """ Создание тикета """
+        None
+
+
+    def delete(self, ticket: Ticket) -> Ticket:
+        """ Удаление тикета """
+        None

+ 25 - 2
handlers/handlers/open_access_request_pending.py

@@ -12,7 +12,10 @@ from typing import List
 from concurrent.futures import ThreadPoolExecutor
 from core.SystemdKiller import SystemdKiller
 from core.utils import get_init_data
+from core.requesters import TicketRequester
 from jsonAndRequest import requestGetListUser
+from config import KEYS
+
 botname = "open_access_request_pending"
 operating_status = 320
 
@@ -35,8 +38,10 @@ proceed_to = [
 ]
 """ Список jid, кому бот может отправлять сообщения в результате обработки заявки """
 
+ASSIGNET_TO_ATTEMPTS = 3
+""" Количество пользователей, которым будет отправлено сообщение """
 INTERVAL_ATTEMPTS = 3
-""" Количество попыток отправки сообщения """
+""" Количество сообщений, которые будут отправлены пользователю """
 # INTERVAL_TIME = 30 * 60  # 30 минут в секундах
 INTERVAL_TIME = 5 # Для проверки
 """ Интервал времени между попытками отправки сообщения """
@@ -46,6 +51,8 @@ TEMP_TICKETS: List[Ticket] = []
 ID_TICKETS_FOR_REMOVE: List[int] = []
 """ Список id тикетов для удаления """
 
+ticket_requester = TicketRequester(KEYS.OPEN_ACCESS_REQUEST_PENDING)
+
 def message_handler(msg: Message):
     """Обработчик входящих сообщений"""
 
@@ -102,7 +109,10 @@ def start_handler():
 def interval_attempts_unlimited(ticket: Ticket) -> None:
     logging.debug(f"Лимит попыток обработки тикета {ticket.id} исчерпан")
     
-    # db.changestatus
+
+    ticket_requester.patch(ticket, {"status": 359})
+    
+    # TODO: implement send ticket changed to next handler
     # bot.send_message(JID, f"Сообщение отправлено {JID}: {datetime.now()}")
     # bot message:
     # {
@@ -131,6 +141,19 @@ def send_notification_to_admins(ticket: Ticket, admins: List[str], message: str)
         bot.send_message(admin, message)
     logging.info(f"Уведомление отправлено администраторам: {ticket.id}")
 
+
+def set_assigned_to(ticket: Ticket) -> Ticket:
+    """Проверка, назначен ли тикет на пользователя"""
+    if ticket.assigned_to is None:
+        # TODO: add function how select user from db
+        # ticket.assigned_to = "username"
+
+        # ticket_requester.patch(ticket, {"assigned_to": "open_access_request_pending@ej.sharix-app.org"})
+        
+        return ticket
+    else:
+        return ticket
+
 # def get_token():
 #     return jsreq.requestGetToken(botname, PASSWORD, config.API_URL + "/auth/token/login/")