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): token = self.request.get("token") admin = Admin.query(Admin.token == token).get() if not admin: self.abort(401) delivery_terminal = DeliveryTerminal.get_by_id( admin.delivery_terminal_id) if not delivery_terminal: self.send_error(u'Вы не привязаны к точке') stop_list = json.loads(self.request.get('stop_list')) for item_id in stop_list.get('stopped'): item = get_product_from_menu(admin.company_id, product_id=item_id) if not item: return self.send_error(u'Продукт не найден') if item_id in delivery_terminal.item_stop_list: return self.send_error(u'Продукт %s уже в стоп-листе' % item.get('name', '')) delivery_terminal.item_stop_list.append(item_id) for item_id in stop_list.get('recovered'): item = get_product_from_menu(admin.company_id, product_id=item_id) if not item: return self.send_error(u'Продукт не найден') if item_id not in delivery_terminal.item_stop_list: return self.send_error(u'Продукт %s еще не в стоп-листе' % item.get('name', '')) delivery_terminal.item_stop_list.remove(item_id) delivery_terminal.put() self.render_json({'success': True})
def get(self): companies = Company.query().fetch() for c in companies: IikoApiLogin(id=c.name, password=c.password).put() venue = None dct = { k: getattr(c, k) for k in Company._properties if k not in ('name', 'password') } CompanyNew(id=c.key.id(), menu=venue.menu, address=venue.address, latitude=venue.latitude, longitude=venue.longitude, payment_types=venue.payment_types, iiko_login=c.name, iiko_org_id=venue.venue_id, **dct).put() dts = get_delivery_terminals(venue.venue_id) for dt in dts: DeliveryTerminal(id=dt['deliveryTerminalId'], active=dt['deliveryTerminalId'] != 'd7fd5599-814a-79be-0146-b83a4192096f', phone=c.phone or '', company_id=c.key.id(), iiko_organization_id=venue.venue_id, name=dt['deliveryRestaurantName'], address=dt['address'], location=GeoPt(venue.latitude, venue.longitude)).put()
def get(self): org_id = self.request.get("selected_company") if org_id == '0': org_id = None start, end = self.get_date_range() terminals = {} for terminal in (DeliveryTerminal.query( DeliveryTerminal.iiko_organization_id == org_id).fetch() if org_id else DeliveryTerminal.query().fetch()): terminals[terminal.key.id()] = terminal.name query = iiko.Order.query(iiko.Order.date > start, iiko.Order.date < end) if org_id: query = query.filter(iiko.Order.venue_id == org_id) orders = query.fetch() for order in orders: order.status_str = iiko.Order.STATUS_MAPPING[order.status][0] order.venue_name = iiko.CompanyNew.get_by_iiko_id( order.venue_id).app_title order.terminal_name = terminals.get(order.delivery_terminal_id, u'Не найдено') customer = order.customer.get() if order.customer else None order.customer_id = customer.customer_id if customer else '-' order.customer_name = customer.name if customer else '-' order.customer_phone = customer.phone if customer else '-' order.new_items = [] for item in order.items: order.new_items.append({ 'name': item['name'], 'amount': item['amount'] }) if order.payment_type == PaymentType.CASH: order.payment_name = 'CASH' elif order.payment_type == PaymentType.CARD: order.payment_name = 'CARD' else: order.payment_name = 'UNKNOWN' values = { 'companies': iiko.CompanyNew.query().fetch(), 'orders': orders, 'chosen_company': iiko.CompanyNew.get_by_iiko_id(org_id), 'start': start, 'end': end } self.render_report('orders', values)
def get(self, delivery_terminal_id): delivery_terminal = DeliveryTerminal.get_by_id(delivery_terminal_id) if delivery_terminal: iiko_org_id = delivery_terminal.iiko_organization_id else: iiko_org_id = delivery_terminal_id return self.render_json( {"types": CompanyNew.get_payment_types(iiko_org_id)})
def get(self): token = self.request.get("token") admin = Admin.query(Admin.token == token).get() if not admin: self.abort(401) self.render_json({ 'dynamic': DeliveryTerminal.get_by_id( admin.delivery_terminal_id).dynamic_dict() })
def get(self, company_id): company = CompanyNew.get_by_id(int(company_id)) qry = DeliveryTerminal.query( DeliveryTerminal.company_id == company.key.id()) active_only = 'all' not in self.request.params if active_only: qry = qry.filter(DeliveryTerminal.active == True) venues = qry.fetch() self.render_json({'venues': [venue.to_dict() for venue in venues]})
def _load_delivery_terminals(company): iiko_delivery_terminals = get_delivery_terminals(company) dts = map(lambda iiko_delivery_terminal: DeliveryTerminal.get_or_insert( iiko_delivery_terminal['deliveryTerminalId'], company_id=company.key.id(), iiko_organization_id=company.iiko_org_id, active=True, name=iiko_delivery_terminal['deliveryRestaurantName'], phone=company.phone, address=iiko_delivery_terminal['address'], location=ndb.GeoPt(company.latitude, company.longitude) ), iiko_delivery_terminals) ndb.put_multi(dts) return dts
def get(self, delivery_terminal_id): delivery_terminal = DeliveryTerminal.get_by_id(delivery_terminal_id) if delivery_terminal: iiko_org_id = delivery_terminal.iiko_organization_id else: iiko_org_id = delivery_terminal_id force_reload = "reload" in self.request.params filtered = "all" not in self.request.params menu = get_menu(iiko_org_id, force_reload=force_reload, filtered=filtered) if iiko_org_id == CompanyNew.COFFEE_CITY: menu = fix_syrop.set_syrop_modifiers(menu) menu = fix_modifiers_by_own.remove_modifiers(menu) add_additional_categories(CompanyNew.get_by_iiko_id(iiko_org_id), menu) self.render_json({'menu': menu})
def post(self): company_id = self.request.get_range('company_id') if not company_id: delivery_terminal_id = self.request.get('venue_id') company_id = DeliveryTerminal.get_by_id(delivery_terminal_id).company_id company = CompanyNew.get_by_id(company_id) if company.iiko_org_id not in (CompanyNew.COFFEE_CITY, CompanyNew.EMPATIKA): self.render_error("Unknown company") return customer_id = self.request.get('customer_id') phone = filter_phone(self.request.get('phone')) provider = self.request.get('provider') social_id = self.request.get('social_id') # 1: check if this social id was already used same_social_id = CATSocialId.query(CATSocialId.venue_id == company.iiko_org_id, CATSocialId.provider == provider, CATSocialId.social_id == social_id).get() if same_social_id: self.render_error(u"Данная учетная запись в социальной сети уже была привязана") return # 2: get customer info from iiko (this attempts to get customer_id if we only have phone) if not customer_id: iiko_customer = get_customer_by_phone(company, phone) if 'httpStatusCode' in iiko_customer: iiko_customer = {'phone': phone, 'balance': 0} customer_id = iiko_customer.get('id') else: iiko_customer = get_customer_by_id(company, customer_id) # 3: if we got customer_id, check if this customer already has an account of this provider if customer_id: same_customer_and_provider = CATSocialId.query(CATSocialId.venue_id == company.iiko_org_id, CATSocialId.customer_id == customer_id, CATSocialId.provider == provider).get() if same_customer_and_provider: self.render_error(u"Вы уже привязывали учетную запись в этой социальной сети") return # 4: add points iiko_customer['balance'] += 20 customer_id = create_or_update_customer(company, iiko_customer) CATSocialId(venue_id=company.iiko_org_id, customer_id=customer_id, provider=provider, social_id=social_id).put() self.render_json({'customer_id': customer_id, 'balance': iiko_customer['balance']})
def get(self, company_id): company = CompanyNew.get_by_id(int(company_id)) stop_lists = get_company_stop_lists(company) venues = DeliveryTerminal.query( DeliveryTerminal.company_id == company.key.id(), DeliveryTerminal.active == True).fetch() item_id = self.request.get("item_id") result = {} for venue in venues: if venue.key.id() not in stop_lists or \ item_id not in stop_lists[venue.key.id()]: remainders = None else: remainders = stop_lists[venue.key.id()][item_id] if remainders < 0: remainders = 0 result[venue.key.id()] = remainders self.render_json({'item_id': item_id, 'remainders': result})
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 get_dt(dt_id): if not dt_id: return None if dt_id not in dt_map: dt_map[dt_id] = DeliveryTerminal.get_by_id(dt_id) return dt_map[dt_id]
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
def post(self): for k, v in self.request.POST.items(): logging.debug("%s: %s", k, v) delivery_terminal_id = self.request.get('venue_id') delivery_terminal = DeliveryTerminal.get_by_id(delivery_terminal_id) if delivery_terminal: company = CompanyNew.get_by_id(delivery_terminal.company_id) else: company = CompanyNew.get_by_iiko_id(delivery_terminal_id) customer = get_resto_customer(company, self.request.get('customer_id')) phone = self.request.get('phone') if company.iiko_org_id == CompanyNew.COFFEE_CITY: logging.debug("wow such coffee so city") create_or_update_customer(company, {'phone': filter_phone(phone)}) set_customer_info(company, customer, self.request.get('name').strip(), self.request.headers, filter_phone(phone)) update_customer_id(company, customer) if not phone: return self.send_error(u'Введите номер телефона') phone = filter_phone(phone) valid, error = check_modifiers_amount( json.loads(self.request.get('items')), company.iiko_org_id) if not valid: return self.send_error(error) items = prepare_items(company, json.loads(self.request.get('items'))) order = iiko.Order() order.date = datetime.datetime.fromtimestamp( self.request.get_range('date')) order.venue_id = company.iiko_org_id order.delivery_terminal_id = delivery_terminal_id order.sum = float(self.request.get('sum')) order.items = items delivery_type = self.request.get_range('deliveryType') order.is_delivery = delivery_type == DeliveryType.DELIVERY if order.is_delivery: order.address = {'home': '0'} 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 order_dict = prepare_order(order, customer, None) validation_result = validate_order(company, delivery_terminal, order, customer) if not validation_result['valid']: return self.send_error(validation_result['errors'][0], order.items) if company.is_iiko_system and order.items: promos = get_order_promos(order, order_dict) set_discounts(order, order_dict['order'], promos) promos = get_order_promos(order, order_dict) discount_sum = order.discount_sum max_bonus_payment = promos['maxPaymentSum'] if company.iiko_org_id == CompanyNew.BON_APPETIT: max_bonus_payment = 0.0 gifts = [] if promos.get('availableFreeProducts'): for gift in promos['availableFreeProducts']: gifts.append({ 'id': gift['id'], 'code': gift['code'], 'name': gift['name'], 'images': gift['images'], 'weight': gift['weight'] }) accumulated_gifts = 0 if company.iiko_org_id in (CompanyNew.EMPATIKA, ): free_codes = CAT_FREE_CUP_CODES[company.iiko_org_id] free_cup = get_product_from_menu(company.iiko_org_id, product_code=free_codes[0]) FREE_CUP_IN_ORDER = 10 CUPS_IN_ORDER = FREE_CUP_IN_ORDER * CUPS_BEFORE_FREE_CUP mock_order = copy.deepcopy(order) mock_order.sum = free_cup['price'] * CUPS_IN_ORDER mock_order.items = prepare_items( company, [{ 'id': free_cup['productId'], 'name': free_cup['name'], 'amount': CUPS_IN_ORDER }]) mock_order_dict = prepare_order(mock_order, customer, None) mock_promos = get_order_promos(mock_order, mock_order_dict) set_discounts(mock_order, mock_order_dict['order'], mock_promos) accumulated_gifts = int(mock_order.discount_sum / free_cup['price']) - FREE_CUP_IN_ORDER discount_gifts = 0 if company.iiko_org_id in (CompanyNew.EMPATIKA, ): for item in order.items: free_codes = CAT_FREE_CUP_CODES[company.iiko_org_id] if item['code'] in free_codes: if item.get('discount_sum'): price = (item['sum'] + item['discount_sum']) / item['amount'] discount_gifts += item['discount_sum'] / price item['amount'] = int(item['amount']) else: discount_sum = 0.0 max_bonus_payment = 0.0 gifts = [] accumulated_gifts = discount_gifts = 0 if company.iiko_org_id == CompanyNew.CHAIHANA_LOUNGE: if orders_exist_for_phone(phone): discount_sum = 0.05 * order.sum else: discount_sum = 0.25 * order.sum delivery_sum = 0 if company.iiko_org_id == CompanyNew.KUKSU: if kuksu_delivery.check_delivery(order): delivery_sum = kuksu_delivery.get_delivery_sum() iiko_customer = get_customer_by_id(company, customer.customer_id) result = { "order_discounts": discount_sum, "delivery_sum": delivery_sum, "max_bonus_payment": max_bonus_payment if max_bonus_payment > 0 else 0, "gifts": gifts, "error": False, "accumulated_gifts": max(0, int(accumulated_gifts - discount_gifts)), "items": order.items, "balance": iiko_customer.get('balance', 0.0) } return self.render_json(result)