Example #1
0
def address_update(request, address_uuid=None):
    username = request.user.username
    template_name = 'addressbook/address_update.html'
    page_title = _('Address Update')
    context = {
        'page_title': page_title,
    }
    form = None
    obj = get_object_or_404(Address,
                            address_uuid=address_uuid,
                            user=request.user)
    username = request.user.username
    if request.method == 'POST':
        postdata = utils.get_postdata(request)
        updated_address = addressbook_service.update_address(obj, postdata)
        if updated_address:
            messages.success(request, _('Address updated'))
            logger.info(
                f'address {updated_address} updated by user \"{username}\"')
            return redirect('addressbook:address-detail',
                            address_uuid=address_uuid)
        else:
            messages.error(request, _('Address not updated'))
            logger.error(
                f'Error on updating address. Action requested by user \"{username}\"'
            )

    form = AddressForm(instance=obj)
    context['form'] = form
    context['address'] = obj
    context['ADDRESS_TYPES'] = Addressbook_Constants.ADDRESS_TYPES
    return render(request, template_name, context)
Example #2
0
def address_create(request):
    username = request.user.username

    template_name = 'addressbook/address_create.html'
    page_title = _('New Address')

    context = {
        'page_title': page_title,
    }

    if request.method == 'POST':
        postdata = utils.get_postdata(request)
        address = addressbook_service.create_address(postdata)
        if address:
            messages.success(request, _('New Address created'))
            logger.info(f'New Address {address} added by user \"{username}\"')
            return redirect('addressbook:addressbook')
        else:
            messages.error(request, _('Address not created'))
            logger.error(
                f'Error on creating new address. Action requested by user \"{username}\"'
            )

    form = AddressForm()
    context['form'] = form
    context['ADDRESS_TYPES'] = Addressbook_Constants.ADDRESS_TYPES
    return render(request, template_name, context)
Example #3
0
def wishlist_ajax_remove(request):
    context = {}
    if request.method != "POST":
        context['error'] = 'Bad Request. POST method required'
        context['status'] = False
        return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)

    form = AddToWishlistForm(utils.get_postdata(request))
    if form.is_valid():
        wishlist_uuid = form.cleaned_data.get('wishlist_uuid')
        product_uuid = form.cleaned_data.get('product_uuid')
        w = get_object_or_404(Wishlist,
                              customer=request.user,
                              wishlist_uuid=wishlist_uuid)
        p = get_object_or_404(Product, product_uuid=product_uuid)
        removed = wishlist_service.remove_from_wishlist(w, p)
        if removed:
            prefix = p.display_name
            context['success'] = True
            context['status'] = True
            context['quantity'] = WishlistItem.objects.filter(
                wishlists__in=[w]).count()
            context['message'] = prefix + " " + str(
                _('removed from list')) + f" {w.name}"
            return JsonResponse(context)
        else:
            logger.error(f"Form is invalid. {form.errors}")
            context['error'] = 'Bad Request. product missing'
            context['status'] = False
            return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)

    context['error'] = 'Bad Request. submitted data invalid'
    context['status'] = False
    return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)
Example #4
0
def policy_groups_delete(request):
    username = request.user.username
    if not PermissionManager.user_can_access_dashboard(request.user):
        logger.warning("Payment : PermissionDenied to user %s for path %s",
                       username, request.path)
        raise PermissionDenied

    if not PermissionManager.user_can_delete_policy(request.user):
        logger.warning("PermissionDenied to user %s for path %s", username,
                       request.path)
        raise PermissionDenied

    if request.method != "POST":
        raise SuspiciousOperation(
            'Bad request. Expected POST request but received a GET')

    postdata = utils.get_postdata(request)
    id_list = postdata.getlist('policies-groups')

    if len(id_list):
        instance_list = list(map(int, id_list))
        PaymentPolicyGroup.objects.filter(id__in=instance_list).delete()
        messages.success(request,
                         f"Policies Groups \"{instance_list}\" deleted")
        logger.info(
            f"Policies Groups \"{instance_list}\" deleted by user {username}")

    else:
        messages.error(request, f"Policies Groups could not be deleted")
        logger.error(f"ID list invalid. Error : {id_list}")
    return redirect('payment:policy-groups')
