Exemplo n.º 1
0
def test_model_url():
    with admin_only_urls():
        with pytest.raises(NoModelUrl):
            get_model_url(Counter)  # That's silly!
        p = get_default_product()

        assert get_model_url(p)
Exemplo n.º 2
0
    def get_success_url(self):  # noqa (C901)
        if self.request.GET.get("mode", "") == "iframe":
            params = ["mode=iframe", "iframe_close=yes"]

            quick_add_target = self.request.GET.get("quick_add_target")
            if quick_add_target:
                params.append("quick_add_target=%s" % quick_add_target)

            quick_add_callback = self.request.GET.get("quick_add_callback")
            if quick_add_callback:
                params.append("quick_add_callback=%s" % quick_add_callback)

            return "%s?%s" % (get_model_url(self.object, shop=self.request.shop), "&".join(params))

        next = self.request.POST.get("__next")
        try:
            if next == "return":
                return self.get_return_url()
            elif next == "new":
                return self.get_new_url()
        except NoModelUrl:
            pass

        try:
            return super(CreateOrUpdateView, self).get_success_url()
        except ImproperlyConfigured:
            pass

        try:
            return get_model_url(self.object, shop=self.request.shop)
        except NoModelUrl:
            pass
Exemplo n.º 3
0
def test_edit_object_view(rf, admin_user, creator_fn):
    shop = factories.get_default_shop()
    view = EditObjectView.as_view()
    object_instance = creator_fn()
    model = ".".join(ContentType.objects.get_for_model(object_instance).natural_key())

    # correct shop
    response = _get_edit_object_view(rf, view, model, object_instance.id, admin_user, shop)
    assert response.status_code == 302

    urls = []

    try:
        urls.append(get_model_url(object_instance, kind="edit", user=admin_user, shop=shop))
    except NoModelUrl:
        pass

    try:
        urls.append(get_model_url(object_instance, kind="detail", user=admin_user, shop=shop))
    except NoModelUrl:
        pass

    assert response.url in urls

    # pass the mode query parameter
    response = _get_edit_object_view(rf, view, model, object_instance.id, admin_user, shop, mode="test")
    assert response.status_code == 302
    assert "mode=test" in response.url
Exemplo n.º 4
0
 def _get_parent_and_sibling_items(self, parent, siblings):
     yield DropdownItem(
         text=_("Parent: %s") % parent,
         icon="fa fa-eye",
         url=get_model_url(parent),
     )
     for sib in siblings:
         yield DropdownItem(
             text=_("Sibling: %s") % sib,
             icon="fa fa-eye",
             url=get_model_url(sib),
         )
Exemplo n.º 5
0
    def get(self, request):     # noqa (C901)
        model_name = request.GET.get("model")
        object_id = request.GET.get("pk", request.GET.get("id"))

        if not model_name or not object_id:
            return HttpResponseBadRequest(_("Invalid object."))

        url = None

        try:
            model = apps.get_model(model_name)
        except LookupError:
            return HttpResponseBadRequest(_("Invalid model."))

        instance = model.objects.filter(pk=object_id).first()
        if instance:
            try:
                # try edit first
                try:
                    url = get_model_url(
                        instance,
                        kind="edit",
                        user=request.user,
                        shop=get_shop(request),
                        raise_permission_denied=True
                    )
                except NoModelUrl:
                    # try detail
                    try:
                        url = get_model_url(
                            instance,
                            kind="detail",
                            user=request.user,
                            shop=get_shop(request),
                            raise_permission_denied=True
                        )
                    except NoModelUrl:
                        pass
            except PermissionDenied as exception:
                from django.utils.encoding import force_text
                raise Problem(force_text(exception))

            if url:
                # forward the mode param
                if request.GET.get("mode"):
                    url = "{}?mode={}".format(url, request.GET["mode"])

                return HttpResponseRedirect(url)

        raise Http404(_("Object not found"))
Exemplo n.º 6
0
 def get_breadcrumb_parents(self):
     return [
         MenuEntry(
             text="%s" % self.object,
             url=get_model_url(self.object)
         )
     ]
