import json import requests import config import ast import logging import loggingConfig import pprint # Форматирование текста в human readable формате import sys #Тестовый класс User и Address (ВАЖНО!!!) поля классов должны называться также как и поля json объекта ''' #Full json order example https://wiki.sharix-app.org/doku.php/open/tech/dev/sharix_open_-_primery_json { "ticket": 123, "status": 111, "priority": 1, (фишка для сортировки) "title": "123", "note": "123", (чтото похожее на json для техподдержки) "due_date": 2023-05-15T17:16:22.955601Z, (для очистка старых заявок, чтобы система не переполнялась) "id_metaservice": 1, "is_global": false, "is_visible": false, "service": 1, "service_type": 1, "status_changed_date": "2023-05-15T17:16:22.955601Z", (для техподдержки когда было изменено) "time_placed": "2023-05-15T16:40:32.179777Z", "time_start": "2023-05-15T16:40:32.179777Z", (когда долже наначаться по заявке) "time_start_predicted": "2023-05-15T16:40:32.179777Z", "time_finish_predicted": "2023-05-15T16:40:32.179777Z", "time_start_real": "2023-05-15T16:40:32.179777Z", () "time_finish_real": "2023-05-15T16:40:32.179777Z", "order_place_type": "address", "order_place_start": "р-н Беговой", "order_place_start_gps": "55.751941, 37.607513", "order_place_start_sector": 4, "order_place_start_real": "р-н Беговой", "order_place_start_real_gps": "55.751941, 37.607513", "order_place_finish_predicted": "р-н Мещанский", "order_place_finish_predicted_gps": "55.751941, 37.607513", "order_place_finish_sector": 4, "order_place_finish_real": "р-н Мещанский", "order_place_finish_real_gps": "55.751941, 37.607513", "predicted_price": 1000, "real_price": 1001, "payment_transaction_id": 1, (локальное, для оплаты) "rating_id": 1, "provider": 1, (приёмник, тот, кто приезжает) "provider_screen_name": "Vasya Ispolnitelev", "receiver": 1, "receiver_screen_name": "Marfa Clientovna", "client_id": 1, (инициатор - клиент - источник) "client_screen_name": "Fedor Client", "resource_id": 1, (машина привязанная к заказу, в друге - помещение (то, что предоставляют компании партнёры)) "attempts": null (клиенту не хочется бесконечно ждать. Кол-во попыток для какойто операции) } ''' #надо адаптировать класс к новому формату 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): self.ticket = ticket self.state = state self.id_metaservice = id_metaservice self.is_global = is_global self.is_visible = is_visible self.service = service self.service_type = service_type 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_start = order_place_start self.order_place_start_gps = order_place_start_gps 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_real = order_place_finish_real self.order_place_finish_real_gps = order_place_finish_real_gps self.predicted_price = predicted_price self.real_price = real_price self.payment_transaction_id = payment_transaction_id self.rating_id = rating_id self.provider = provider self.provider_screen_name = provider_screen_name self.receiver = receiver self.receiver_screen_name = receiver_screen_name self.client_id = client_id self.resource_id = resource_id #доделать до конца по аналогии с закоммиченным 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) #\n добавляете в местах с пустой строкой в шаблоне #ticket json example ''' { "id": 2, "status": 111, "created_date": "2023-05-15", "status_changed_date": "2023-05-15T17:16:22.955601Z", "priority": 0, "title": "Test", "note": "{\n \n \"ticket\": 1,\n \"state\": 1,\n \"id_metaservice\": 1,\n \"is_global\": false,\n \"is_visible\": false,\n \"service\": 1,\n \"service_type\": 1,\n\n \"time_placed\": 1}" "due_date": "2023-05-15", "task_list": 10, "created_by": 1, "type": 1, "assigned_to": 1 } ''' #ticket minimal example ''' { "id": 2, "status": 111, "created_date": "2023-05-15", "status_changed_date": "2023-05-15T17:16:22.955601Z", "priority": 0, "title": null, "note": null, "due_date": null, "task_list": 10, "created_by": 1, "type": 1, "assigned_to": null } ''' orderJson = { "ticket": 123, "status": 111, "priority": 1, "title": "123", "note": "123", "due_date": "2000-01-01", "id_metaservice": 1, "is_global": False, "is_visible": False, "service": 1, "service_type": 1, "status_changed_date": "2023-05-15T17:16:22.955601Z", "time_placed": "2023-05-15T16:40:32.179777Z", "time_start": "2023-05-15T16:40:32.179777Z", "time_start_predicted": "2023-05-15T16:40:32.179777Z", "time_finish_predicted": "2023-05-15T16:40:32.179777Z", "time_start_real": "2023-05-15T16:40:32.179777Z", "time_finish_real": "2023-05-15T16:40:32.179777Z", "order_place_type": "address", "order_place_start": "р-н Беговой", "order_place_start_gps": "55.751941, 37.607513", "order_place_start_sector": 4, "order_place_start_real": "р-н Беговой", "order_place_start_real_gps": "55.751941, 37.607513", "order_place_finish_predicted": "р-н Мещанский", "order_place_finish_predicted_gps": "55.751941, 37.607513", "order_place_finish_sector": 4, "order_place_finish_real": "р-н Мещанский", "order_place_finish_real_gps": "55.751941, 37.607513", "predicted_price": 1000, "real_price": 1001, "payment_transaction_id": 1, "rating_id": 1, "provider": 1, "provider_screen_name": "Vasya Ispolnitelev", "receiver": 1, "receiver_screen_name": "Marfa Clientovna", "client_id": 1, "client_screen_name": "Fedor Client", "resource_id": None, "attempts": None, "state": "ok" } class OrderTicket(object): def __init__(self, id, status, created_date, status_changed_date, priority, title=None, note=None, due_date=None, task_list=None, created_by=None, type=None, assigned_to=None): self.id = id self.status = status self.created_date = created_date self.status_changed_date = status_changed_date self.priority = priority self.title = title self.note = note self.due_date = due_date self.task_list = task_list self.created_by = created_by self.type = type self.assigned_to = assigned_to def __str__(self): return "{0}, {1}, {2}, {3}, {4}, {5}, {6},\n{7}, {8}, {9}, {10}, {11}\n".format(self.id, self.status, self.created_date, self.status_changed_date, self.priority, self.title, self.note, self.due_date, self.task_list, self.created_by, self.type, self.assigned_to) #Функция преобразования json в объект класса Order def jsonToOrder(jsonstring) -> Order: jsonObj = json.loads(jsonstring) # print(jsonObj) logging.debug(jsonObj) u = Order(**jsonObj) return u #Функция преобразования json в объект класса OrderTicket def jsonToOrderTicket(jsonstring) -> OrderTicket: # print (jsonstring) logging.debug(jsonstring) jsonObj = json.loads(jsonstring) # print(jsonObj) logging.debug(jsonObj) u = OrderTicket(**jsonObj) return u #Функция обращения к апи и получение токена def requestGetToken(login, password, url) -> str: #login = "79876543210" #password = "admin12345@" #url = "https://user.sharix-app.org/auth/token/login/" data = { "password": password, "phone_number": login } response = requests.post(url, json=data) result = response.json() return result['auth_token'] #Функция обращения к апи и получение токена def createUser(username, phone, password, url) -> str: data = { "username": username, "phone_number": phone, "password": password } response = requests.post(url, json=data) result = response.json() return result #Функция обращения к апи и получение списка пользователей def requestGetListUser(): auth_token=requestGetToken() # print(auth_token) logging.debug(f"Auth token: {auth_token}") headers = {'Authorization': f'Token {auth_token}'} url = 'https://user.sharix-app.org/platform/api/sharix-users/' response = requests.get(url, headers=headers) # print(response) logging.debug(response) # print(response.json()) logging.debug(f"Auth token: {response.json()}") def requestGetList(auth_token, url): #auth_token=requestGetToken(login, password, url) #print(auth_token) headers = {'Authorization': f'Token {auth_token}'} #url = 'https://user.sharix-app.org/platform/api/sharix-users/' response = requests.get(config.API_URL+"/tickets/api/tickets/?list_id=10", headers=headers) #response = requests.get(config.API_URL+"/metaservicesynced/api/orders/", headers=headers) #print(response) #return response.json() #print(response.json()) logging.debug(pprint.pformat(response.json())) ordertext=response.json() startlist = [] if not ordertext: # print("Empty array") logging.info("Empty array") else: for i in ordertext: # print (i, "PROCESSING") logging.debug(f"\"PROCESSING\"\n{pprint.pformat(i)}") try: orderticket = OrderTicket(**i) # print(i, "ORDER ", orderticket) # logging.debug(f"{pprint.pformat(i)}, \"ORDER\" {orderticket}") startlist.append(orderticket) logging.debug(f"\"ORDER\"\n{orderticket}") except Exception as ex: # print(ex) logging.error("Exception occurred", exc_info=True) # print (startlist) logging.debug("Startlist: " + pprint.pformat(startlist)) #if ordertext is not None: # for order in ordertext: # print (order) # strorder = str(order).replace("'", '"') # strorder = strorder.replace("None", 'null') # #parsed_json = ast.literal_eval(order) # #print (parsed_json) # orderObj = jsonToOrderTicket(strorder) # print (orderObj) # startlist.append(orderObj) # #bot.bot_log(str(datetime.now())+"Заказ успешно добавлен в очередь обработки\n") #print (orderticket) return startlist def update_partially(url, field, value, headers): """ Изменить конкретное поле """ return def create(url, json, headers) -> str: """ Создать элемент с помощью POST Возвращает: json строку с данными созданного элемента или ошибки Статус выполнения: проверена работа на локальном сервере """ response = requests.post(url, json=json, headers=headers) if response.status_code != 201: logging.error(response.json()) return return response.json() def createOrder(url, order, headers): """ Создать заказ Возвращает: json строку с данными созданного заказа или ошибки Статус выполнения: проверена работа на локальном сервере """ # Конвертировать объект в json try: json = vars(order) except Exception as e: logging.error("Ошибка конвертации в json", exc_info=True) return logging.info("Успешная конвертация в json") logging.debug(pprint.pformat(json)) # Создать заказ # none - ошибка создания, json строка - успешное создание created_json = create(url, json, headers) # Проверить успешность создания if created_json: logging.info("Заказ успешно создан.") return created_json logging.info("Ошибка создания заказа.") return def testCreateOrder(): """ Код для тестирования создания заказа """ test_token = "4a9333794bb8296083aaa898954affe6a74e6a20" test_headers = {'Authorization': f'Token {test_token}'} try: order1 = Order( ticket=1, state=1, id_metaservice=1, is_global=1, is_visible=1, service=1, service_type=1, time_placed="2000-01-01", order_place_finish_predicted_gps="55.751941, 37.607513" ) except Exception as e: logging.error("order wasn't created", exc_info=True) sys.exit() else: logging.info("order created successfully") createOrder("http://127.0.0.1:8000/openlocal/api/orderslocal/", order1, test_headers) ''' https://testbase.sharix-app.org/openlocal/api/orderslocal/ уже есть: чтение создать заказ редактировать заказ целиком редактировать отдельное поле под каждую операцию отдельный запрос (универсальная ф-ция: передаётся название поля и значение) функционал: подобрать, отправлять vs создать вложенные json убрать (сделать одноуровневым) вернуть attempts в json xmpppy как отправлять сообшение в группу? '''