Example #5
0
def process_add_to_cart_request(request):
    postdata = utils.get_postdata(request)
    form = AddCartForm(postdata)
    context = {}
    if form.is_valid():
        logger.debug("Summitted data are valid")
        variant_uuid = form.cleaned_data['variant_uuid']
        attr = form.cleaned_data['attr']
        variant = None
        try:
            variant = ProductVariant.objects.get(product_uuid=variant_uuid)
        except ProductVariant.DoesNotExist:
            pass
        result, cart = add_to_cart(request.user.cart, variant)
        prefix = variant.product.display_name
        if result:
            cart.refresh_from_db()
            context['success'] = True
            context['status'] = True
            context['quantity'] = cart.quantity
            context['message'] = _(CORE_UI_STRINGS.PRODUCT_ADDED)
            return context
        else:
            context['success'] = False
            context['status'] = True
            context['quantity'] = cart.quantity
            context['message'] = _(CORE_UI_STRINGS.PRODUCT_QTY_NOT_AVAILABLE)
            return context

    else:
        logger.error(f"Form is invalid. {form.errors}")
        context['error'] = _(CORE_UI_STRINGS.INVALID_FORM)
        context['status'] = False
        return context
Example #6
0
def process_order(user, request):
    postdata = utils.get_postdata(request)
    address = None
    payment_option = None
    payment_method = None
    result = {'success' : False}
    if  not isinstance(user, User) or not isinstance(postdata, dict):
        logger.warn(f"process_order : User or postdata has a wrong type. Expecting user type to be User but got a {type(user)} instead ")
        logger.warn(f"process_order : User or postdata has a wrong type. Expecting postdata type to be dict or a descendant of a dict but got a {type(postdata)} instead ")
        return result
    
    if commons.SHIP_MODE_FIELD not in postdata:
        logger.warn(f"process_order : SHIP_MODE_FIELD {commons.SHIP_MODE_FIELD} missing")
        return result

    ship_mode = shipment_service.get_ship_mode_from_id(int(postdata.get(commons.SHIP_MODE_FIELD)))

    if commons.PAYMENT_OPTION_FIELD not in postdata:
        logger.warn(f"process_order : PAYMENT_OPTION_FIELD {commons.PAYMENT_OPTION_FIELD} missing")
        return result

    payment_option = int(postdata.get(commons.PAYMENT_OPTION_FIELD))

    if commons.PAYMENT_METHOD_FIELD not in postdata:
        logger.warn(f"process_order : PAYMENT_METHOD_FIELD \"{commons.PAYMENT_METHOD_FIELD}\" missing")
        return result
    
    try:
        payment_method = PaymentMethod.objects.get(id=int(postdata.get(commons.PAYMENT_METHOD_FIELD)))
    except ObjectDoesNotExist as e:
        logger.warn(f"process_order : no payment_method found with id \"{postdata.get(commons.PAYMENT_METHOD_FIELD)}\" mode = ORDER_PAYMENT_PAY which is \"{commons.ORDER_PAYMENT_PAY}\"")
        logger.exception(e)
        return result

    if commons.SHIPPING_ADDRESS_FIELD not in postdata and ship_mode.mode not in shipment_service.constants.IN_STORE_PICK_MODE:
        logger.warn(f"process_order : SHIPPING_ADDRESS_FIELD \"{commons.SHIPPING_ADDRESS_FIELD}\" missing for the selected shipping mode {ship_mode}")
        return result
    
    if ship_mode.mode not in shipment_service.constants.IN_STORE_PICK_MODE:
        try:
            addr_pk = int(postdata.get(commons.SHIPPING_ADDRESS_FIELD))
            address = addressbook_service.get_address(addr_pk)
        except TypeError as e:
            logger.warning("error while reading address pk from query parameter", e)
            return result
    if not address:
        logger.warn(f"process_order : no address found with id \"{postdata.get(commons.SHIPPING_ADDRESS_FIELD)}\". shipping mode {ship_mode}")
        #return result

    
    data = {'postdata': postdata,'request': request, commons.PAYMENT_METHOD_FIELD : payment_method, commons.SHIP_MODE_FIELD : ship_mode ,commons.SHIPPING_ADDRESS_FIELD : address, commons.PAYMENT_OPTION_FIELD : payment_option}
    if payment_option == commons.PAY_BEFORE_DELIVERY:
        result = order_pay_before_delivery(user, data)
    elif payment_option == commons.PAY_AT_DELIVERY:
        result = order_pay_at_delivery(user, data)
    elif payment_option == commons.PAY_AT_ORDER:
        result = order_pay_at_order(user, data)

    return result