Exemplo n.º 7
0
    def handle_product_data(self, request):
        product_id = request.GET["id"]
        shop_id = request.GET["shop_id"]
        customer_id = request.GET.get("customer_id")
        supplier_id = request.GET.get("supplier_id")
        quantity = decimal.Decimal(request.GET.get("quantity", 1))
        product = Product.objects.filter(pk=product_id).first()
        if not product:
            return {"errorText": _("Product %s does not exist.") % product_id}
        shop = Shop.objects.get(pk=shop_id)
        try:
            shop_product = product.get_shop_instance(shop)
        except ShopProduct.DoesNotExist:
            return {
                "errorText": _("Product %(product)s is not available in the %(shop)s shop.") %
                {"product": product.name, "shop": shop.name}
            }

        min_quantity = shop_product.minimum_purchase_quantity
        # Make quantity to be at least minimum quantity
        quantity = (min_quantity if quantity < min_quantity else quantity)
        customer = Contact.objects.filter(pk=customer_id).first() if customer_id else None
        price_info = get_price_info(shop, customer, product, quantity)

        supplier = None
        if supplier_id:
            supplier = shop_product.suppliers.enabled().filter(id=supplier_id).first()

        if not supplier:
            supplier = shop_product.get_supplier(customer, quantity)

        stock_status = supplier.get_stock_status(product.pk) if supplier else None
        return {
            "id": product.id,
            "sku": product.sku,
            "name": product.name,
            "quantity": quantity,
            "logicalCount": stock_status.logical_count if stock_status else 0,
            "physicalCount": stock_status.physical_count if stock_status else 0,
            "salesDecimals": product.sales_unit.decimals if product.sales_unit else 0,
            "salesUnit": product.sales_unit.symbol if product.sales_unit else "",
            "purchaseMultiple": shop_product.purchase_multiple,
            "taxClass": {
                "id": product.tax_class.id,
                "name": force_text(product.tax_class),
            },
            "baseUnitPrice": {
                "value": price_info.base_unit_price.value,
                "includesTax": price_info.base_unit_price.includes_tax
            },
            "unitPrice": {
                "value": price_info.discounted_unit_price.value,
                "includesTax": price_info.base_unit_price.includes_tax
            },
            "product": {
                "text": product.name,
                "id": product.id,
                "url": get_model_url(product, shop=request.shop)
            }
        }
Exemplo n.º 8
0
 def get_breadcrumb_parents(self):
     return [
         MenuEntry(
             text="%s" % self.object,
             url=get_model_url(self.object, shop=self.request.shop)
         )
     ]
Exemplo n.º 9
0
    def save_form_parts(self, form):
        is_new = (not self.object.pk)
        form_parts = self.get_form_parts(self.object)
        for form_part in form_parts:
            retval = form_part.form_valid(form)

            if retval is not None:  # Allow a form part to change the identity of the object
                self.object = retval
                for form_part in form_parts:
                    form_part.object = self.object
        if is_new:
            object_created.send(sender=type(self.object), object=self.object)

        self._add_create_or_change_message(self.request, self.object, is_new)

        if self.request.GET.get("redirect") and not self.request.POST.get("__next"):
            return HttpResponseRedirect(self.request.GET.get("redirect"))

        if hasattr(self, "get_success_url"):
            return HttpResponseRedirect(self.get_success_url())

        if is_new:
            return HttpResponseRedirect(get_model_url(self.object, shop=self.request.shop))
        else:
            return HttpResponseRedirect(self.request.path)
Exemplo n.º 10
0
 def _get_children_items(self, children):
     for child in children:
         yield DropdownItem(
             text=_("Child: %s") % child,
             icon="fa fa-eye",
             url=get_model_url(child),
         )
Exemplo n.º 11
0
    def render_text(self, obj):
        url = getattr(obj, "url", None)
        text = ""
        if obj:
            text = force_text(obj)
            self.empty_text = False
            if not url:
                try:
                    url = get_model_url(obj)
                except NoModelUrl:
                    pass

        if not url:
            url = "#"

        css_style = ""

        if self.empty_text or not text:
            css_style = "display: none"

        icon = "<i class='%s'></i>" % self.external_icon

        return mark_safe(
            ("<a class=\"btn btn-inverse browse-text btn-sm\" style=\"%(css_style)s\" \
            href=\"%(url)s\" target=\"_blank\">%(icon)s %(text)s</a>") % {
                "css_style": css_style,
                "icon": icon,
                "text": escape(text),
                "url": escape(url),
            })
Exemplo n.º 12
0
 def get_breadcrumb_parents(self):
     return [
         MenuEntry(
             text=self.object,
             url=get_model_url(self.object)
         )
     ]
Exemplo n.º 13
0
 def _get_children_items(self, children):
     for child in children:
         yield DropdownItem(
             text=_("Child: %s") % child,
             icon="fa fa-eye",
             url=get_model_url(child),
         )
