def get(self):
     text = u'7 дней после заказа'
     start = datetime.utcnow() - timedelta(days=DAYS + 1)
     end = datetime.utcnow() - timedelta(days=DAYS)
     orders = Order.query(Order.date >= start, Order.date <= end).fetch()
     for order in orders:
         if order.venue_id in COMPANIES:
             last_order = Order.query(
                 Order.customer == order.customer).order(-Order.date).get()
             if last_order.date > end:
                 continue
             deferred.defer(send_order_screen_push, order, text)
    def get(self):
        now = datetime.datetime.now()
        delta = datetime.timedelta(minutes=MINUTES_INTERVAL)
        orders = Order.query(Order.status == Order.CREATING,
                             Order.created <= now - delta).fetch()
        if orders:
            infos = []
            for order in orders:
                info = [("id", order.order_id),
                        ("payment type", order.payment_type),
                        ("payment id", order.alfa_order_id)]
                to_delete = False

                iiko_order = order_info1(order.order_id, order.venue_id)
                if 'httpStatusCode' not in iiko_order:
                    info.append(('found', True))
                    order.load_from_object(iiko_order)
                else:
                    if order.payment_type == PaymentType.CARD:
                        try:
                            company = CompanyNew.get_by_iiko_id(order.venue_id)
                            delivery_terminal = DeliveryTerminal.get_by_id(order.delivery_terminal_id) \
                                if order.delivery_terminal_id else None
                            # check payment status
                            status = alfa_bank.check_extended_status(
                                company, delivery_terminal,
                                order.alfa_order_id)["alfa_response"]
                            info.append(("status check result", status))

                            # if status check was successful:
                            if str(status.get("errorCode", '0')) == '0':
                                # money already deposited -- do not delete
                                if status['orderStatus'] == 2:
                                    info.append(("ERROR", "deposited"))
                                # money approved -- reverse
                                elif status['orderStatus'] == 1:
                                    reverse_result = alfa_bank.get_back_blocked_sum(
                                        company, delivery_terminal,
                                        order.alfa_order_id)
                                    info.append(
                                        ("reverse result", reverse_result))
                                    if str(reverse_result.get(
                                            'errorCode', '0')) == '0':
                                        to_delete = True
                                # any other status is OK to delete
                                else:
                                    to_delete = True
                        except Exception as e:
                            info.append(("exception", repr(e)))
                    else:
                        to_delete = True
                if to_delete:
                    order.key.delete()
                    info.append(("deleted", True))
                infos.append(info)
            mail_body = "Orders with creating status\n"
            mail_body += "List of orders:\n" + \
                         "\n\n".join("\n".join("%s: %s" % t for t in info) for info in infos)
            admin.send_error("order", "Orders crashed while creating",
                             mail_body)
Exemple #3
0
    def post(self, order_id):
        order = Order.order_by_id(order_id)
        meal_rate = float(self.request.get('meal_rate'))
        service_rate = float(self.request.get('service_rate'))
        comment = self.request.get('comment')
        rate = OrderRate(meal_rate=meal_rate,
                         service_rate=service_rate,
                         comment=comment)
        order.rate = rate
        order.put()

        is_negative = 0 < meal_rate < 4 or 0 < service_rate < 4
        if is_negative or rate.comment:
            company = CompanyNew.get_by_iiko_id(order.venue_id)
            customer = order.customer.get()
            dt = DeliveryTerminal.get_by_id(order.delivery_terminal_id)
            body = u"Клиент: %s %s<br>" \
                   u"Заказ №%s<br>" \
                   u"Точка: %s<br>" \
                   u"Оценка еды: %d из 5<br>" \
                   u"Оценка обслуживания: %d из 5<br>" % \
                   (customer.phone, customer.name, order.number, dt.name, meal_rate, service_rate)
            if comment:
                body += u"Комментарий: %s" % comment
            logging.info(body)
            to = company.support_emails
            cc = ['*****@*****.**', '*****@*****.**']
            subject = u'Негативный отзыв о заказе' if is_negative else u'Отзыв о заказе с комментарием'
            mandrill.send_email('*****@*****.**', to, cc, subject,
                                body)

        self.render_json({})
Exemple #4
0
    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})
Exemple #5
0
 def get(self):
     orders = Order.query(Order.status < Order.CLOSED).fetch()
     for order in orders:
         try:
             logging.info("order number: %s" % order.number)
             order.reload()
         except Exception as e:
             logging.exception(e)
Exemple #6
0
 def post(self, order_id):
     order = Order.order_by_id(order_id)
     if order.status in (Order.NOT_APPROVED, Order.APPROVED):
         order.cancel_requested = True
         order.put()
         self.render_json({})
     else:
         self.response.set_status(400)
         self.render_json({'error': u"Заказ уже выдан или отменен"})
Exemple #7
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
    def get_square_table(self, company):
        orders = Order.query(Order.status == Order.CLOSED,
                             Order.venue_id == company.iiko_org_id).fetch()

        if not orders:
            return []

        clients = []
        for order in orders:
            client = order.customer.get()
            client.first_order_time = None
            clients.append(client)
        clients_map = {c.key.id(): c for c in clients}

        for order in orders:
            client = clients_map[order.customer.id()]
            if not client.first_order_time or client.first_order_time > order.date:
                client.first_order_time = order.date

        clients = sorted(clients, key=lambda client: client.first_order_time)
        start_time = clients[0].first_order_time
        start_time = start_time.replace(hour=0, minute=0)

        def _week_number(dt):
            return (dt - start_time).days / 7

        def _week_start(number):
            return start_time + timedelta(days=7 * number)

        weeks_count = _week_number(datetime.now()) + 1

        orders_square = []
        for i in xrange(weeks_count):
            orders_row = []
            for j in xrange(weeks_count):
                orders_row.append([])
            orders_square.append(orders_row)

        client_week = {}
        for client in clients:
            client_week[client.key.id()] = _week_number(
                client.first_order_time)

        for order in orders:
            row = client_week[order.customer.id()]
            column = _week_number(order.date)
            orders_square[row][column].append(order)

        return [[
            self.get_orders_info(cell,
                                 begin=_week_start(i),
                                 end=_week_start(i + 1))
            for i, cell in enumerate(row)
        ] for row in orders_square]
Exemple #9
0
 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()
Exemple #10
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
         })
Exemple #11
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
     })
Exemple #12
0
 def _get_orders(self, delivery_terminal_id):
     customer_id = self.request.get("customer_id")
     customer = Customer.customer_by_customer_id(customer_id)
     if not customer:
         return []
     return Order.query(Order.customer == customer.key).fetch()
Exemple #13
0
 def _get_orders(self, delivery_terminal_id):
     return Order.query(Order.status == Order.CLOSED,
                        Order.delivery_terminal_id == delivery_terminal_id,
                        Order.date >= self.today()).fetch()
Exemple #14
0
 def _get_orders(self, delivery_terminal_id):
     timestamp = self.request.get_range('timestamp')
     return Order.query(Order.delivery_terminal_id == delivery_terminal_id,
                        Order.updated >= datetime.datetime.fromtimestamp(timestamp)).fetch()
Exemple #15
0
 def _get_orders(self, delivery_terminal_id):
     return Order.query(Order.status.IN([Order.NOT_APPROVED, Order.APPROVED]),
                        Order.delivery_terminal_id == delivery_terminal_id,
                        Order.date >= self.today()).fetch()
Exemple #16
0
 def post(self):
     order_id = self.request.get('order_id')
     order = Order.order_by_id(order_id)
     send_order_review_push(order)