2 Commits 8540bcc784 ... 0973fb78ad

Autor SHA1 Mensagem Data
  Dev Server 0973fb78ad Merge remote-tracking branch 'refs/remotes/origin/simple' into simple 1 ano atrás
  Dev Server 6d4cf733b0 new changes for assist template 1 ano atrás
5 arquivos alterados com 202 adições e 6 exclusões
  1. 1 1
      BotClass.py
  2. 132 0
      assist_servicerequest_booked.py
  3. 20 2
      config_template.py
  4. 26 0
      genservice.py
  5. 23 3
      jsonAndRequest.py

+ 1 - 1
BotClass.py

@@ -35,7 +35,7 @@ class JabberBot:
 
     def step_on(self):
         try:
-            self.conn.Process(1) #с какой частотой происходит подключение к серверу, в данном случае каждую секунду
+            self.conn.Process(5) #с какой частотой происходит подключение к серверу, в данном случае каждую секунду
         except KeyboardInterrupt: return 0
         return 1
 

+ 132 - 0
assist_servicerequest_booked.py

@@ -0,0 +1,132 @@
+import xmpp
+from xmpp import cli
+import config
+from BotClass import JabberBot
+import json
+#раскомментировать, когда перейдем на разные пароли
+import hashlib
+from datetime import datetime
+
+import time
+import threading
+
+#test
+import jsonAndRequest as jsreq
+
+global tasklist
+
+#В этом файле содержится только то, что запускает конкретный обработчик
+
+# botname="open_strequest_assigned"
+botname="assist_servicerequest_booked"
+operating_status=211
+JID=botname+"@"+config.JSERVER
+PORT=config.PORT
+
+#раскомментировать, когда перейдем на разные пароли
+PASSWORD=hashlib.md5((botname+config.PASSWORD).encode('utf-8')).hexdigest()
+
+print(JID, PASSWORD)
+
+#таким образом хранится список jid, от которых можно получать сообщения этому боту
+listen_to=["assist_backend@ej.sharix-app.org", "799999999999@ej.sharix-app.org"]
+
+#тут хранится список jid, кому бот может отправлять сообщения в результате обработки заявки
+proceed_to=["assist_servicerequest_booked@ej.sharix-app.org", "assit_backend@ej.sharix-app.org", "799999999999@ej.sharix-app.org", "assist_servicerequest_assigned@ej.sharix-app.org", "assist_servicerequest_forcemajeure@ej.sharix-app.org"]
+
+#максимальное значение попыток обработать заказ
+idle_value=10
+
+# обработчик входящих сообщений
+def message_handler(conn, mess):
+    text = mess.getBody()#текст сообщения боту
+    user = mess.getFrom()#отправитель сообщения
+    #user = mess.getNode()#только jid 
+   
+   #нужна проверка, данный обработчик вообще должен от данного отправителя получать сообщения или нет. Подсказка ниже
+    print (str(user).split("/")[0])
+    if (str(user).split("/")[0]) in listen_to:
+        print(text)
+        print(mess)
+
+        if text is not None:
+            orderObj = jsreq.jsonToOrder(text)
+            print (orderObj)
+            tasklist.append(orderObj)
+            bot.bot_log(str(datetime.now())+" Поступивший заказ успешно добавлен в очередь обработки\n")
+            print("Поступивший заказ успешно добавлен в очередь обработки\n")
+
+def assist_wait(period,localtask):
+    bot.bot_log(botname+" "+str(datetime.now())+" "+"Заказ ожидает\n")
+    time.sleep(period)
+    
+    #ВАЖНО! Надо скорее всего через API редактировать заказ, иначе возможна потеря данных
+    localtask.title=localtask.title+"1"
+
+    #обязательно данный обработчик должен заканчиваться передачей заказа куда-то на обработку дальше - обратно или другому, иначе оно потеряется
+    bot.proceed_status(proceed_to[2],localtask)
+    bot.bot_log(botname+" "+str(datetime.now())+" "+"Заказ подождал и возвращен пользователю\n")
+
+def assist_servicerequest_choose_driver(localtask):
+    bot.bot_log(botname+" "+str(datetime.now())+" "+"Заказ в обработчике\n")
+    
+    #ВАЖНО! Надо через API редактировать заказ, иначе возможна потеря данных
+    #localtask.title +=1
+
+    bot.proceed_status(proceed_to[-2],localtask)
+    bot.bot_log(botname+" "+str(datetime.now())+" "+"Заказ успешно обработан\n")
+
+
+def assist_servicerequest_booked():
+    print("Тут описывается работа со списком задач в данном статусе")
+    while (len(tasklist)):
+    #for i in range(len(tasklist)):
+        #проверяем элемент tasklist[i]
+        #print (i, len(tasklist))
+        localtask=tasklist.pop(0)
+        bot.bot_log(botname + " " + datetime.now().strftime('%Y-%m-%d') + " "+ "Заказ в очереди на обработке\n")
+        #bot.bot_log(botname + " " + datetime.now().strftime('%Y-%m-%d') + " " + str(i) + " " + "Заказ в очереди на обработке\n")
+        #print ("EACH TASKLIST", tasklist[i])
+        #localtask=tasklist.pop(i)
+        
+        #если боту почему-то пришла не его заявка - это явно ошибка движения процессов и отдаем в форсмажор - этот обработчик указывать стоит всегда последним
+        if (localtask.status!=operating_status):
+            bot.proceed_status(proceed_to[-1],localtask)
+            bot.bot_log(botname+" "+str(datetime.now())+" "+"Заказ не по адресу, перенаправляем на форсмажор\n")
+            continue
+
+        if (localtask.asap!=true):
+            t1=threading.Thread(target=assist_wait, args=(5,localtask))
+            t1.start()
+
+        if (localtask.client_id=="799999999999"):
+            print ("HELLO")
+            #t1=threading.Thread(target=assist_servicerequest_choose_driver, args=(localtask))
+            #t1.start()
+
+        #если никакие обработчики не подошли - отправляем обратно в очередь
+        bot.proceed_status(proceed_to[0],localtask)
+        print("Заказ возвращен в очередь\n")
+        print (tasklist)
+
+#Авторизация и запуск бота
+
+#пустой список заказов
+tasklist = []
+
+#надо инициализировать tasklist при запуске из API
+token = jsreq.requestGetToken(botname, PASSWORD, config.API_URL+"/auth/token/login/")
+
+#ВАЖНО! Надо еще фильтровать список по статусу обработки заявки
+tasklist=jsreq.requestGetList(token, config.API_URL+"/tickets/api/tickets/?list_id=10")
+#tasklist=jsreq.requestGetList(token, config.API_URL+"/tickets/api/tickets")
+print (len(tasklist))
+
+
+bot = JabberBot(JID, PASSWORD, PORT)
+
+bot.register_handler('message', message_handler)
+bot.start(assist_servicerequest_booked)
+
+
+