Exemplo n.º 14
0
 def get_toolbar(self):
     toolbar = get_default_edit_toolbar(self,
                                        "permissions_form",
                                        discard_url=get_model_url(
                                            self.object),
                                        with_split_save=False)
     return toolbar
Exemplo n.º 15
0
    def form_valid(self, form):
        product_ids_to_quantities = dict(
            (int(key.replace("q_", "")), value)
            for (key, value)
            in six.iteritems(form.cleaned_data)
            if key.startswith("q_") and value > 0
        )
        order = self.object
        product_map = Product.objects.in_bulk(set(product_ids_to_quantities.keys()))
        products_to_quantities = dict(
            (product_map[product_id], quantity)
            for (product_id, quantity)
            in six.iteritems(product_ids_to_quantities)
        )

        unsaved_shipment = Shipment(order=order, supplier=form.cleaned_data["supplier"])
        for extend_class in get_provide_objects(FORM_MODIFIER_PROVIDER_KEY):
            extend_class().form_valid_hook(form, unsaved_shipment)
        try:
            shipment = order.create_shipment(
                product_quantities=products_to_quantities,
                shipment=unsaved_shipment
            )
        except NoProductsToShipException:
            messages.error(self.request, _("No products to ship."))
            return self.form_invalid(form)
        else:
            messages.success(self.request, _("Shipment %s created.") % shipment.id)
            return HttpResponseRedirect(get_model_url(order))
Exemplo n.º 16
0
 def get_toolbar(self):
     toolbar = get_default_edit_toolbar(
         self,
         self.get_save_form_id(),
         discard_url=(get_model_url(self.object) if self.object.pk else None)
     )
     # TODO: Add extensibility
     return toolbar
Exemplo n.º 17
0
 def get_toolbar(self):
     toolbar = get_default_edit_toolbar(
         self,
         "permissions_form",
         discard_url=get_model_url(self.object),
         with_split_save=False
     )
     return toolbar
Exemplo n.º 18
0
    def get(self, request):  # noqa (C901)
        model_name = request.GET.get("model")
        object_id = request.GET.get("pk", request.GET.get("id"))

        if not model_name or not object_id:
            return HttpResponseBadRequest(_("Invalid object."))

        url = None

        try:
            model = apps.get_model(model_name)
        except LookupError:
            return HttpResponseBadRequest(_("Invalid model."))

        instance = model.objects.filter(pk=object_id).first()
        if instance:
            try:
                # try edit first
                try:
                    url = get_model_url(instance,
                                        kind="edit",
                                        user=request.user,
                                        shop=get_shop(request),
                                        raise_permission_denied=True)
                except NoModelUrl:
                    # try detail
                    try:
                        url = get_model_url(instance,
                                            kind="detail",
                                            user=request.user,
                                            shop=get_shop(request),
                                            raise_permission_denied=True)
                    except NoModelUrl:
                        pass
            except PermissionDenied as exception:
                from shuup.utils.django_compat import force_text
                raise Problem(force_text(exception))

            if url:
                # forward the mode param
                if request.GET.get("mode"):
                    url = "{}?mode={}".format(url, request.GET["mode"])

                return HttpResponseRedirect(url)

        raise Http404(_("Object not found."))
Exemplo n.º 19
0
def check_for_delete(view, request, object):
    can_delete = object.can_delete()
    delete_url = get_model_url(object, "delete")
    response = view(request, pk=object.pk)
    if hasattr(response, "render"):
        response.render()
    assert response.status_code in [200, 302]
    assert bool(delete_url in force_text(response.content)) == can_delete
Exemplo n.º 20
0
def check_for_delete(view, request, object):
    can_delete = object.can_delete()
    delete_url = get_model_url(object, "delete")
    response = view(request, pk=object.pk)
    if hasattr(response, "render"):
        response.render()
    assert response.status_code in [200, 302]
    assert bool(delete_url in force_text(response.content)) == can_delete
Exemplo n.º 21
0
 def get_toolbar(self):
     save_form_id = self.get_save_form_id()
     object = self.get_object()
     delete_url = get_model_url(object, "delete") if object.pk else None
     return get_default_edit_toolbar(
         self,
         save_form_id,
         delete_url=(delete_url if object.can_delete() else None))
Exemplo n.º 22
0
 def get_toolbar(self):
     toolbar = get_default_edit_toolbar(
         self,
         "change_password_form",
         discard_url=get_model_url(self.object),
         with_split_save=False
     )
     return toolbar
