예제 #1
0
def show_order(request,
               template_name=u'show_order.jinja2', ):
    email = request.POST.get(u'email', False, )
    if email:
        email = email.strip()
    email_error = False
    FIO = request.POST.get(u'FIO', None, )
    phone = request.POST.get(u'phone', None, )
    comment = request.POST.get(u'comment', None, )
    country = request.POST.get(u'select_country', None, )

    try:
        country_list = Country.objects.all()
    except Country.DoesNotExist:
        country_list = None

    delivery_company = request.POST.get(u'select_delivery_company', None, )

    try:
        delivery_companies_list = DeliveryCompany.objects.all()
    except DeliveryCompany.DoesNotExist:
        delivery_companies_list = None

    if request.method == 'POST':
        POST_NAME = request.POST.get(u'POST_NAME', None, )
        if POST_NAME == 'order':
            """
                Здесь как-то нужно проверить email
            """
            if not email:
                email_error = u'Вы забыли указать Ваш E-Mail.'
            else:
                is_valid = True
                if proj.settings.SERVER:
                    is_valid = validate_email(email, check_mx=True, )
                    if not is_valid:
                        # email_error = u'Сервер указанный в Вашем E-Mail - ОТСУТСВУЕТ !!!'
                        email_error = u'Проверьте пожалуйста указанный Вами e-mail.'
                    is_valid = validate_email(email, verify=True, )
                if not is_valid:
                    """
                        Делаем повторную проверку на просто валидацию E-Mail адреса
                    """
                    try:
                        EmailField().clean(email, )
                        email_error = False
                        is_valid = True
                    except ValidationError:
                        email_error = u'Ваш E-Mail адрес не существует.'

                if is_valid and not email_error in locals():
                    try:
                        country = Country.objects.get(pk=int(country, ), )
                        """ Взять или создать корзину пользователя """
                        """ Создать теоретически это не нормально """
                        cart, create = get_cart_or_create(request, )
                        if create:
                            return redirect(to=u'/корзина/заказ/непринят/', )

                    except (ValueError, TypeError):
                        raise Http404

                    try:
                        """ Выборка всех продуктов из корзины """
                        all_products = cart.cart.all()
                    except Product.DoesNotExist:
                        """ Странно!!! В корзине нету продуктов!!! """
                        return redirect(to='show_cart', )

                    else:
                        """ Создаем ЗАКАЗ """
                        choice1 = request.POST.get(u'choice1', True, )
                        choice2 = request.POST.get(u'choice2', False, )

                        if country.pk == 1:
                            """ для Украины """
                            region = request.POST.get(u'region', None, )
                            settlement = request.POST.get(u'settlement', None, )
                            warehouse_number = request.POST.get(u'warehouse_number', None, )

                            if delivery_company is None:
                                delivery_company = 1
                            elif type(delivery_company) == unicode:
                                try:
                                    delivery_company = int(delivery_company, )
                                except ValueError:
                                    delivery_company = 1
                            try:
                                delivery_company = DeliveryCompany.objects.get(select_number=delivery_company, )
                            except DeliveryCompany.DoesNotExist:
                                delivery_company = None

                            """ Создаем новый заказ """
                            order = Order.objects.create(user=cart.user,
                                                         sessionid=cart.sessionid,
                                                         email=email,
                                                         FIO=FIO,
                                                         phone=phone,
                                                         country=country,
                                                         delivery_company=delivery_company,
                                                         region=region,
                                                         settlement=settlement,
                                                         warehouse_number=warehouse_number,
                                                         comment=comment,
                                                         checkbox1=choice1,
                                                         checkbox2=choice2, )

                        else:
                            """ для другого Государства """
                            address = request.POST.get(u'address', None, )
                            postcode = request.POST.get(u'postcode', None, )
                            """ Создаем новый заказ """
                            order = Order.objects.create(user=cart.user,
                                                         sessionid=cart.sessionid,
                                                         email=email,
                                                         FIO=FIO,
                                                         phone=phone,
                                                         country=country,
                                                         address=address,
                                                         postcode=postcode,
                                                         comment=comment,
                                                         checkbox1=choice1,
                                                         checkbox2=choice2, )
                        """ Берем указатель на model заказ """
                        ContentType_Order = ContentType.objects.get_for_model(Order, )
                        """ Перемещение всех продуктов из корзины в заказ """
                        """ Просто меняем 2-а поля назначения у всех продуктов в этой корзине """
                        all_products.update(content_type=ContentType_Order, object_id=order.pk, )
                        """ Удаляем старую корзину """
                        cart.delete()

                        delivery_order.apply_async(
                            queue='delivery_send',
                            kwargs={'order_pk': order.pk, },
                        )
                        send_template_sms.apply_async(
                            queue='delivery_send',
                            kwargs={
                                'sms_to_phone_char': order.phone,
                                'sms_template_name': proj.settings.SMS_TEMPLATE_NAME['SEND_ORDER_NUMBER'],
                                'sms_order_number': order.pk,
                            },
                        )
                        request.session[u'order_last'] = order.pk
                        return redirect(to=u'/корзина/заказ/принят/', )

        elif POST_NAME == 'order_cart':
            """ Взять корзину """
            product_cart, created = get_cart_or_create(request, )

            try:
                """ Выборка всех продуктов из корзины """
                for product_in_cart in product_cart.cart.all():
                    """ Нужно проверить, есть ли вообще такой продукт в корзине? """
                    try:
                        product_in_request = int(
                            request.POST.get(
                                u'product_in_request_%d' % product_in_cart.pk,
                                None,
                            ),
                        )
                    except (ValueError, TypeError, ):
                        continue

                    if product_in_request == product_in_cart.pk:

                        if request.POST.get(u'delete_%d' % product_in_cart.pk, None, ):
                            product_in_cart.product_delete
                            continue

                        product_quantity = request.POST.get(u'quantity_%d' % product_in_cart.pk, None, )
                        if product_quantity != product_in_cart.quantity:
                            product_in_cart.update_quantity(product_quantity, )

            except Product.DoesNotExist:
                """ Странно!!! В корзине нету продуктов!!! """
                return redirect(to='show_cart', )

    return render_to_response(template_name=template_name,
                              dictionary={'country_list': country_list,
                                          'delivery_companies_list': delivery_companies_list,
                                          'email': email,
                                          'email_error': email_error,
                                          'FIO': FIO,
                                          'phone': phone,
                                          'comment': comment,
                                          'select_country': country,
                                          'select_delivery_company': delivery_company, },
                              context_instance=RequestContext(request, ),
                              content_type='text/html', )