+ 20 - 2
config_template.py

@@ -1,8 +1,26 @@
 #rename this file to config.py
-BOTLIST=["open_template_bot","open_strequest_assigned","open_strequest_inprocess","open_strequest_new","open_strequest_reopened","open_strequest_wontfix","open_strequest_done","open_strequest_duplicate","open_strequest_closed","open_accessrequest_pending","open_accessrequest_accepted","open_accessrequest_declined","open_negrequest_pending","open_negrequest_accepted","open_negrequest_declined","open_servicerequest_template","open_servicerequest_booked","open_servicerequest_assigned","open_servicerequest_accepted","open_servicerequest_pending","open_servicerequest_declined","open_servicerequest_prestart","open_servicerequest_process","open_servicerequest_forcemajeure","open_servicerequest_forcemajeurecancelled","open_servicerequest_done","open_servicerequest_cancelled","open_servicerequest_closed"]
+
+#JID="example@msg.sharix-app.org"
+#BOTLIST=["guide_template_bot","guide_strequest_assigned","guide_strequest_inprocess","guide_strequest_new","guide_strequest_reguideed","guide_strequest_wontfix","guide_strequest_done","guide_strequest_duplicate","guide_strequest_closed","guide_accessrequest_pending","guide_accessrequest_accepted","guide_accessrequest_declined","guide_negrequest_pending","guide_negrequest_accepted","guide_negrequest_declined","guide_servicerequest_template","guide_servicerequest_booked","guide_servicerequest_assigned","guide_servicerequest_accepted","guide_servicerequest_pending","guide_servicerequest_declined","guide_servicerequest_prestart","guide_servicerequest_process","guide_servicerequest_forcemajeure","guide_servicerequest_forcemajeurecancelled","guide_servicerequest_done","guide_servicerequest_cancelled","guide_servicerequest_closed"]
+#BOTLIST=["sports_template_bot","sports_strequest_assigned","sports_strequest_inprocess","sports_strequest_new","sports_strequest_resportsed","sports_strequest_wontfix","sports_strequest_done","sports_strequest_duplicate","sports_strequest_closed","sports_accessrequest_pending","sports_accessrequest_accepted","sports_accessrequest_declined","sports_negrequest_pending","sports_negrequest_accepted","sports_negrequest_declined","sports_servicerequest_template","sports_servicerequest_booked","sports_servicerequest_assigned","sports_servicerequest_accepted","sports_servicerequest_pending","sports_servicerequest_declined","sports_servicerequest_prestart","sports_servicerequest_process","sports_servicerequest_forcemajeure","sports_servicerequest_forcemajeurecancelled","sports_servicerequest_done","sports_servicerequest_cancelled","sports_servicerequest_closed"]
+#BOTLIST=["drive_template_bot","drive_strequest_assigned","drive_strequest_inprocess","drive_strequest_new","drive_strequest_redriveed","drive_strequest_wontfix","drive_strequest_done","drive_strequest_duplicate","drive_strequest_closed","drive_accessrequest_pending","drive_accessrequest_accepted","drive_accessrequest_declined","drive_negrequest_pending","drive_negrequest_accepted","drive_negrequest_declined","drive_servicerequest_template","drive_servicerequest_booked","drive_servicerequest_assigned","drive_servicerequest_accepted","drive_servicerequest_pending","drive_servicerequest_declined","drive_servicerequest_prestart","drive_servicerequest_process","drive_servicerequest_forcemajeure","drive_servicerequest_forcemajeurecancelled","drive_servicerequest_done","drive_servicerequest_cancelled","drive_servicerequest_closed"]
+#BOTLIST=["open_template_bot","open_strequest_assigned","open_strequest_inprocess","open_strequest_new","open_strequest_reopened","open_strequest_wontfix","open_strequest_done","open_strequest_duplicate","open_strequest_closed","open_accessrequest_pending","open_accessrequest_accepted","open_accessrequest_declined","open_negrequest_pending","open_negrequest_accepted","open_negrequest_declined","open_servicerequest_template","open_servicerequest_booked","open_servicerequest_assigned","open_servicerequest_accepted","open_servicerequest_pending","open_servicerequest_declined","open_servicerequest_prestart","open_servicerequest_process","open_servicerequest_forcemajeure","open_servicerequest_forcemajeurecancelled","open_servicerequest_done","open_servicerequest_cancelled","open_servicerequest_closed"]
+BOTLIST=["assist_template_bot","assist_strequest_assigned","assist_strequest_inprocess","assist_strequest_new","assist_strequest_reassisted","assist_strequest_wontfix","assist_strequest_done","assist_strequest_duplicate","assist_strequest_closed","assist_accessrequest_pending","assist_accessrequest_accepted","assist_accessrequest_declined","assist_negrequest_pending","assist_negrequest_accepted","assist_negrequest_declined","assist_servicerequest_template","assist_servicerequest_booked","assist_servicerequest_assigned","assist_servicerequest_accepted","assist_servicerequest_pending","assist_servicerequest_declined","assist_servicerequest_prestart","assist_servicerequest_process","assist_servicerequest_forcemajeure","assist_servicerequest_forcemajeurecancelled","assist_servicerequest_done","assist_servicerequest_cancelled","assist_servicerequest_closed"]
+JSERVER="ej.sharix-app.org"
+PASSWORD="12345"
+PORT=349
+#Assist
+API_URL = "http://10.0.20.2:8000"
+#Drive
+#API_URL = "http://10.0.20.3:8000"
+#Guide
+#API_URL = "http://10.0.20.4:8000"
+#Sports
+#API_URL = "http://10.0.20.5:8000"
+
 JSERVER="ej.sharix-app.org"
 PASSWORD="12345"
 PORT=349