Exemplo n.º 23
0
 def format_target(self, instance, *args, **kwargs):
     if instance.target:
         try:
             return '<a href=%s target="_blank">%s</a>' % (get_model_url(
                 instance.target), instance.target)
         except Exception as e:
             return instance.target
     return "-"
Exemplo n.º 24
0
 def get_object_url(self, instance):
     try:
         return get_model_url(instance,
                              user=self.request.user,
                              shop=self.request.shop)
     except NoModelUrl:
         pass
     return None
Exemplo n.º 25
0
 def get_toolbar(self):
     toolbar = get_default_edit_toolbar(
         self,
         self.get_save_form_id(),
         discard_url=(get_model_url(self.object)
                      if self.object.pk else None))
     # TODO: Add extensibility
     return toolbar
Exemplo n.º 26
0
 def get_search_results(self, request, query):
     minimum_query_length = 3
     if len(query) >= minimum_query_length:
         users = User.objects.filter(Q(username__icontains=query) | Q(email=query))
         for i, user in enumerate(users[:10]):
             relevance = 100 - i
             yield SearchResult(
                 text=six.text_type(user), url=get_model_url(user), category=_("Contacts"), relevance=relevance
             )
Exemplo n.º 27
0
 def get_search_results(self, request, query):
     minimum_query_length = 3
     if len(query) >= minimum_query_length:
         users = get_user_model().objects.filter(Q(username__icontains=query) | Q(email=query))
         for i, user in enumerate(users[:10]):
             relevance = 100 - i
             yield SearchResult(
                 text=six.text_type(user), url=get_model_url(user), category=self.category, relevance=relevance
             )
Exemplo n.º 28
0
def test_edit_object_view(rf, admin_user, creator_fn):
    shop = factories.get_default_shop()
    view = EditObjectView.as_view()
    object_instance = creator_fn()
    model = ".".join(
        ContentType.objects.get_for_model(object_instance).natural_key())

    # correct shop
    response = _get_edit_object_view(rf, view, model, object_instance.id,
                                     admin_user, shop)
    assert response.status_code == 302

    urls = []

    try:
        urls.append(
            get_model_url(object_instance,
                          kind="edit",
                          user=admin_user,
                          shop=shop))
    except NoModelUrl:
        pass

    try:
        urls.append(
            get_model_url(object_instance,
                          kind="detail",
                          user=admin_user,
                          shop=shop))
    except NoModelUrl:
        pass

    assert response.url in urls

    # pass the mode query parameter
    response = _get_edit_object_view(rf,
                                     view,
                                     model,
                                     object_instance.id,
                                     admin_user,
                                     shop,
                                     mode="test")
    assert response.status_code == 302
    assert "mode=test" in response.url
Exemplo n.º 29
0
 def get_help_blocks(self, request, kind):
     yield SimpleHelpBlock(
         text=_("Add a product category to organize your products"),
         actions=[{
             "text": _("New category"),
             "url": get_model_url(Category, "new")
         }],
         icon_url="shuup_admin/img/category.png",
         category=HelpBlockCategory.PRODUCTS,
         priority=1,
         done=Category.objects.exists() if kind == "setup" else False)
Exemplo n.º 30
0
    def get_toolbar(self):
        toolbar = get_default_edit_toolbar(
            self,
            self.get_save_form_id(),
            discard_url=(get_model_url(self.object) if self.object.pk else None)
        )

        for button in get_provide_objects("admin_contact_edit_toolbar_button"):
            toolbar.append(button(self.object))

        return toolbar
Exemplo n.º 31
0
    def get_toolbar(self):
        toolbar = get_default_edit_toolbar(
            self,
            self.get_save_form_id(),
            discard_url=(get_model_url(self.object)
                         if self.object.pk else None))

        for button in get_provide_objects("admin_contact_edit_toolbar_button"):
            toolbar.append(button(self.object))

        return toolbar
Exemplo n.º 32
0
 def get_search_results(self, request, query):
     minimum_query_length = 3
     if len(query) >= minimum_query_length:
         contacts = Contact.objects.filter(
             Q(name__icontains=query) | Q(email=query))
         for i, contact in enumerate(contacts[:10]):
             relevance = 100 - i
             yield SearchResult(text=six.text_type(contact),
                                url=get_model_url(contact),
                                category=self.category,
                                relevance=relevance)