Example #7
0
def wishlists_delete(request):
    username = request.user.username

    if request.method != "POST":
        raise SuspiciousOperation(
            'Bad request. Expected POST request but received a GET')

    postdata = utils.get_postdata(request)
    id_list = postdata.getlist('wishlists')
    deleted = wishlist_service.delete_wishlists(id_list)
    if deleted:
        messages.success(request, _("Shopping List deleted"))
    else:
        messages.error(request, _("Shopping List could not be deleted"))
        logger.error(f"ID list invalid. Error : {id_list}")
    return redirect('wishlist:wishlist-home')
Example #8
0
def addresses_delete(request):
    username = request.user.username

    postdata = utils.get_postdata(request)
    id_list = postdata.getlist('addresses')

    if len(id_list):
        address_id_list = list(map(int, id_list))
        Address.objects.filter(id__in=address_id_list,
                               user=request.user).delete()
        messages.success(request, f"Addresses \"{id_list}\" deleted")
        logger.info(f"Addresses \"{id_list}\" deleted by user {username}")

    else:
        messages.error(request,
                       f"Addresses \"{id_list}\" could not be deleted")
        logger.error(f"ID list invalid. Error : {id_list}")
    return redirect('addressbook:addressbook')
Example #9
0
def wishlist_ajax_create_add(request):
    context = {}
    if request.method != "POST":
        context['error'] = 'Bad Request. POST method required'
        context['status'] = False
        return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)

    form = CreateAndAddWishlistForm(utils.get_postdata(request))
    if form.is_valid():
        name = form.cleaned_data.get('name')
        product_uuid = form.cleaned_data.get('product_uuid')
        logger.debug(
            f"wishlist_ajax_create_add: form is valid with cleaned_data : {form.cleaned_data}"
        )
        customer = User.objects.get(pk=form.cleaned_data.get('customer'))
        p = get_object_or_404(
            Product, product_uuid=form.cleaned_data.get('product_uuid'))

        w = wishlist_service.create_wishlist({
            'name': name,
            'customer': customer
        })

        added = wishlist_service.add_to_wishlist(w, p)
        if added:
            prefix = p.display_name
            context['success'] = True
            context['wishlist'] = w.name
            context['status'] = True
            context['message'] = prefix + " " + str(
                _('added to list')) + f" {w.name}"
            return JsonResponse(context)
        else:
            logger.error(f"Form is invalid. {form.non_field_errors()}")
            context['error'] = 'Bad Request. product missing'

            context['status'] = False
            return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)
    logger.warning(f"Wishlist creation errors : {form.non_field_errors()}")
    context['error'] = 'Bad Request. submitted data invalid'
    context['message'] = form.non_field_errors()
    context['status'] = False
    return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)
Example #10
0
def wishlist_create(request):
    username = request.user.username
    template_name = 'wishlist/wishlist_create.html'
    page_title = _('Shopping List')
    form = None
    if request.method == 'POST':
        postdata = utils.get_postdata(request)
        w = wishlist_service.create_wishlist(postdata)
        if w is not None:
            messages.success(request, _('Shopping list created'))
            logger.info(f'Wishlist {w.name} created by user \"{username}\"')
            return redirect('wishlist:wishlist-home')
        else:
            messages.warning(request, _('Shopping list not created'))
            logger.warn(f'Wishlist not created by user \"{username}\"')
            return redirect('wishlist:wishlist-home')
    else:
        form = WishlistForm()
    context = {'page_title': page_title, 'form': form}
    return render(request, template_name, context)