-API_URL = "https://testbase.sharix-app.org"
+#API_URL = "https://testbase.sharix-app.org"
 
 

+ 26 - 0
genservice.py

@@ -0,0 +1,26 @@
+import hashlib
+
+#rename this file to config.py
+#JID="example@msg.sharix-app.org"
+USERLIST=["guide_backend","drive_backend","assist_backend","sports_backend","open_backend","guide_webadmin_backend","drive_webadmin_backend","assist_webadmin_backend","sports_webadmin_backend","open_webadmin_backend","guide_tickets_backend","drive_tickets_backend","assist_tickets_backend","sports_tickets_backend","open_tickets_backend"]
+SERVICEADMINLIST=["79999999999","99999999999","79876543210","799999999999"]
+#BOTLIST=["open_template_bot","open_strequest_assigned","open_strequest_inprocess","open_strequest_new","open_strequest_reopened","open_strequest_wontfix","open_strequest_done","open_strequest_duplicate","open_strequest_closed","open_accessrequest_pending","open_accessrequest_accepted","open_accessrequest_declined","open_negrequest_pending","open_negrequest_accepted","open_negrequest_declined","open_servicerequest_template","open_servicerequest_booked","open_servicerequest_assigned","open_servicerequest_accepted","open_servicerequest_pending","open_servicerequest_declined","open_servicerequest_prestart","open_servicerequest_process","open_servicerequest_forcemajeure","open_servicerequest_forcemajeurecancelled","open_servicerequest_done","open_servicerequest_cancelled","open_servicerequest_closed"]
+JSERVER="ej.sharix-app.org"
+PASSWORD="12345"
+PORT=349
+API_URL = "https://testbase.sharix-app.org"
+#AUTH_API_URL = "https://testbase.sharix-app.org/auth/token/login/"
+#REG_API_URL = "https://testbase.sharix-app.org/v1/auth/users/"
+#тут надо указывать еще порт сервера
+
+#первое время пусть пароль будет у всех обработчиков одинаковый, далее надо будет генерировать уникальные связки на основе логина и ключа, указанного в файле.
+
+# бот в конверс
+
+# JID="bottickets@msg.sharix-app.org"
+# PASSWORD="12345!"
+
+for i in range (len(USERLIST)):
+    print(USERLIST[i], hashlib.md5((USERLIST[i]+PASSWORD).encode('utf-8')).hexdigest())
+
+