Exemplo n.º 33
0
    def form_valid(self, form):
        order = self.object
        restock_products = bool(form.cleaned_data.get("restock_products"))

        try:
            order.create_full_refund(restock_products)
        except NoRefundToCreateException:
            messages.error(self.request, _("Could not create a full refund."))
            return self.form_invalid(form)

        messages.success(self.request, _("Full refund created."))
        return HttpResponseRedirect(get_model_url(order))
Exemplo n.º 34
0
    def get(self, request, *args, **kwargs):
        order = self.object = self.get_object()
        billing_address = order.billing_address
        customer_email = (billing_address.email if billing_address
                          and billing_address.email else order.email)
        if not customer_email:
            messages.error(self.request,
                           _("Missing to email for the payment link."))
            return HttpResponseRedirect(get_model_url(self.get_object()))

        params = dict(order=order,
                      customer_email=customer_email,
                      payment_link=reverse("shuup:stripe_payment_view",
                                           kwargs={
                                               "pk": order.pk,
                                               "key": order.key
                                           }),
                      language=order.language)
        SendStripePaymentLink(**params).run(shop=order.shop)
        messages.success(self.request, _("Payment link send!"))
        return HttpResponseRedirect(get_model_url(self.get_object()))
Exemplo n.º 35
0
    def form_valid(self, form):
        order = self.object
        restock_products = bool(form.cleaned_data.get("restock_products"))

        try:
            order.create_full_refund(restock_products)
        except NoRefundToCreateException:
            messages.error(self.request, _("Could not create full refund."))
            return self.form_invalid(form)

        messages.success(self.request, _("Full refund created."))
        return HttpResponseRedirect(get_model_url(order))
Exemplo n.º 36
0
def test_product_module_search(rf, admin_user):
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)

    with replace_modules([ProductModule]):
        with admin_only_urls():
            default_product = get_default_product()
            model_url = get_model_url(default_product)
            sku = default_product.sku
            assert any(sr.url == model_url for sr in get_search_results(request, query=sku))  # Queries work
            assert any(sr.is_action for sr in get_search_results(request, query=sku[:5]))  # Actions work
            assert empty_iterable(get_search_results(request, query=sku[:2]))  # Short queries don't
Exemplo n.º 37
0
 def get_help_blocks(self, request, kind):
     yield SimpleHelpBlock(
         text=_("Add a product category to organize your products"),
         actions=[{
             "text": _("New category"),
             "url": get_model_url(Category, "new")
         }],
         icon_url="shuup_admin/img/category.png",
         category=HelpBlockCategory.PRODUCTS,
         priority=1,
         done=Category.objects.exists() if kind == "setup" else False
     )
Exemplo n.º 38
0
def test_product_module_search(rf, admin_user):
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)

    with replace_modules([ProductModule]):
        with admin_only_urls():
            default_product = get_default_product()
            model_url = get_model_url(default_product)
            sku = default_product.sku
            assert any(sr.url == model_url for sr in get_search_results(request, query=sku))  # Queries work
            assert any(sr.is_action for sr in get_search_results(request, query=sku[:5]))  # Actions work
            assert empty_iterable(get_search_results(request, query=sku[:2]))  # Short queries don't
Exemplo n.º 39
0
def test_model_url_with_permissions():
    permissions = set(
        ["shop_product.new", "shop_product.delete", "shop_product.edit"])
    shop = get_default_shop()
    p = get_default_product()

    # If no user is given, don't check for permissions
    assert get_model_url(p, shop=shop)

    # If a user is given and no permissions are provided, check for default model permissions
    user = get_default_staff_user()
    with pytest.raises(NoModelUrl):
        assert get_model_url(p, user=user, shop=shop)

    # If a user is given and permissions are provided, check for those permissions
    assert get_model_url(p, user=user, required_permissions=(), shop=shop)
    with pytest.raises(NoModelUrl):
        assert get_model_url(p,
                             user=user,
                             required_permissions=["shop_product.new"],
                             shop=shop)

    # Confirm that url is returned with correct permissions
    set_permissions_for_group(user.groups.first(), permissions)
    assert get_model_url(p, user=user, shop=shop)
    assert get_model_url(p,
                         user=user,
                         required_permissions=permissions,
                         shop=shop)
