def close(order): company = CompanyNew.get_by_iiko_id(order.venue_id) if company.auto_token and order.source == AUTO_APP_SOURCE: close_order(order, company.auto_token) if order.payment_type == PaymentType.CARD: delivery_terminal = DeliveryTerminal.get_by_id(order.delivery_terminal_id) \ if order.delivery_terminal_id else None pay_result = pay_by_card(company, delivery_terminal, order.alfa_order_id, 0) logging.info("pay result: %s" % str(pay_result)) success = 'errorCode' not in pay_result.keys() or str( pay_result['errorCode']) == '0' if not success: logging.warning("pay failed") return if company.is_iiko_system: bonus = SharedBonus.query( SharedBonus.recipient == order.customer, SharedBonus.status == SharedBonus.READY).get() if bonus: taskqueue.add(url='/single_task/bonus/activate', params={'order_id': order.order_id}) order_user_agent = order.customer.get().user_agent if company.review_enable and supports_review(company.iiko_org_id, order_user_agent): taskqueue.add(url='/single_task/push/review', params={'order_id': order.order_id}, countdown=60 * 30) send_order_status_push(order)
def get_venue_promos(org_id): if org_id in HARDCODED_PROMOS: return HARDCODED_PROMOS[org_id] url = '/organization/%s/marketing_campaigns' % org_id company = CompanyNew.get_by_iiko_id(org_id) if not company.is_iiko_system: return [] promos = json.loads(get_request(company, url, {}, force_platius=True)) result = [] for promo in promos: if not promo['name']: continue promo_start = promo_end = None if promo['start']: promo_start = datetime.strptime(promo['start'], '%Y-%m-%d') if datetime.now() < promo_start: continue if promo['end']: promo_end = datetime.strptime(promo['end'], '%Y-%m-%d') if datetime.now() > promo_end: continue result.append({ 'id': promo['id'], 'name': promo['name'] if promo['name'] else '', 'description': promo['description'] if promo['description'] else '', 'image_url': promo['imageUrl'], 'display_type': 3, 'start': (promo_start - datetime(1970, 1, 1)).total_seconds() if promo_start else None, 'end': (promo_end - datetime(1970, 1, 1)).total_seconds() if promo_end else None }) return result
def order_info(order): company = CompanyNew.get_by_iiko_id(order.venue_id) result = get_request(company, '/orders/info', { 'requestTimeout': 30, 'organization': order.venue_id, 'order': order.order_id }) return json.loads(result)
def get_history_by_phone(phone, org_id): company = CompanyNew.get_by_iiko_id(org_id) result = get_request(company, '/orders/deliveryHistoryByPhone', { 'organization': org_id, 'phone': phone }) obj = json.loads(result) return obj
def get_history(client_id, org_id): company = CompanyNew.get_by_iiko_id(org_id) result = get_request(company, '/orders/deliveryHistory', { 'organization': org_id, 'customer': client_id, 'requestTimeout': 20 }) obj = json.loads(result) return obj
def order_info1(order_id, org_id): company = CompanyNew.get_by_iiko_id(org_id) result = get_request(company, '/orders/info', { 'requestTimeout': 30, 'organization': org_id, 'order': order_id }) logging.info(result) return json.loads(result)
def do_load(order, order_id, org_id, iiko_order=None): if not iiko_order: iiko_order = order_info1(order_id, org_id) company = CompanyNew.get_by_iiko_id(org_id) changes = {} no_new_value = object() def _attr(name, new_value=no_new_value): old_value = getattr(order, name) if new_value is no_new_value: new_value = iiko_order[name] if old_value != new_value: changes[name] = old_value setattr(order, name, new_value) if not order: changes['order'] = None order = Order(order_id=order_id, venue_id=org_id, source=IIKO_SOURCE) order.is_delivery = iiko_order['orderType'][ 'orderServiceType'] == 'DELIVERY_BY_COURIER' customer = Customer.customer_by_customer_id(iiko_order['customerId']) order.customer = customer.key if customer else None # TODO create customer new_sum = iiko_order['sum'] for payment in iiko_order['payments']: if payment['paymentType']['code'] is not None and \ 'INET' in payment['paymentType']['code']: new_sum -= payment['sum'] _attr('sum', new_sum) _attr('items') _attr('address') _attr('number') delivery_terminal_id = None if iiko_order['deliveryTerminal']: delivery_terminal_id = iiko_order['deliveryTerminal'][ 'deliveryTerminalId'] _attr('delivery_terminal_id', delivery_terminal_id) date = parse_iiko_time(iiko_order['deliveryDate'], company) _attr('date', date) created_time = parse_iiko_time(iiko_order['createdTime'], company) _attr('created_in_iiko', created_time) status = Order.parse_status(iiko_order['status']) if status == Order.CLOSED and iiko_order['sum'] < 0.005: status = Order.CANCELED _attr('status', status) logging.debug("changes in %s: %s", order_id, changes.keys()) if changes and order.source in [APP_SOURCE, AUTO_APP_SOURCE]: __handle_changes(order, changes) order.put() return order
def get_menu(org_id, force_reload=False, filtered=True): menu = PickleStorage.get("iiko_menu_%s" % org_id) if not force_reload else None if not menu: company = CompanyNew.get_by_iiko_id(org_id) menu = _load_menu(company) PickleStorage.save("iiko_menu_%s" % org_id, menu) if filtered: _filter_menu(org_id, menu) return menu
def get_order_promos(order, order_dict, set_info=False): order_request = order_dict url = '/orders/calculate_loyalty_discounts' payload = order_request company = CompanyNew.get_by_iiko_id(order.venue_id) result = json.loads(post_request(company, url, {}, payload, force_platius=True)) logging.info(result) menu_list = list_menu(order.venue_id) # TODO gifts in LPQ are disabled! if order.venue_id == CompanyNew.HLEB: result['availableFreeProducts'] = [] if result.get('availableFreeProducts'): for free_product in result['availableFreeProducts'][:]: product = get_product_from_menu(order.venue_id, product_code=free_product.get('productCode'), menu_list=menu_list) if product: free_product['id'] = product['productId'] free_product['name'] = product['name'] free_product['price'] = product['price'] if not product['price'] and product.get('modifiers'): free_product['price'] = product['modifiers'][0]['price'] free_product['amount'] = 1 free_product['sum'] = 0 free_product['weight'] = product['weight'] free_product['images'] = product['images'] free_product['code'] = free_product['productCode'] else: logging.error('not found product in menu') result['availableFreeProducts'].remove(free_product) if result.get('discountInfo'): for dis_info in result.get('discountInfo'): if dis_info.get('details'): for detail in dis_info.get('details'): if detail.get('productCode'): product = get_product_from_menu(order.venue_id, product_code=detail.get('productCode'), menu_list=menu_list) if product: detail['id'] = product['productId'] if product.get('productId') else product.get('id') detail['name'] = product['name'] detail['code'] = product['code'] else: logging.error('product from iiko.biz not found!') if set_info: promo = get_promo_by_id(order.venue_id, dis_info.get('id')) dis_info['description'] = promo['description'] dis_info['start'] = promo['start'] dis_info['end'] = promo['end'] dis_info['imageUrl'] = promo['imageUrl'] return result
def get(self): org_id = self.request.get("selected_company") if org_id == "0": org_id = None start, end = self.get_date_range() change_dicts = [] for company in (CompanyNew.query().fetch() if not org_id else [CompanyNew.get_by_iiko_id(org_id)]): for order in Order.query(Order.venue_id == company.iiko_org_id, Order.date > start, Order.date < end).fetch(): if order.status != Order.CLOSED: continue for log in OrderChangeLog.query( OrderChangeLog.order_id == order.order_id).fetch(): for change in log.changes: if change.what == 'sum': change_dicts.append({ 'company': company.app_title, 'day': order.date, 'number': order.number, 'status': Order.STATUS_MAPPING[order.status][0], 'type': PaymentType.PAYMENT_MAP[order.payment_type], 'old': change.old, 'new': change.new }) return self.render_report( 'changes', { 'companies': CompanyNew.query().fetch(), 'chosen_company': CompanyNew.get_by_iiko_id(org_id), 'start': start, 'end': end, 'changes': change_dicts })
def _defer_load_images(org_id, image_number): logging.info("starting defer for %s", org_id) images = _get_menu_images(CompanyNew.get_by_iiko_id(org_id).menu) count = len(images) logging.info("progress: %s/%s", image_number, count) try: while image_number < count: image_url = str(images[image_number]) try: get_image(image_url, force_fetch=True) except Exception as e: logging.exception(e) image_number += 1 except DeadlineExceededError: deferred.defer(_defer_load_images, org_id, image_number)
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): order_id = self.request.get('order_id') order = Order.order_by_id(order_id) company = CompanyNew.get_by_iiko_id(order.venue_id) customer = order.customer.get() bonus = SharedBonus.query(SharedBonus.recipient == order.customer, SharedBonus.status == SharedBonus.READY).get() iiko_history = get_history_by_phone(customer.phone, company.iiko_org_id) order_count = 0 if iiko_history.get('customersDeliveryHistory'): for customer_info in iiko_history["customersDeliveryHistory"]: if customer_info.get("deliveryHistory"): order_count += len(customer_info['deliveryHistory']) if order_count == 1: bonus.deactivate(company) else: bonus.cancel()
def cancel(order): company = CompanyNew.get_by_iiko_id(order.venue_id) if company.auto_token and order.source == AUTO_APP_SOURCE: cancel_order(order, company.auto_token) if order.venue_id == CompanyNew.ORANGE_EXPRESS: oe_cancel.handle_cancel(order) else: if order.payment_type == PaymentType.CARD: delivery_terminal = DeliveryTerminal.get_by_id(order.delivery_terminal_id) \ if order.delivery_terminal_id else None cancel_result = get_back_blocked_sum(company, delivery_terminal, order.alfa_order_id) logging.info("cancel %s" % str(cancel_result)) success = 'errorCode' not in cancel_result or str(cancel_result['errorCode']) == '0' if not success: logging.warning("cancel failed") return send_order_status_push(order)
def get(self): square_list = JsonStorage.get("square_table") companies = CompanyNew.query().fetch() if square_list: for square in square_list.values(): for row in square: for cell in row: cell["begin"] = datetime.fromtimestamp(cell["begin"]) cell["end"] = datetime.fromtimestamp(cell["end"]) company_id = self.request.get_range('selected_company') if not company_id: company_id = CompanyNew.get_by_iiko_id( CompanyNew.ORANGE_EXPRESS).key.id() self.render('reports/square_table.html', square=square_list, chosen_company=CompanyNew.get_by_id(company_id), companies=companies) else: self.response.write("Report not ready")
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, 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 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)