Beispiel #1
0
 def get(self):
     company_id = self.request.get_range('company_id')
     if not company_id:
         company_id = 5765997218758656  # DemoStandResto in empatika-resto-test
     company = CompanyNew.get_by_id(company_id)
     if not company:
         company = CompanyNew.get_by_id(
             5764144745676800)  # oe in empatika-resto
     return self.render_json({
         'text':
         company.invitation_settings.about_text
         if company.invitation_settings else ''
     })
Beispiel #2
0
    def get(self):
        mass_pushes = MassPushHistory.query().order(
            -MassPushHistory.created).fetch()
        for push in mass_pushes:
            if push.company_ids:
                push.companies = ', '.join([
                    (CompanyNew.get_by_id(company_id).app_title if company_id
                     and CompanyNew.get_by_id(company_id) else u'Не найдено')
                    for company_id in push.company_ids
                ])
            else:
                push.companies = ''
            push.android_number = len(push.android_channels)
            push.ios_number = len(push.ios_channels)

        self.render('/pushes_history.html', history=mass_pushes)
Beispiel #3
0
    def get(self):
        company_id = self.request.get_range('company_id')
        company = CompanyNew.get_by_id(company_id)
        if not company.invitation_settings or not company.invitation_settings.enable:
            self.abort(403)
        customer_id = self.request.get('customer_id')
        customer = get_resto_customer(company, customer_id)
        if not customer:
            self.abort(400)
        share = Share(share_type=branch_io.INVITATION, sender=customer.key)
        share.put()

        if 'iOS' in self.request.headers["User-Agent"]:
            user_agent = 'ios'
        elif 'Android' in self.request.headers["User-Agent"]:
            user_agent = 'android'
        else:
            user_agent = 'unknown'
        urls = [{
            'url':
            branch_io.create_url(company, share.key.id(), branch_io.INVITATION,
                                 channel, user_agent),
            'channel':
            channel
        } for channel in branch_io.CHANNELS]
        share.urls = [url['url'] for url in urls]
        share.put()

        self.render_json({
            'urls': urls,
            'text': company.invitation_settings.share_text,
            'image_url': company.invitation_settings.share_image
        })
Beispiel #4
0
 def get(self, company_id):
     company = CompanyNew.get_by_id(int(company_id))
     self.render_json({
         "types": [
             payment_type.get().to_dict()
             for payment_type in company.payment_types
         ]
     })
Beispiel #5
0
 def get(self, company_id):
     company = CompanyNew.get_by_id(int(company_id))
     news = News.get(company)
     self.render_json({
         "news": news.dict() if news else None,
         "card_button_text": company.card_button_text or u"Добавить карту",
         "card_button_subtext": company.card_button_subtext or "",
         'is_iiko': company.is_iiko_system or company.iiko_org_id in HARDCODED_PROMOS
     })
Beispiel #6
0
    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]})
Beispiel #7
0
 def get(self):
     item_id = self.request.get('item_id')
     company_id = self.request.get_range('company_id')
     company = CompanyNew.get_by_id(company_id)
     if not company:
         self.abort(400)
     item = get_product_from_menu(company.iiko_org_id, product_id=item_id)
     if not item:
         self.abort(400)
     recommendations = Recommendation.get_for_item_id(item_id)
     self.render_json({'items': recommendations})
Beispiel #8
0
 def dispatch(self):
     company_id = self.request.get("organizationId")
     if company_id:
         self.company = CompanyNew.get_by_id(int(company_id))
     if not self.company:
         ua = self.request.headers["User-Agent"]
         name = ua.split('/', 1)[0].lower().strip()
         self.company = CompanyNew.query(CompanyNew.app_name == name).get()
     if not self.company:
         self.abort(400)
     return super(AlfaBaseHandler, self).dispatch()
Beispiel #9
0
    def get(self, company_id):
        card = self.request.get("card")
        iiko_customer = get_customer_by_card(
            CompanyNew.get_by_id(int(company_id)), card)
        if 'httpStatusCode' in iiko_customer:
            self.response.set_status(400)
            return self.render_json(
                {'description': u'Не удалось найти бонусную карту'})

        BonusCardHack(id=iiko_customer['phone'],
                      customer_id=iiko_customer['id']).put()
        self.render_json({'phone': '+' + iiko_customer['phone']})
Beispiel #10
0
 def get(self, company_id):
     company = CompanyNew.get_by_id(int(company_id))
     force_reload = "reload" in self.request.params
     filtered = "all" not in self.request.params
     menu = get_menu(company.iiko_org_id,
                     force_reload=force_reload,
                     filtered=filtered)
     if company.iiko_org_id == CompanyNew.COFFEE_CITY:
         menu = fix_syrop.set_syrop_modifiers(menu)
         menu = fix_modifiers_by_own.remove_modifiers(menu)
     add_additional_categories(company, menu)
     self.render_json({'menu': menu})
Beispiel #11
0
 def get(self):
     menu_reload = 'menu_reload' in self.request.params
     mass_pushes = MassPushHistory.query().order(-MassPushHistory.created).fetch()
     for push in mass_pushes[:]:
         if self.user.company.id() not in push.company_ids or len(push.company_ids) > 1:
             mass_pushes.remove(push)
             continue
         push.companies = ''.join(['%s, ' % CompanyNew.get_by_id(company_id).app_title
                                   for company_id in push.company_ids])
         push.android_number = len(push.android_channels)
         push.ios_number = len(push.ios_channels)
     self.render('mt/pushes_history.html', history=mass_pushes, user=self.user, menu_reload=menu_reload)