Exemplo n.º 40
0
def test_model_url_with_permissions():
    permissions = set(
        ["shuup.add_product", "shuup.delete_product", "shuup.change_product"])
    shop = get_default_shop()

    p = get_default_product()

    # If no user is given, don't check for permissions
    assert get_model_url(p, shop=shop)

    # If a user is given and no permissions are provided, check for default model permissions
    user = StaffUser()
    with pytest.raises(NoModelUrl):
        assert get_model_url(p, user=user, shop=shop)

    # If a user is given and permissions are provided, check for those permissions
    assert get_model_url(p, user=user, required_permissions=(), shop=shop)
    with pytest.raises(NoModelUrl):
        assert get_model_url(p,
                             user=user,
                             required_permissions=["shuup.add_product"],
                             shop=shop)

    # Confirm that url is returned with correct permissions
    user.permissions = permissions
    assert get_model_url(p, user=user, shop=shop)
    assert get_model_url(p,
                         user=user,
                         required_permissions=permissions,
                         shop=shop)
Exemplo n.º 41
0
    def handle_product_data(self, request):
        product_id = request.GET["id"]
        shop_id = request.GET["shop_id"]
        customer_id = request.GET.get("customer_id")
        quantity = decimal.Decimal(request.GET.get("quantity", 1))
        product = Product.objects.filter(pk=product_id).first()
        if not product:
            return {"errorText": _("Product %s does not exist.") % product_id}
        shop = Shop.objects.get(pk=shop_id)
        try:
            shop_product = product.get_shop_instance(shop)
        except ObjectDoesNotExist:
            return {
                "errorText": _("Product %(product)s is not available in the %(shop)s shop.") %
                {"product": product.name, "shop": shop.name}
            }

        min_quantity = shop_product.minimum_purchase_quantity
        # Make quantity to be at least minimum quantity
        quantity = (min_quantity if quantity < min_quantity else quantity)
        customer = Contact.objects.filter(pk=customer_id).first() if customer_id else None
        price_info = get_price_info(shop, customer, product, quantity)
        supplier = shop_product.suppliers.first()  # TODO: Allow setting a supplier?
        stock_status = supplier.get_stock_status(product.pk) if supplier else None
        return {
            "id": product.id,
            "sku": product.sku,
            "name": product.name,
            "quantity": quantity,
            "logicalCount": stock_status.logical_count if stock_status else 0,
            "physicalCount": stock_status.physical_count if stock_status else 0,
            "salesDecimals": product.sales_unit.decimals if product.sales_unit else 0,
            "salesUnit": product.sales_unit.short_name if product.sales_unit else "",
            "purchaseMultiple": shop_product.purchase_multiple,
            "taxClass": {
                "id": product.tax_class.id,
                "name": force_text(product.tax_class),
            },
            "baseUnitPrice": {
                "value": price_info.base_unit_price.value,
                "includesTax": price_info.base_unit_price.includes_tax
            },
            "unitPrice": {
                "value": price_info.discounted_unit_price.value,
                "includesTax": price_info.base_unit_price.includes_tax
            },
            "product": {
                "text": product.name,
                "id": product.id,
                "url": get_model_url(product)
            }
        }
Exemplo n.º 42
0
def test_product_module_search(rf, admin_user):
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)

    with replace_modules([CategoryModule, ImportAdminModule, ProductModule,
                          ProductTypeModule, ManufacturerModule, PaymentMethodModule, ShippingMethodModule]):
        with admin_only_urls():
            default_product = get_default_product()
            model_url = get_model_url(default_product, shop=get_shop(request))
            sku = default_product.sku
            assert any(sr.url == model_url for sr in get_search_results(request, query=sku))  # Queries work
            assert any(sr.is_action for sr in get_search_results(request, query=sku[:5]))  # Actions work
            assert empty_iterable(get_search_results(request, query=sku[:2]))  # Short queries don't
Exemplo n.º 43
0
 def get_search_results(self, request, query):
     minimum_query_length = 3
     if len(query) >= minimum_query_length:
         categories = Category.objects.filter(
             Q(translations__name__icontains=query)
             | Q(identifier__icontains=query)).distinct().order_by(
                 "tree_id", "lft")
         for i, category in enumerate(categories[:10]):
             relevance = 100 - i
             yield SearchResult(text=six.text_type(category),
                                url=get_model_url(category),
                                category=self.category,
                                relevance=relevance)