Example #11
0
def ajax_cart_item_updateV2(request, item_uuid=None, action=None):
    logger.info(
        f"Cart Item Update Ajax : item \"{item_uuid}\" - action \"{action}\"")
    cart, created = CartModel.objects.get_or_create(user=request.user)
    item = None
    context = {'success': False}
    if request.method != 'POST':
        logger.debug(
            f"ajax_cart_item_update : REQUEST.METHOD : {request.method}")
        context['error'] = 'Method not allowed. POST requets expected.'
        context['status'] = False
        logger.warn(context['error'])
        return JsonResponse(context, status=HTTPStatus.METHOD_NOT_ALLOWED)

    postdata = utils.get_postdata(request)
    result = cart_service.process_cart_action(postdata)
    status = HTTPStatus.OK
    if result.get('invalid_data'):
        status = HTTPStatus.BAD_REQUEST
    return JsonResponse(result, status=status)
Example #12
0
def wishlist_update(request, wishlist_uuid=None):
    username = request.user.username
    template_name = 'wishlist/wishlist_update.html'
    page_title = _('Wishlist Update')

    form = None
    w = get_object_or_404(Wishlist,
                          customer=request.user,
                          wishlist_uuid=wishlist_uuid)
    old_name = w.name
    if request.method == 'POST':
        postdata = utils.get_postdata(request)
        w = wishlist_service.update_wishlist(w, postdata)
        messages.success(request, _('Shopping list updated'))
        logger.info(
            f'Wishlist {old_name} updated to {w.name} by user \"{username}\"')
        return redirect('wishlist:wishlist', wishlist_uuid=wishlist_uuid)
    else:
        form = WishlistForm(instance=w)
    context = {'page_title': page_title, 'form': form, 'wishlist': w}
    return render(request, template_name, context)
Example #13
0
def wishlist_ajax_rename(request):
    context = {}
    if request.method != "POST":
        context['error'] = 'Bad Request. POST method required'
        context['status'] = False
        return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)

    form = RenameWishlistForm(utils.get_postdata(request))
    if form.is_valid():
        name = form.cleaned_data.get('name')
        wishlist_uuid = form.cleaned_data.get('wishlist_uuid')
        customer = User.objects.get(pk=form.cleaned_data.get('customer'))
        w = get_object_or_404(Wishlist,
                              customer=customer,
                              wishlist_uuid=wishlist_uuid)
        updated = wishlist_service.update_wishlist(
            w, {
                'name': form.cleaned_data.get('name'),
                'customer': customer
            })
        if updated:
            prefix = w.name
            context['success'] = True
            context['status'] = True
            context['message'] = prefix + " " + str(
                _('shop list renamed to')) + f" {name}"
            return JsonResponse(context)
        else:
            logger.error(f"Form is invalid. {form.errors}")
            context['error'] = 'Bad Request.'
            context['status'] = False
            return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)

    context['error'] = 'Bad Request. submitted data invalid'
    context['status'] = False
    return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)
Example #14
0
def product_detail_slug(request,
                        category_slug=None,
                        product_slug=None,
                        product_uuid=None):
    template_name = 'catalog/product_detail.html'
    product = get_object_or_404(Product,
                                category__slug=category_slug,
                                slug=product_slug,
                                product_uuid=product_uuid)
    page_title = product.display_name
    if request.method == "POST":
        if request.user.is_authenticated:
            form = AddCartForm(utils.get_postdata(request))
            if form.is_valid():
                variant = get_object_or_404(
                    ProductVariant,
                    product_uuid=form.cleaned_data['variant_uuid'])
                item, cart = cart_service.add_to_cart(
                    cart_service.get_cart(request.user), variant)
                if item:
                    messages.success(request, message=_("Product added"))
                    logger.info("Product added")
                else:
                    messages.success(request, message=_("Product not added"))
                    logger.info("Product not added")
            else:
                messages.warning(request, message=_("Invalid form"))
                logger.info(
                    f"Product not added. Form is not valid : {form.errors} ")
        else:
            messages.warning(
                request,
                message=_(
                    "You must first login before you can add item to your cart"
                ))
            logger.info(f"product_details : Product not added. anonyme user")

    Product.objects.filter(product_uuid=product.product_uuid).update(
        view_count=F('view_count') + 1)
    images = ProductImage.objects.filter(product=product)
    common_attrs, selective_attrs = catalog_service.get_product_attributes(
        product.id)
    product_attrs = catalog_service.product_attributes(product.id)
    if request.user.is_authenticated:
        wishlist_list = wishlist_service.get_wishlists(
            {'customer': request.user})
    else:
        wishlist_list = None

    context = {
        'page_title':
        page_title,
        'product':
        product,
        'image_list':
        images,
        'common_attrs':
        common_attrs,
        'selective_attrs':
        selective_attrs,
        'product_attrs':
        product_attrs,
        'OG_TITLE':
        page_title,
        'OG_DESCRIPTION':
        product.short_description,
        'OG_IMAGE':
        request.build_absolute_uri(product.images.first().get_image_url()),
        'OG_URL':
        request.build_absolute_uri(),
        'wishlist_list':
        wishlist_list,
        'recommendations':
        inventory_service.get_recommandations(product),
        'recommendation_label':
        CORE_UI_STRING.RECOMMANDATION_LABEL
    }
    return render(request, template_name, context)