+ 23 - 3
jsonAndRequest.py

@@ -62,26 +62,41 @@ https://wiki.sharix-app.org/doku.php/open/tech/dev/sharix_open_-_primery_json
 
 #надо адаптировать класс к новому формату JSON
 class Order(object):
-    def __init__(self, ticket, state, id_metaservice, is_global, is_visible, service, service_type, time_placed, time_start=None, time_start_predicted=None, time_finish_predicted=None, time_start_real=None, time_finish_real=None, order_place_start=None, order_place_start_gps=None, order_place_start_real=None, order_place_start_real_gps=None, order_place_finish_predicted=None, order_place_finish_predicted_gps=None, order_place_finish_real=None, order_place_finish_real_gps=None, predicted_price=None, real_price=None, payment_transaction_id=None, rating_id=None, provider=None, provider_screen_name=None, receiver=None, receiver_screen_name=None, client_id=None, resource_id=None):
+    #def __init__(self, ticket, state, id_metaservice, is_global, is_visible, service, service_type, time_placed, time_start=None, time_start_predicted=None, time_finish_predicted=None, time_start_real=None, time_finish_real=None, order_place_start=None, order_place_start_gps=None, order_place_start_real=None, order_place_start_real_gps=None, order_place_finish_predicted=None, order_place_finish_predicted_gps=None, order_place_finish_real=None, order_place_finish_real_gps=None, predicted_price=None, real_price=None, payment_transaction_id=None, rating_id=None, provider=None, provider_screen_name=None, receiver=None, receiver_screen_name=None, client_id=None, resource_id=None):
+    def __init__(self, receivers=None, receivers_names=None, comment=None, tasks=None, journey_places=None, is_with_payment_document=None, ticket=None, status=None, priority=None, title=None, note=None, due_date=None, id_metaservice=None, is_global=None, is_visible=None, service=None, service_type=None, status_changed_date=None, time_placed=None, time_start=None, time_start_predicted=None, time_finish_predicted=None, time_start_real=None, time_finish_real=None, order_place_type=None, order_place_start=None, order_place_start_gps=None, order_place_start_sector=None, order_place_start_real=None, order_place_start_real_gps=None, order_place_finish_predicted=None, order_place_finish_predicted_gps=None, order_place_finish_sector = None, order_place_finish_real = None, order_place_finish_real_gps = None, predicted_price=None, real_price=None, payment_transaction_id=None, rating_id=None, provider=None, provider_screen_name=None, receiver=None, receiver_screen_name=None, client_id=None, client_screen_name=None, resource_id=None, attempts=None, asap=None):
+        self.receivers = receivers
+        self.receivers_names = receivers_names
+        self.comment = comment
+        self.tasks = tasks
+        self.journey_places = journey_places
+        self.is_with_payment_document = is_with_payment_document
         self.ticket = ticket
-        self.state = state
+        self.status = status
+        self.priority = priority
+        self.title = title
+        self.note = note
+        self.due_date = due_date
         self.id_metaservice = id_metaservice
         self.is_global = is_global
         self.is_visible = is_visible
         self.service = service
         self.service_type = service_type