Exemplo n.º 44
0
def test_product_module_search(rf, admin_user):
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)

    with replace_modules([CategoryModule, ImportAdminModule, ProductModule, MediaModule,
                          ProductTypeModule, ManufacturerModule, PaymentMethodModule, ShippingMethodModule]):
        with admin_only_urls():
            default_product = get_default_product()
            model_url = get_model_url(default_product, shop=get_shop(request))
            sku = default_product.sku
            assert any(sr.url == model_url for sr in get_search_results(request, query=sku))  # Queries work
            assert any(sr.is_action for sr in get_search_results(request, query=sku[:5]))  # Actions work
            assert empty_iterable(get_search_results(request, query=sku[:2]))  # Short queries don't
Exemplo n.º 45
0
 def get_search_results(self, request, query):
     minimum_query_length = 3
     if len(query) >= minimum_query_length:
         contacts = Contact.objects.filter(
             Q(name__icontains=query) |
             Q(email=query)
         )
         for i, contact in enumerate(contacts[:10]):
             relevance = 100 - i
             yield SearchResult(
                 text=six.text_type(contact), url=get_model_url(contact),
                 category=_("Contacts"), relevance=relevance
             )
Exemplo n.º 46
0
 def form_valid(self, form):
     order = self.object
     amount = Money(form.cleaned_data["amount"], order.currency)
     if amount.value == 0:
         messages.error(self.request, _("Payment amount cannot be 0"))
         return self.form_invalid(form)
     try:
         payment = order.create_payment(amount, description="Manual payment")
         messages.success(self.request, _("Payment %s created.") % payment.payment_identifier)
     except NoPaymentToCreateException:
         messages.error(self.request, _("Order has already been paid"))
         return self.form_invalid(form)
     else:
         return HttpResponseRedirect(get_model_url(order))
Exemplo n.º 47
0
 def get_help_blocks(self, request, kind):
     from shuup.admin.utils.permissions import has_permission
     if has_permission(request.user, "category.new"):
         yield SimpleHelpBlock(
             text=_("Add a product category to organize your products"),
             actions=[{
                 "text": _("New category"),
                 "url": get_model_url(Category, "new")
             }],
             icon_url="shuup_admin/img/category.png",
             category=HelpBlockCategory.PRODUCTS,
             priority=1,
             done=Category.objects.filter(
                 shops=request.shop).exists() if kind == "setup" else False)
Exemplo n.º 48
0
    def get_search_results(self, request, query):
        shop = get_shop(request)

        if len(query) >= 3:
            contact = get_person_contact(request.user)
            tasks = (Task.objects.for_shop(get_shop(request)).filter(
                name__icontains=query).assigned_to(contact).exclude(
                    status__in=(TaskStatus.DELETED, TaskStatus.COMPLETED)))
            for task in tasks:
                yield SearchResult(text=force_text(
                    "{task_name} [{task_status}]".format(
                        **dict(task_name=task.name, task_status=task.status))),
                                   url=get_model_url(task, shop=shop),
                                   category=_("Tasks"))
Exemplo n.º 49
0
 def form_valid(self, form):
     order = self.object
     amount = Money(form.cleaned_data["amount"], order.currency)
     if amount.value == 0:
         messages.error(self.request, _("Payment amount cannot be 0"))
         return self.form_invalid(form)
     try:
         payment = order.create_payment(amount, description="Manual payment")
         messages.success(self.request, _("Payment %s created.") % payment.payment_identifier)
     except NoPaymentToCreateException:
         messages.error(self.request, _("Order has already been paid"))
         return self.form_invalid(form)
     else:
         return HttpResponseRedirect(get_model_url(order))
Exemplo n.º 50
0
 def post(self, request, *args, **kwargs):
     order = self.object = self.get_object()
     error = False
     if order.payment_status not in (PaymentStatus.DEFERRED, PaymentStatus.NOT_PAID):
         error = True
         messages.error(self.request, _("Only orders which are not paid or deferred can be set as paid."))
     if order.taxful_total_price:
         error = True
         messages.error(self.request, _("Only zero price orders can be set as paid without creating a payment."))
     if not error:
         amount = Money(0, order.shop.currency)
         order.create_payment(amount, description=_("Zero amount payment"))
         messages.success(self.request, _("Order marked as paid."))
     return HttpResponseRedirect(get_model_url(self.get_object()))
Exemplo n.º 51
0
 def post(self, request, *args, **kwargs):
     order = self.object = self.get_object()
     error = False
     if not order.is_not_paid():
         error = True
         messages.error(self.request, _("Only orders which are not paid can be set as paid."))
     if order.taxful_total_price:
         error = True
         messages.error(self.request, _("Only zero price orders can be set as paid without creating a payment."))
     if not error:
         amount = Money(0, order.shop.currency)
         order.create_payment(amount, description=_("Zero amount payment"))
         messages.success(self.request, _("Order marked as paid."))
     return HttpResponseRedirect(get_model_url(self.get_object()))