Example #15
0
def checkout_old(request):
    #TODO Refactore this viewsmove business logic to order_service
    cart = orders_service.get_user_cart(request.user)
    template_name = 'orders/checkout.html'
    address_list = addressbook_service.get_addresses(request.user)
    address = None
    if address_list.exists():
        address = address_list.first()
    context = {
        'page_title' : _("Checkout") + ' - ' + settings.SITE_NAME,
        'address_list': address_list,
        'address': address,
        'ADDRESS_TYPES' : Addressbook_Constants.ADDRESS_TYPES,
        'cart' : cart,
        'cartitems' : orders_service.get_user_cartitems(request.user),
        'payment_methods' : orders_service.get_payment_methods(filter_active=True),
        'PAYMENT_OPTIONS': commons.ORDER_PAYMENT_OPTIONS,
    }
    country = ''
    if not cart or (cart.quantity == 0 or cart.amount == 0.0):
        messages.error(request, _("Your Cart is empty"))
        return redirect('catalog:catalog-home')
    if request.method == 'POST':
        postdata = utils.get_postdata(request)
        #result = orders_service.process_order(request.user, postdata)
        if not address:
            addressForm = AddressForm(postdata)
            if addressForm.is_valid():
                logger.info("AddressForm is Valid")
                address = addressForm.save()
                country = address.country
            else:
                logger.info("AddressForm is not Valid")

        payment_option_form = PaymentOptionForm(postdata)
        payment_option_form_is_valid = payment_option_form.is_valid()
        if  payment_option_form_is_valid:
            logger.debug("Order Form is valid")
            
            payment_option = payment_option_form.cleaned_data.get('payment_option')
            logger.debug(f"Selected Payment Option : {payment_option}")
            if payment_option == commons.PAY_WITH_PAY:
                order = orders_service.create_order_from_cart(user=request.user, address=address)
                logger.debug("Order ready. Now preparing payment data")

                try:
                    payment_data = {
                        'requester_name': settings.PAY_USERNAME,
                        'amount': order.total,
                        'customer_name': request.user.get_full_name(),
                        'quantity': cart.quantity,
                        'description': settings.PAY_REQUEST_DESCRIPTION,
                        'country' : country,
                        'redirect_success_url': request.build_absolute_uri(reverse('orders:checkout-success', kwargs={'order_uuid': order.order_uuid})),
                        'redirect_failed_url': request.build_absolute_uri(reverse('orders:checkout-failed', kwargs={'order_uuid': order.order_uuid})),
                        'product_name' : 'LYSHOP'
                    }
                    logger.debug("Sending request payment")
                except Exception as e:
                    logger.error("Error on prepayring payment data")
                    logger.exception(e)
                    raise e
                
                #cart_items_queryset = orders_service.get_user_cartitems(request.user)
                response = orders_service.request_payment(payment_data)
                if response:
                    response_json = response.json()
                    logger.debug("request payment succeed")
                    
                    orders_service.order_clear_cart(request.user)
                    logger.debug("Creating Payment Request")
                    payment_data['token'] = response_json['token']
                    payment_data['pay_url'] = response_json['url']
                    payment_data['order'] = order
                    payment_data['customer'] = request.user
                    payment_data['verification_code'] = response_json['verification_code']
                    try:
                        payment_request = PaymentRequest.objects.create(**payment_data)
                        messages.success(request,"order has been successfully submitted")
                        return redirect('orders:checkout-redirect-payment', request_uuid=payment_request.request_uuid)
                    except Exception as e:
                        messages.error(request,"An error occured during processing Order")
                        logger.error(f"Error on creating PaymentRequest object")
                        logger.exception(e)
                    
                else:
                    logger.debug("request payment failed")
                    
            elif payment_option == commons.PAY_BEFORE_DELIVERY:
                pass

            elif payment_option == commons.PAY_BY_SMS:
                pass 

            elif payment_option == commons.PAY_AT_DELIVERY:
                pass

        else:
            if not payment_option_form_is_valid:
                logger.error("Order Form is not valid. Error on PaymentOptionForm")
                logger.error(payment_option_form.errors)
        logger.debug("Processing Checkout POST request")
    
    elif request.method == 'GET':
        logger.debug("Processing Checkout POST request")
    return render(request, template_name, context)