예제 #2
0
def result_ordering(request, ):
    if request.method == 'POST':
        POST_NAME = request.POST.get(u'POST_NAME', None, )
        if POST_NAME == 'ordering_step_two':
            FIO = request.session.get(u'FIO', None, )
            email = request.session.get(u'email', None, )
            phone = request.session.get(u'phone', None, )
            select_country = request.session.get(u'select_country', None, )
            order_pk = request.session.get(u'order_pk', None, )
            try:
                order_pk = int(order_pk, )
            except ValueError:
                return redirect(to=u'/заказ/вы-где-то-оступились/', )

            try:
                order = Order.objects.get(pk=order_pk, )
            except Order.DoesNotExist:
                return redirect(to=u'/заказ/вы-где-то-оступились/', )
            if select_country == 1:
                """ Страна Украина """
                region = request.POST.get(u'region', None, )
                order.region = region
                request.session[u'region'] = region
                settlement = request.POST.get(u'settlement', None, )
                order.settlement = settlement
                request.session[u'settlement'] = settlement
                delivery_company = request.POST.get(u'select_delivery_company', None, )
                if delivery_company is None:
                    delivery_company = 1
                elif type(delivery_company) == unicode:
                    try:
                        delivery_company = int(delivery_company, )
                    except (TypeError, ValueError, ):
                        delivery_company = 1
                # from apps.cart.models import DeliveryCompany
                # try:
                #     delivery_company = DeliveryCompany.objects.get(select_number=delivery_company, )
                # except DeliveryCompany.DoesNotExist:
                #     delivery_company = None
                order.delivery_company_id = delivery_company
                warehouse_number = request.POST.get(u'warehouse_number', None, )
                order.warehouse_number = warehouse_number
                choice1 = request.POST.get(u'choice1', True, )
                order.checkbox1 = choice1
                choice2 = request.POST.get(u'choice2', False, )
                order.checkbox2 = choice2
            else:
                """ для любого другого Государства """
                address = request.POST.get(u'address', None, )
                order.address = address
                request.session[u'address'] = address
                postcode = request.POST.get(u'postcode', None, )
                order.postcode = postcode
                request.session[u'postcode'] = postcode
            comment = request.POST.get(u'comment', None, )
            order.comment = comment
            order.save()
            cart, create = get_cart_or_create(request, )
            if create:
                return redirect(to=u'/заказ/вы-где-то-оступились/', )
            try:
                """ Выборка всех продуктов из корзины """
                all_products = cart.cart.all()
            except Product.DoesNotExist:
                """ Странно!!! В корзине нету продуктов!!! """
                return redirect(to='show_cart', )
            else:
                """ Берем указатель на model заказ """
                ContentType_Order = ContentType.objects.get_for_model(Order, )
                """ Перемещение всех продуктов из корзины в заказ """
                """ Просто меняем 2-а поля назначения у всех продуктов в этой корзине """
                all_products.update(content_type=ContentType_Order, object_id=order.pk, )
                """ Удаляем старую корзину """
                cart.delete()

                delivery_order.apply_async(
                    queue='delivery_send',
                    kwargs={'order_pk': order.pk, },
                    task_id='celery-task-id-delivery_order-{0}'.format(celery.utils.uuid(), ),
                )

                phone = order.phone \
                    .lstrip('+') \
                    .replace('(', '') \
                    .replace(')', '') \
                    .replace(' ', '') \
                    .replace('-', '') \
                    .replace('.', '') \
                    .replace(',', '') \
                    .lstrip('380') \
                    .lstrip('38') \
                    .lstrip('80') \
                    .lstrip('0')

                if len(phone, ) == 9:
                    send_template_sms.apply_async(
                        queue='delivery_send',
                        kwargs={
                            'sms_to_phone_char': '+380%s' % phone,
                            'sms_template_name': proj.settings.SMS_TEMPLATE_NAME['SEND_ORDER_NUMBER'],
                            'sms_order_number': order.pk,
                        },
                        task_id='celery-task-id-send_template_sms-{0}'.format(celery.utils.uuid(), ),
                    )

                request.session[u'order_pk_last'] = order.pk

                return redirect(to=u'/заказ/оформление-прошло-успешно/', )
        else:
            return redirect(to=u'/заказ/вы-где-то-оступились/', )
    else:
        return redirect(to=u'/заказ/вы-где-то-оступились/', )