Beispiel #12
0
    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']})
Beispiel #13
0
    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})
Beispiel #14
0
 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")
Beispiel #15
0
 def post(self):
     company_id = self.request.get_range('company_id')
     company = CompanyNew.get_by_id(company_id)
     customer_id = self.request.get('customer_id')
     customer = get_resto_customer(company, customer_id)
     customer.put()
     share_data = self.request.get('share_data')
     logging.info('shared_data: %s' % share_data)
     invitation_response = {}
     if share_data:
         share_data = json.loads(share_data)
         share_id = share_data.get('share_id')
         if share_id:
             share = Share.get_by_id(int(share_id))
             if share.share_type == INVITATION:
                 if not customer_id:
                     SharedBonus(sender=share.sender,
                                 recipient=customer.key,
                                 share_id=share.key.id()).put()
                     invitation_response = {
                         'success':
                         True,
                         'description':
                         company.invitation_settings.success_message
                         if company.invitation_settings else 'Success',
                     }
                 else:
                     invitation_response = {
                         'success':
                         False,
                         'description':
                         company.invitation_settings.failure_message
                         if company.invitation_settings else 'Fail',
                     }
     self.render_json({
         'customer_id':
         customer.customer_id
         if customer.customer_id else customer.key.id(),
         'invitation':
         invitation_response
     })
Beispiel #16
0
 def get(self):
     company_id = self.request.get_range('company_id')
     company = CompanyNew.get_by_id(company_id)
     client_id = self.request.get('client_id')
     customer = get_resto_customer(company, client_id)
     branch_invitation = company.invitation_settings is not None and company.invitation_settings.enable
     if branch_invitation and 'orangexpress/1.2.2' in self.request.user_agent:
         branch_invitation = Order.query(
             Order.customer == customer.key).get() is not None
     self.render_json({
         'app_name': company.app_title,
         'description': company.description,
         'min_order_sum': company.min_order_sum,
         'cities': company.cities,
         'phone': company.phone,
         'schedule': company.schedule,
         'email': company.email,
         'support_emails': company.support_emails,
         'site': company.site,
         'branch_invitation': branch_invitation,
         'branch_gift': company.branch_gift_enable
     })
Beispiel #17
0
def push_venues(chosen_companies, text, full_text, head, android_avail,
                ios_avail, user_login, jinja):
    def get_client_channel(client_id):
        return 'client_%s' % client_id

    if chosen_companies:
        clients = ClientInfo.query(
            ClientInfo.company_id.IN(chosen_companies)).fetch()
    else:
        clients = []
    android_channels = []
    ios_channels = []

    dummy_order = None

    for chosen_company in chosen_companies:
        company = CompanyNew.get_by_id(chosen_company)
        if company.ios_push_channel:
            ios_channels.append(company.ios_push_channel)
        if company.android_push_channel:
            android_channels.append(company.android_push_channel)
        dummy_order = Order(
            venue_id=company.iiko_org_id)  # for proper parse account

    for client in clients:
        device = client.get_device()
        if device == ANDROID_DEVICE and android_avail:
            android_channels.append(get_client_channel(client.key.id()))
        elif device == IOS_DEVICE and ios_avail:
            ios_channels.append(get_client_channel(client.key.id()))
        else:
            customer = client.customer.get() if client.customer else None
            if not customer:
                continue
            device = customer.get_device()
            if device == ANDROID_DEVICE and android_avail:
                android_channels.append(get_client_channel(client.key.id()))
            elif device == IOS_DEVICE and ios_avail:
                ios_channels.append(get_client_channel(client.key.id()))

    result = {}
    if android_avail:
        data = make_mass_push_data(text, full_text, ANDROID_DEVICE, head)
        response = send_push(android_channels, data, ANDROID_DEVICE,
                             dummy_order)
        result['android'] = {
            'data': data,
            'channels': android_channels,
            'response': response['result'] if response.get('result') else False
        }
    if ios_avail:
        data = make_mass_push_data(text, full_text, IOS_DEVICE, head)
        response = send_push(ios_channels, data, IOS_DEVICE, dummy_order)
        result['ios'] = {
            'data': data,
            'channels': ios_channels,
            'response': response['result'] if response.get('result') else False
        }

    values = {
        'text': text,
        'head': head,
        'android_avail': android_avail,
        'android_channels': android_channels,
        'ios_avail': ios_avail,
        'ios_channels': ios_channels,
        'company_ids': chosen_companies,
        'parse_response': json.dumps(result)
    }

    MassPushHistory(**values).put()
    str_companies = ''.join([
        '%s, ' % CompanyNew.get_by_id(company_id).app_title
        for company_id in chosen_companies
    ])
    html_body = jinja.render_template('email/pushes.html',
                                      text=text,
                                      head=head,
                                      str_companies=str_companies,
                                      result=result,
                                      user=user_login)
    send_email('*****@*****.**', ['*****@*****.**'], [],
               u'Рассылкка пушей', html_body)

    return result
Beispiel #18
0
    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})
Beispiel #19
0
    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)