Exemplo n.º 52
0
    def delete(self, request, *args, **kwargs):
        order = self.get_object()
        payment_id = request.POST.get("payment")
        order_url = get_model_url(self.get_object())
        payment = order.payments.filter(pk=payment_id).first() if payment_id else None

        if not payment:
            messages.error(self.request, _("Payment doesn't exist."))
            return HttpResponseRedirect(order_url)

        payment.delete()
        order.update_payment_status()
        messages.success(self.request, _("Payment deleted."))
        return HttpResponseRedirect(order_url)
Exemplo n.º 53
0
 def get_help_blocks(self, request, kind):
     from shuup.admin.utils.permissions import has_permission
     if has_permission(request.user, "category.new"):
         yield SimpleHelpBlock(
             text=_("Add a product category to organize your products"),
             actions=[{
                 "text": _("New category"),
                 "url": get_model_url(Category, "new")
             }],
             icon_url="shuup_admin/img/category.png",
             category=HelpBlockCategory.PRODUCTS,
             priority=1,
             done=Category.objects.filter(shops=request.shop).exists() if kind == "setup" else False
         )
Exemplo n.º 54
0
    def delete(self, request, *args, **kwargs):
        order = self.get_object()
        payment_id = request.POST.get("payment")
        order_url = get_model_url(self.get_object())
        payment = order.payments.filter(pk=payment_id).first() if payment_id else None

        if not payment:
            messages.error(self.request, _("Payment doesn't exist."))
            return HttpResponseRedirect(order_url)

        payment.delete()
        order.update_payment_status()
        messages.success(self.request, _("Payment deleted."))
        return HttpResponseRedirect(order_url)
Exemplo n.º 55
0
    def get_search_results(self, request, query):
        minimum_query_length = 3
        if len(query) >= minimum_query_length:
            orders = Order.objects.filter(
                Q(identifier__istartswith=query)
                | Q(reference_number__istartswith=query)
                | Q(email__icontains=query)
                | Q(phone__icontains=query)).order_by("-id")[:15]

            for i, order in enumerate(orders):
                relevance = 100 - i
                yield SearchResult(text=six.text_type(order),
                                   url=get_model_url(order),
                                   category=_("Orders"),
                                   relevance=relevance)
Exemplo n.º 56
0
 def get_context_data(self, **kwargs):
     context = super(EditScriptContentView, self).get_context_data(**kwargs)
     context["title"] = get_create_or_change_title(self.request, self.object)
     context["action_infos"] = Action.get_ui_info_map()
     context["condition_infos"] = Condition.get_ui_info_map()
     context["cond_op_names"] = get_enum_choices_dict(StepConditionOperator)
     context["step_next_names"] = get_enum_choices_dict(StepNext)
     context["toolbar"] = Toolbar([
         JavaScriptActionButton(
             text="Save", icon="fa fa-save", extra_css_class="btn-success",
             onclick="ScriptEditor.save();return false"
         ),
         get_discard_button(get_model_url(self.object, "edit"))
     ])
     return context
Exemplo n.º 57
0
    def get_success_url(self):
        if self.request.GET.get("mode", "") == "iframe":
            quick_add_target = self.request.GET.get("quick_add_target")
            return "%s?mode=iframe&quick_add_target=%s&iframe_close=yes" % (
                get_model_url(self.object), quick_add_target)

        next = self.request.POST.get("__next")
        try:
            if next == "return":
                return self.get_return_url()
            elif next == "new":
                return self.get_new_url()
        except NoModelUrl:
            pass

        try:
            return super(CreateOrUpdateView, self).get_success_url()
        except ImproperlyConfigured:
            pass

        try:
            return get_model_url(self.object)
        except NoModelUrl:
            pass
Exemplo n.º 58
0
 def get_search_results(self, request, query):
     minimum_query_length = 3
     if len(query) >= minimum_query_length:
         categories = Category.objects.filter(
             Q(translations__name__icontains=query) |
             Q(identifier__icontains=query)
         ).distinct().order_by("tree_id", "lft")
         for i, category in enumerate(categories[:10]):
             relevance = 100 - i
             yield SearchResult(
                 text=six.text_type(category),
                 url=get_model_url(category),
                 category=self.category,
                 relevance=relevance
             )