Beispiel #1
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 #2
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 #3
0
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
Beispiel #4
0
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)
Beispiel #5
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 #6
0
    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()
Beispiel #7
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 #8
0
 def get(self):
     companies = CompanyNew.query().fetch()
     for company in companies:
         try:
             get_menu(company.iiko_org_id, force_reload=True)
         except Exception as e:
             logging.exception(e)
Beispiel #9
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 #10
0
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(self):
        companies = CompanyNew.query().fetch()
        companies_dict = {}
        for company in companies:
            companies_dict[company.iiko_org_id] = self.get_square_table(
                company)

        JsonStorage.save("square_table", companies_dict)
Beispiel #12
0
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
Beispiel #13
0
 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)})
Beispiel #14
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 #15
0
 def get(self):
     companies = CompanyNew.query().fetch()
     for company in companies:
         if not company.menu:
             continue
         try:
             deferred.defer(_defer_load_images, company.iiko_org_id, 0)
         except Exception as e:
             logging.exception(e)
Beispiel #16
0
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)
Beispiel #17
0
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
Beispiel #18
0
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
Beispiel #19
0
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
Beispiel #20
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 #21
0
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
Beispiel #22
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 #23
0
 def post(self):
     companies = CompanyNew.query().fetch()
     for company in companies:
         if PushAdmin.query(PushAdmin.company == company.key).get():
             continue
         login = company.app_title or company.app_name[0] or company.iiko_org_id
         success, info = PushAdmin.create(login.strip().lower(), company.key, '0000')
         if not success:
             logging.info(info)
             self.abort(500)
     self.redirect_to('push_admin_main')
Beispiel #24
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 #25
0
 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
         })
Beispiel #26
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 #27
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 #28
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 #29
0
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)
Beispiel #30
0
 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})