def post(self): status_list = list() # parse data logging.info(self.request.get('json')) arr = json.loads(self.request.get('json')) for item in arr["orders"]: # get ids and info delivery_terminal_id = item['venue_id'] delivery_terminal = DeliveryTerminal.get_by_id(delivery_terminal_id) if not delivery_terminal: # old version: got organization id instead of DT id delivery_terminal = DeliveryTerminal.get_any(delivery_terminal_id) delivery_terminal_id = delivery_terminal.key.id() order_id = item['order_id'] order_info = order_info1(order_id, delivery_terminal.iiko_organization_id) if 'httpStatusCode' not in order_info: address = delivery_terminal.address name = delivery_terminal.name # make dict status_list.append({ 'order_id': order_id, 'number': order_info['number'], 'venue_id': delivery_terminal_id, 'status': Order.parse_status(order_info['status']), 'address': address, 'name': name, 'createdTime': order_info['createdTime'] }) else: logging.warning('order %s not found' % order_id) self.render_json({"orders": status_list})
def post(self, delivery_terminal_id): logging.info(self.request.POST) custom_data = None try: custom_data = json.loads(self.request.get('custom_data')) except ValueError: pass bonus_sum = self.request.get('bonus_sum') bonus_sum = float(bonus_sum) if bonus_sum else 0.0 discount_sum = self.request.get('discount_sum') discount_sum = float(discount_sum) if discount_sum else 0.0 customer_id = self.request.get('customer_id') or self.request.get( 'customerId') address = self.request.get('address') comment = self.request.get('comment') binding_id = self.request.get('binding_id') alpha_client_id = self.request.get('alpha_client_id') source = self.request.get('source') delivery_terminal = DeliveryTerminal.get_by_id(delivery_terminal_id) if delivery_terminal: org_id = delivery_terminal.iiko_organization_id else: org_id = delivery_terminal_id company = CompanyNew.get_by_iiko_id(org_id) if not delivery_terminal: delivery_terminal = DeliveryTerminal.get_any(company.iiko_org_id) delivery_terminal_id = delivery_terminal.key.id() response_delivery_terminal_id = delivery_terminal_id customer = get_resto_customer(company, customer_id) set_customer_info(company, customer, self.request.get('name').strip(), self.request.headers, filter_phone(self.request.get('phone')), custom_data) update_customer_id(company, customer) self.order = order = iiko.Order() order.order_id = self.request.get('id') or str(uuid.uuid4()) if source == AUTO_APP_SOURCE: if not company.auto_token: send_error( "order", u"Компания %s не настроена для работы с автоматизацией" % company.app_title, "") return self.send_error( u"Неизвестная системная ошибка, попробуйте позже") order.source = source order.date = datetime.datetime.utcfromtimestamp( int(self.request.get('date'))) order.payment_type = self.request.get('paymentType') str_date = self.request.get('str_date') if str_date: parsed_str_date = parse_str_date(str_date) if parsed_str_date: order.date = parsed_str_date - datetime.timedelta( seconds=company.get_timezone_offset()) else: logging.warning("Failed to parse str_date: %s", str_date) order.date = datetime.datetime.now() + datetime.timedelta( hours=1) if order.date < datetime.datetime.utcnow() and \ ('/2.0 ' in self.request.user_agent or '/2.0.1' in self.request.user_agent): logging.info('new date(str): %s' % order.date) order.date += datetime.timedelta(hours=12) logging.info("ios v2.0 fuckup, adding 12h: %s", order.date) send_confirmation_sms = False if company.iiko_org_id in (CompanyNew.EMPATIKA, CompanyNew.ORANGE_EXPRESS): confirm_by_phone = self.request.get("confirm_by_phone") if confirm_by_phone == "1": comment = u"Клиент просит перезвонить. " + comment elif confirm_by_phone == "0": comment = u"Клиенту будет отправлено СМС-подтверждение. " + comment send_confirmation_sms = True else: pass # old version order.delivery_terminal_id = delivery_terminal_id order.venue_id = company.iiko_org_id gifts = json.loads( self.request.get('gifts')) if self.request.get('gifts') else [] order.customer = customer.key items = prepare_items(company, json.loads(self.request.get('items'))) order.items = items order.initial_sum = order.sum = calc_sum(items, company.iiko_org_id) logging.info("calculated sum: %s, app sum: %s", order.sum, self.request.get('sum')) if company.iiko_org_id in (CompanyNew.DIMASH, CompanyNew.CHAIHANA_LOUNGE): if 'Android' in self.request.user_agent: comment = u"Заказ с Android. " + comment else: comment = u"Заказ с iOS. " + comment is_repeated_order = None if company.iiko_org_id in _FIRST_ORDER_COMMENTS: comment_first, comment_repeated = _FIRST_ORDER_COMMENTS[ company.iiko_org_id] is_repeated_order = orders_exist_for_phone(customer.phone) comment = (comment_repeated if is_repeated_order else comment_first) + comment order.comment = comment delivery_type = self.request.get_range('deliveryType') order.is_delivery = delivery_type == DeliveryType.DELIVERY if order.is_delivery: if not address: self.abort(400) try: order.address = json.loads(address) prepare_address(order) except Exception as e: logging.exception(e) self.abort(400) order.delivery_type = None for company_delivery_type in company.delivery_types: company_delivery_type = company_delivery_type.get() if company_delivery_type.delivery_id == delivery_type: order.delivery_type = company_delivery_type if order.venue_id == CompanyNew.KUKSU: kuksu_delivery.check_and_add_delivery(company, order) # this resets order.delivery_terminal_id if it is delivery (not takeout) order_dict = prepare_order(order, customer, order.payment_type) if delivery_terminal_id != order.delivery_terminal_id: delivery_terminal_id = order.delivery_terminal_id delivery_terminal = DeliveryTerminal.get_by_id(delivery_terminal_id) \ if delivery_terminal_id else None validation_result = validate_order(company, delivery_terminal, order, customer) if not validation_result['valid']: return self.send_error(validation_result['errors'][0]) pre_check_result = pre_check_order(company, order_dict) if 'code' in pre_check_result: logging.warning('iiko pre check failed') msg = pre_check_result["description"] or pre_check_result["message"] send_error("iiko", "iiko pre check failed", msg) self.abort(400) order.discount_sum = 0.0 order.bonus_sum = 0.0 if company.is_iiko_system: create_or_update_customer(company, {'phone': customer.phone}) success = set_discounts_bonuses_gifts(order, order_dict, discount_sum, bonus_sum, gifts) if not success: self.abort(409) order.sum -= order.bonus_sum + order.discount_sum elif company.iiko_org_id == CompanyNew.CHAIHANA_LOUNGE: assert is_repeated_order is not None if is_repeated_order: order.discount_sum = 0.05 * order.sum else: order.discount_sum = 0.25 * order.sum if order.payment_type == PaymentType.COURIER_CARD: for payment in order_dict['order']['paymentItems']: if payment['paymentType']['code'] == 'CARD': payment['sum'] -= order.discount_sum if order.payment_type == PaymentType.CASH and not order.is_delivery: payments_list = order_dict['order']['paymentItems'] for payment in payments_list: if payment['paymentType']['code'] == 'CASH': payments_list.remove(payment) break # pay after pre check if order.payment_type == PaymentType.CARD: binding_id = check_binding_id(company, alpha_client_id, binding_id) success, result = create_payment(company, delivery_terminal, order, alpha_client_id) if not success: self.send_error(result) return order.alfa_order_id = result order.put() success, result = perform_payment(company, delivery_terminal, order, order_dict, order.alfa_order_id, binding_id) if not success: self.send_error(u"Не удалось произвести оплату. " + result) return result = place_order(company, order_dict) if 'code' in result.keys(): logging.error('iiko failure') if order.payment_type == PaymentType.CARD: # return money return_result = get_back_blocked_sum(company, delivery_terminal, order.alfa_order_id) logging.info('return') logging.info(return_result) msg = result["description"] or result["message"] send_error("iiko", "iiko place order failed", msg) self.response.set_status(400) return self.render_json(result) customer.customer_id = result['customerId'] customer.put() order.customer = customer.key client_info_id = self.request.get_range('user_data_id') if client_info_id: client_info = ClientInfo.get_by_id(client_info_id) if client_info and client_info.customer != customer.key: client_info.customer = customer.key client_info.put() order.order_id = result['orderId'] order.number = result['number'] order.set_status(result['status']) order.created_in_iiko = parse_iiko_time(result['createdTime'], company) order.put() try: send_order_email(order, customer, company) except DownloadError: logging.warning('mandrill is not responsed') if send_confirmation_sms: countdown = random.randint(120, 420) # make it realistic deferred.defer(send_confirmation, order.key, _countdown=countdown) response_items = order.items if company.iiko_org_id == CompanyNew.COFFEE_CITY: response_items = json.loads(json.dumps(order.items)) for item in response_items: fix_modifiers_by_own.remove_modifiers_from_item(item) resp = { 'customer_id': customer.customer_id, 'order': { 'order_id': order.order_id, 'resto_id': order.key.id(), 'status': order.status, 'items': response_items, 'sum': order.sum, 'payments': order_dict['order']['paymentItems'], # it was added 'number': order.number, 'venue_id': response_delivery_terminal_id, 'address': order.address, 'date': int(self.request.get('date')), }, 'error': False, 'error_code': 0, } logging.info(resp) delete_iiko_customer_from_memcache(company.iiko_org_id, customer.phone) self.render_json(resp)
def get(self): client_id = self.request.get('client_id') org_id = self.request.get('organisation_id') overall_history = [] company = CompanyNew.get_by_id(int(org_id)) client = Customer.customer_by_customer_id(client_id) if client: response = get_history_by_phone(client.phone, company.iiko_org_id) history = [] if "customersDeliveryHistory" in response: for customer_info in response["customersDeliveryHistory"]: history.extend(customer_info["deliveryHistory"]) else: response = get_history(client_id, company.iiko_org_id) history = response.get("historyOrders", []) for delivery_terminal in DeliveryTerminal.get_any( company.iiko_org_id), : orders_history = list() if history: for order in history: items_list = list() gift_list = list() for order_items in order['items']: item = { 'sum': order_items['sum'], 'amount': order_items['amount'], 'name': order_items['name'], 'modifiers': order_items['modifiers'], 'id': order_items['id'], } if company.iiko_org_id == CompanyNew.COFFEE_CITY: fix_modifiers_by_own.remove_modifiers_from_item( item) if order_items['sum'] != 0: items_list.append(item) else: gift_list.append(item) address = {} if order['address']: address = { 'city': order['address']['city'], 'street': order['address']['street'], 'home': order['address']['home'], 'apartment': order['address']['apartment'], 'housing': order['address']['housing'], 'entrance': order['address']['entrance'], 'floor': order['address']['floor'], } resto_order = Order.order_by_id(order['orderId']) if resto_order: resto_order_id = resto_order.key.id() resto_status = resto_order.status resto_payment_type = resto_order.payment_type resto_delivery_terminal_id = resto_order.delivery_terminal_id else: resto_order_id = resto_status = resto_payment_type = resto_delivery_terminal_id = None orders_history.append({ 'self': order['isSelfService'], 'order_id': order['orderId'], 'number': order['number'], 'address': address, # 'order_organization':order['organizationId'], 'date': time.mktime( datetime.strptime( order['date'], "%Y-%m-%d %H:%M:%S").timetuple()), # 'order_current_date': current_time, 'phone': order['phone'], 'discount': order['discount'], 'sum': order['sum'], 'items': items_list, 'gifts': gift_list, 'venue_id': resto_delivery_terminal_id or delivery_terminal.key.id(), 'resto_id': resto_order_id, 'status': resto_status, 'payment_type': resto_payment_type, }) overall_history.append({ 'venue_id': delivery_terminal.key.id(), 'address': delivery_terminal.address, 'name': delivery_terminal.name, 'local_history': orders_history }) self.render_json({'history': overall_history})
def prepare_order(order, customer, payment_type): company = CompanyNew.get_by_iiko_id(order.venue_id) local_date = order.date + timedelta(seconds=company.get_timezone_offset()) obj = { 'restaurantId': order.venue_id, 'organization': order.venue_id, 'customer': { 'name': customer.name, 'phone': customer.phone, }, 'order': { 'id': order.order_id, 'date': local_date.strftime('%Y-%m-%d %H:%M:%S'), 'isSelfService': 0 if order.is_delivery else 1, 'fullSum': order.sum, 'paymentItems': [{ 'paymentType': { 'code': '', 'name': 'not iiko.Net' }, 'sum': order.sum, "combinatable": True, 'isProcessedExternally': 0 }], 'phone': customer.phone, 'items': order.items, 'comment': order.comment, 'address': { 'home': 0 } } } if company.is_iiko_system: obj['order']['paymentItems'].append({ "sum": 0.0, 'paymentType': { "code": get_iikonet_payment_type(order), "name": "iiko.Net", "comment": "", "combinatable": True, }, "additionalData": json.dumps({ "externalIdType": "PHONE", "externalId": customer.phone }), "isProcessedExternally": False, "isPreliminary": True, "isExternal": True, }) if customer.customer_id: obj['customer']['id'] = customer.customer_id if not order.is_delivery: obj['deliveryTerminalId'] = order.delivery_terminal_id else: order.delivery_terminal_id = None if order.venue_id == CompanyNew.ORANGE_EXPRESS: dt_mapping = { u"Одинцово": "2b20fde1-727f-e430-013e-203bb2e09905", u"Егорьевск": "7658baf0-cc65-28b5-014b-7cde6614cfbe", u"Подольск": "e0a67a59-c018-2c9c-0149-893d7b97148e", u"Климовск": "e0a67a59-c018-2c9c-0149-893d7b97148e", u"Домодедово": "2d163ab4-ce5d-e5cf-014b-84e547cfdf79", u"Авиагородок": "1bb4d840-045f-e28c-014f-b6a61cea9a39", } obj['deliveryTerminalId'] = dt_mapping.get(order.address.get('city')) elif order.venue_id == CompanyNew.PANDA: #obj['deliveryTerminalId'] = "9d55b8d9-7b71-aa53-0144-4da56c249760" # DOSTAVKA48 obj['deliveryTerminalId'] = "12c99191-4e48-67cc-014d-0ef17725d974" # PANDA elif order.venue_id in (CompanyNew.BURGER_CLUB, CompanyNew.CHAIHANA_LOUNGE): obj['deliveryTerminalId'] = DeliveryTerminal.get_any(order.venue_id).key.id() customer_id = customer.customer_id if customer_id: obj['customer']['id'] = customer_id if order.is_delivery: obj['order']['address'] = order.address if payment_type: typ = company.get_payment_type(payment_type) obj['order']['paymentItems'][0]['paymentType']['code'] = typ.iiko_uuid if typ.type_id == 2: obj['order']['paymentItems'][0].update({ 'isProcessedExternally': True, 'isExternal': True, 'isPreliminary': True }) try: if order.delivery_type and order.delivery_type.iiko_uuid: obj['order']['orderTypeId'] = order.delivery_type.iiko_uuid except AttributeError: logging.warning("No order.delivery_type in prepare_order (maybe CAT mock_order)") return obj