+        self.status_changed_date = status_changed_date
         self.time_placed = time_placed
         self.time_start = time_start
         self.time_start_predicted = time_start_predicted
         self.time_finish_predicted = time_finish_predicted
         self.time_start_real = time_start_real
         self.time_finish_real = time_finish_real
+        self.order_place_type = order_place_type
         self.order_place_start = order_place_start
         self.order_place_start_gps = order_place_start_gps
+        self.order_place_start_sector = order_place_start_sector
         self.order_place_start_real = order_place_start_real
         self.order_place_start_real_gps = order_place_start_real_gps
         self.order_place_finish_predicted = order_place_finish_predicted
         self.order_place_finish_predicted_gps = order_place_finish_predicted_gps
+        self.order_place_finish_sector = order_place_finish_sector
         self.order_place_finish_real = order_place_finish_real
         self.order_place_finish_real_gps = order_place_finish_real_gps
         self.predicted_price = predicted_price
@@ -93,11 +108,14 @@ class Order(object):
         self.receiver = receiver
         self.receiver_screen_name = receiver_screen_name
         self.client_id = client_id
+        self.client_screen_name = client_screen_name
         self.resource_id = resource_id
+        self.attempts = attempts
+        self.asap = asap
 
         #доделать до конца по аналогии с закоммиченным json
     def __str__(self):
-        return "{0}, {1}, {2}, {3}, {4}, {5}, {6},\n{7}, {8}, {9}, {10}, {11}, {12},\n{13}, {14}, {15}, {16}, {17}, {18}, {19}, {20},\n{21}, {22}, {23}, {24},\n{25}, {26}, {27}, {28}, {29}, {30}".format(self.ticket, self.state, self.id_metaservice, self.is_global, self.is_visible, self.service, self.service_type, self.time_placed, self.time_start, self.time_start_predicted, self.time_finish_predicted, self.time_start_real, self.time_finish_real, self.order_place_start, self.order_place_start_gps, self.order_place_start_real, self.order_place_start_real_gps, self.order_place_finish_predicted, self.order_place_finish_predicted_gps, self.order_place_finish_real, self.order_place_finish_real_gps, self.predicted_price, self.real_price, self.payment_transaction_id, self.rating_id,  self.provider, self.provider_screen_name, self.receiver, self.receiver_screen_name, self.client_id, self.resource_id)
+        return "{0}, {1}, {2}, {3}, {4}, {5}, {6},\n{7}, {8}, {9}, {10}, {11}, {12},\n{13}, {14}, {15}, {16}, {17}, {18}, {19}, {20},\n{21}, {22}, {23}, {24},\n{25}, {26}, {27}, {28}, {29}, {30}\n{31}, {32}, {33}, {34}, {35}, {36},\n{37}, {38}, {39}, {40}\n{41}, {42}, {43}, {44}, {45}, {46},\n{47}\n".format(self.receivers, self.receivers_names, self.comment, self.tasks, self.journey_places, self.is_with_payment_document, self.ticket, self.status, self.priority, self.title, self.note, self.due_date, self.id_metaservice, self.is_global, self.is_visible, self.service, self.service_type, self.status_changed_date, self.time_placed, self.time_start, self.time_start_predicted, self.time_finish_predicted, self.time_start_real, self.time_finish_real, self.order_place_type, self.order_place_start, self.order_place_start_gps, self.order_place_start_sector, self.order_place_start_real, self.order_place_start_real_gps, self.order_place_finish_predicted, self.order_place_finish_predicted_gps, self.order_place_finish_sector, self.order_place_finish_real, self.order_place_finish_real_gps, self.predicted_price, self.real_price, self.payment_transaction_id, self.rating_id, self.provider, self.provider_screen_name, self.receiver, self.receiver_screen_name, self.client_id, self.client_screen_name, self.resource_id, self.attempts, self.asap)
         #\n добавляете в местах с пустой строкой в шаблоне
         
 
@@ -181,6 +199,7 @@ def requestGetToken(login, password, url) -> str:
     }
     response = requests.post(url, json=data)
     result = response.json()
+    print (result)
     return result['auth_token']
 #Функция обращения к апи и получение токена
 def createUser(username, phone, password, url) -> str:
@@ -191,6 +210,7 @@ def createUser(username, phone, password, url) -> str:
     } 
     response = requests.post(url, json=data)
     result = response.json()
+    print (result)
     return result
 #Функция обращения к апи и получение списка пользователей
 def requestGetListUser():