Example #16
0
def client_add_payment(request, order_uuid, token):
    postdata = utils.get_postdata(request)

    pass
Example #17
0
def ajax_cart_item_update_quantity(request):
    logger.info(f"Ajax Cart item update requested by User \"{request.user}\"")
    cart, created = CartModel.objects.get_or_create(user=request.user)
    item = None
    context = {'success': False}
    if request.method != 'POST':
        context['error'] = 'Method not allowed. POST requets expected.'
        context['status'] = False
        return JsonResponse(context, status=HTTPStatus.METHOD_NOT_ALLOWED)

    form = CartItemQuantityUpdateForm(utils.get_postdata(request))
    if not form.is_valid():
        context['error'] = 'Invalid Form'
        context['status'] = False
        logger.error(
            f"Cart item update quantity : Form error  \"{form.errors}\"")
        return JsonResponse(context, status=HTTPStatus.BAD_REQUEST)
    try:
        item = CartItem.objects.filter(item_uuid=form.cleaned_data.get(
            'item_uuid')).select_related().get()
    except CartItem.DoesNotExist as e:
        context['error'] = 'No Cart Item found.'
        context['status'] = False
        logger.info(f"Cart item update quantity : Cart Item not found.")
        return JsonResponse(context, status=HTTPStatus.NOT_FOUND)

    requested_quantity = form.cleaned_data.get('quantity')
    updated_rows, item = cart_service.update_cart(cart, item,
                                                  requested_quantity)

    if updated_rows == -1:
        context[
            'error'] = f'Requested quantity \"{requested_quantity}\" not available.'
        context['item_quantity'] = item.quantity
        context['status'] = False
        context['is_active'] = True
        logger.info(
            f"Cart item update quantity : Requested quantity \"{requested_quantity}\" not available."
        )
        return JsonResponse(context, status=HTTPStatus.NOT_ACCEPTABLE)

    if updated_rows == 0:
        context[
            'error'] = f'invalid quantity \"{requested_quantity}\" received.'
        context['item_quantity'] = item.quantity
        context['status'] = False
        context['is_active'] = True
        logger.error(f'invalid quantity \"{requested_quantity}\" received.')
        return JsonResponse(context, status=HTTPStatus.NOT_ACCEPTABLE)

    if updated_rows == 1:
        cart.refresh_from_db()
        item.refresh_from_db()
        context['success'] = True
        context['status'] = True
        context['item_quantity'] = requested_quantity
        context['item_total'] = item.total_price
        context['total'] = float(f'{cart.amount:g}')
        context['solded_price'] = float(f'{cart.solded_price:g}')
        context['reduction'] = float(f'{cart.get_reduction():g}')
        context['subtotal'] = float(f'{cart.amount:g}')
        context['total'] = float(f'{cart.get_total():g}')
        context['cart_quantity'] = cart.quantity
        logger.info(
            f"Updated  Cart Item  \"{item}\" quantity from Cart \"{cart}\" to quantity {item.quantity}"
        )
        return JsonResponse(context)