Пример #1
0
def test_display_queryset(regular_user):
    shop = get_default_shop()
    anonymous_group = AnonymousContact().get_default_group()
    PersonContact().get_default_group()
    CompanyContact().get_default_group()
    assert get_groups_for_price_display_create(shop).count() == 3
    assert get_price_displays_for_shop(None).count() == 3
    assert get_price_displays_for_shop(shop).count() == 3

    get_person_contact(regular_user)

    assert get_price_displays_for_shop(shop).count() == 3

    # create new group display (from admin usually)
    ContactGroupPriceDisplay.objects.create(group=anonymous_group, shop=shop)

    for_create = get_groups_for_price_display_create(shop)
    assert for_create.count() == 2
    assert anonymous_group not in for_create

    items = get_price_displays_for_shop(shop)
    assert items.count() == 3
    for item in items:
        if item.group == anonymous_group:
            assert item.shop
        else:
            assert not item.shop
        assert item.group.identifier in PROTECTED_CONTACT_GROUP_IDENTIFIERS

    new_group = ContactGroup.objects.create(identifier="test", shop=shop)

    items = get_price_displays_for_shop(shop)
    assert items.count() == 4
    for item in items:
        if item.group in [new_group, anonymous_group]:
            assert item.shop
        else:
            assert not item.shop
        if item.group != new_group:
            assert item.group.identifier in PROTECTED_CONTACT_GROUP_IDENTIFIERS
        else:
            assert item.group.identifier == "test"
Пример #2
0
def test_purchasability():
    anon_contact = AnonymousContact()
    shop_product = get_default_shop_product()
    supplier = get_default_supplier()
    assert shop_product.purchasable

    shop_product.raise_if_not_orderable(supplier=supplier,
                                        customer=anon_contact,
                                        quantity=1)
    assert shop_product.is_orderable(supplier=supplier,
                                     customer=anon_contact,
                                     quantity=1)

    with modify(shop_product, purchasable=False):
        with pytest.raises(ProductNotOrderableProblem):
            shop_product.raise_if_not_orderable(supplier=supplier,
                                                customer=anon_contact,
                                                quantity=1)
        assert not shop_product.is_orderable(
            supplier=supplier, customer=anon_contact, quantity=1)
def test_discount_for_multi_group_using_customer(rf, admin_user, price, discount, anonymous_discount):
    customer = create_customer()
    anonymous = AnonymousContact()

    request, shop, _ = initialize_test(rf, True, customer)

    product = create_product("product", shop=shop, default_price=price)

    CgpDiscount.objects.create(product=product, group=customer.groups.first(), shop=shop, discount_amount_value=discount)
    CgpDiscount.objects.create(product=product, group=anonymous.get_default_group(), shop=shop, discount_amount_value=anonymous_discount)

    # discount for customer
    request, shop, _ = initialize_test(rf, True, customer)
    price_info = product.get_price_info(request)
    assert price_info.price == shop.create_price(max(price-discount, 0))

    # discount for anonymous
    request, shop, _ = initialize_test(rf, True, anonymous)
    price_info = product.get_price_info(request)
    assert price_info.price == shop.create_price(max(price-anonymous_discount, 0))
Пример #4
0
def test_pricing_module_is_active():
    """
    Make sure that our custom pricing module is active.
    """
    shop = Shop(currency="USD", prices_include_tax=False)
    customer = AnonymousContact()
    product = Product(sku="6.0745")

    pricing_mod = get_pricing_module()
    pricing_ctx = pricing_mod.get_context_from_data(shop, customer)

    pi = product.get_price_info(pricing_ctx, quantity=2)

    price = shop.create_price
    assert pi.price == price("12.149")
    assert pi.base_price == price("48.596")
    assert pi.quantity == 2
    assert pi.discounted_unit_price == price("6.0745")
    assert pi.base_unit_price == price("24.298")
    assert pi.discount_rate == Decimal("0.75")
Пример #5
0
def test_product_query(visibility, show_in_list, show_in_search, admin_user, regular_user):
    shop = get_default_shop()
    product = create_product("test-sku", shop=shop)
    shop_product = product.get_shop_instance(shop)
    anon_contact = AnonymousContact()
    regular_contact = get_person_contact(regular_user)
    admin_contact = get_person_contact(admin_user)

    shop_product.visibility = visibility
    shop_product.save()

    assert shop_product.visibility_limit == ProductVisibility.VISIBLE_TO_ALL

    # Anonymous contact should be the same as no contact
    assert (product in Product.objects.listed(shop=shop)) == show_in_list
    assert (product in Product.objects.searchable(shop=shop)) == show_in_search
    assert (product in Product.objects.listed(shop=shop, customer=anon_contact)) == show_in_list
    assert (product in Product.objects.searchable(shop=shop, customer=anon_contact)) == show_in_search

    # Admin should see all non-deleted results
    configuration.set(None, get_all_seeing_key(admin_contact), True)
    assert product in Product.objects.listed(shop=shop, customer=admin_contact)
    assert product in Product.objects.searchable(shop=shop, customer=admin_contact)

    # Anonymous contact shouldn't see products with logged in visibility limit
    shop_product.visibility_limit = ProductVisibility.VISIBLE_TO_LOGGED_IN
    shop_product.save()
    assert product not in Product.objects.listed(shop=shop, customer=anon_contact)
    assert product not in Product.objects.searchable(shop=shop, customer=anon_contact)

    # Reset visibility limit
    shop_product.visibility_limit = ProductVisibility.VISIBLE_TO_ALL
    shop_product.save()

    # No one should see deleted products
    product.soft_delete()
    assert product not in Product.objects.listed(shop=shop)
    assert product not in Product.objects.searchable(shop=shop)
    assert product not in Product.objects.listed(shop=shop, customer=admin_contact)
    assert product not in Product.objects.searchable(shop=shop, customer=admin_contact)
    configuration.set(None, get_all_seeing_key(admin_contact), False)
def test_supplier_price_without_selected_supplier(rf):
    shop = factories.get_shop()

    supplier1 = Supplier.objects.create(name="Test 1")
    supplier1.shops = [shop]
    supplier2 = Supplier.objects.create(name="Test 2")
    supplier2.shops = [shop]

    strategy = "shuup.testing.supplier_pricing.supplier_strategy:CheapestSupplierPriceSupplierStrategy"
    with override_settings(SHUUP_PRICING_MODULE="supplier_pricing", SHUUP_SHOP_PRODUCT_SUPPLIERS_STRATEGY=strategy):
        customer = AnonymousContact()
        pricing_mod = get_pricing_module()
        supplier1_ctx = pricing_mod.get_context_from_data(shop, customer, supplier=supplier1)
        supplier2_ctx = pricing_mod.get_context_from_data(shop, customer, supplier=supplier2)

        # Supplied by both suppliers
        product1_default_price = 10
        product1 = factories.create_product("sku1", shop=shop, supplier=supplier1, default_price=product1_default_price)
        shop_product1 = product1.get_shop_instance(shop)
        shop_product1.suppliers.add(supplier2)

        # Both suppliers should get price from shop
        # product default price
        assert product1.get_price(supplier1_ctx).amount.value == product1_default_price
        assert product1.get_price(supplier2_ctx).amount.value == product1_default_price

        # Now let's add per supplier prices
        supplier1_price = 7
        supplier2_price = 8
        SupplierPrice.objects.create(shop=shop, supplier=supplier1, product=product1, amount_value=supplier1_price)
        SupplierPrice.objects.create(shop=shop, supplier=supplier2, product=product1, amount_value=supplier2_price)

        assert product1.get_price(supplier1_ctx).amount.value == supplier1_price
        assert product1.get_price(supplier2_ctx).amount.value == supplier2_price

        # Now pricing context without defined supplier
        # should return cheapest price
        context = pricing_mod.get_context_from_data(shop, customer)
        assert shop_product1.get_supplier().pk == supplier1.pk
        assert product1.get_price(context).amount.value == supplier1_price
Пример #7
0
def _get_template_engine_and_context(product_sku='6.0745', create_var_product=False):
    engine = django.template.engines['jinja2']
    assert isinstance(engine, django_jinja.backend.Jinja2)

    shop = get_default_shop()
    shop.currency = 'USD'
    shop.prices_include_tax = False
    shop.save()

    request = RequestFactory().get('/')
    request.shop = shop
    request.customer = AnonymousContact()
    request.person = request.customer
    PriceDisplayOptions(include_taxes=False).set_for_request(request)
    tax = get_default_tax()
    create_default_tax_rule(tax)
    tax_class = get_default_tax_class()
    order, order_line = _get_order_and_order_line(request)

    product = create_product(sku=product_sku, shop=shop, tax_class=tax_class)

    if create_var_product:
        var_product = create_product(sku="32.9", shop=shop, tax_class=tax_class)
        child_product_1 = create_product(sku="4.50", shop=shop, tax_class=tax_class, supplier=get_default_supplier())
        child_product_2 = create_product(sku="12.00", shop=shop, tax_class=tax_class, supplier=get_default_supplier())
        child_product_1.link_to_parent(var_product, variables={"color": "red"})
        child_product_2.link_to_parent(var_product, variables={"color": "blue"})

    context = {
        'request': request,
        'prod': product,
        'var_prod': var_product if create_var_product else None,
        # TODO: Test also with variant products
        'sline': _get_source_line(request),
        'bline': _get_basket_line(request),
        'oline': order_line,
        'order': order
    }

    return (engine, context)
Пример #8
0
def test_simple_supplier_out_of_stock(rf, anonymous):
    supplier = get_simple_supplier()
    shop = get_default_shop()
    product = create_product("simple-test-product",
                             shop,
                             supplier,
                             stock_behavior=StockBehavior.STOCKED)

    if anonymous:
        customer = AnonymousContact()
    else:
        customer = create_random_person()

    ss = supplier.get_stock_status(product.pk)
    assert ss.product == product
    assert ss.logical_count == 0
    num = random.randint(100, 500)
    supplier.adjust_stock(product.pk, +num)
    assert supplier.get_stock_status(product.pk).logical_count == num

    shop_product = product.get_shop_instance(shop)
    assert shop_product.is_orderable(supplier, customer, 1)

    # Create order
    order = create_order_with_product(product, supplier, num, 3, shop=shop)
    order.get_product_ids_and_quantities()
    pss = supplier.get_stock_status(product.pk)
    assert pss.logical_count == 0
    assert pss.physical_count == num

    assert not shop_product.is_orderable(supplier, customer, 1)

    # Create shipment
    shipment = order.create_shipment_of_all_products(supplier)
    assert isinstance(shipment, Shipment)
    pss = supplier.get_stock_status(product.pk)
    assert pss.logical_count == 0
    assert pss.physical_count == 0

    assert not shop_product.is_orderable(supplier, customer, 1)
Пример #9
0
def _get_order(prices_include_tax=False, include_basket_campaign=False, include_catalog_campaign=False):
    shop = get_shop(prices_include_tax=prices_include_tax)
    supplier = get_simple_supplier()

    if include_basket_campaign:
        _add_basket_campaign(shop)

    if include_catalog_campaign:
        _add_catalog_campaign(shop)
    _add_taxes()

    source = BasketishOrderSource(shop)
    source.status = get_initial_order_status()
    ctx = get_pricing_module().get_context_from_data(shop, AnonymousContact())
    for product_data in _get_product_data():
        quantity = product_data.pop("quantity")
        product = create_product(
            sku=product_data.pop("sku"),
            shop=shop,
            supplier=supplier,
            stock_behavior=StockBehavior.STOCKED,
            tax_class=get_default_tax_class(),
            **product_data)
        shop_product = product.get_shop_instance(shop)
        shop_product.categories.add(get_default_category())
        shop_product.save()
        supplier.adjust_stock(product.id, INITIAL_PRODUCT_QUANTITY)
        pi = product.get_price_info(ctx)
        source.add_line(
            type=OrderLineType.PRODUCT,
            product=product,
            supplier=supplier,
            quantity=quantity,
            base_unit_price=pi.base_unit_price,
            discount_amount=pi.discount_amount
        )
    oc = OrderCreator()
    order = oc.create_order(source)
    return order
Пример #10
0
def test_category_visibility(admin_user, regular_user):
    visible_public_category = Category.objects.create(status=CategoryStatus.VISIBLE, visibility=CategoryVisibility.VISIBLE_TO_ALL, identifier="visible_public", name=DEFAULT_NAME)
    hidden_public_category = Category.objects.create(status=CategoryStatus.INVISIBLE, visibility=CategoryVisibility.VISIBLE_TO_ALL, identifier="hidden_public", name=DEFAULT_NAME)
    deleted_public_category = Category.objects.create(status=CategoryStatus.DELETED, visibility=CategoryVisibility.VISIBLE_TO_ALL, identifier="deleted_public", name=DEFAULT_NAME)
    logged_in_category = Category.objects.create(status=CategoryStatus.VISIBLE, visibility=CategoryVisibility.VISIBLE_TO_LOGGED_IN, identifier="visible_logged_in", name=DEFAULT_NAME)
    group_visible_category = Category.objects.create(status=CategoryStatus.VISIBLE, visibility=CategoryVisibility.VISIBLE_TO_GROUPS, identifier="visible_groups", name=DEFAULT_NAME)

    assert visible_public_category.name == DEFAULT_NAME
    assert str(visible_public_category) == DEFAULT_NAME

    anon_contact = AnonymousContact()
    regular_contact = get_person_contact(regular_user)
    admin_contact = get_person_contact(admin_user)

    for (customer, category, expect) in [
        (anon_contact, visible_public_category, True),
        (anon_contact, hidden_public_category, False),
        (anon_contact, deleted_public_category, False),
        (anon_contact, logged_in_category, False),
        (anon_contact, group_visible_category, False),

        (regular_contact, visible_public_category, True),
        (regular_contact, hidden_public_category, False),
        (regular_contact, deleted_public_category, False),
        (regular_contact, logged_in_category, True),
        (regular_contact, group_visible_category, False),

        (admin_contact, visible_public_category, True),
        (admin_contact, hidden_public_category, True),
        (admin_contact, deleted_public_category, False),
        (admin_contact, logged_in_category, True),
        (admin_contact, group_visible_category, True),
    ]:
        result = Category.objects.all_visible(customer=customer).filter(pk=category.pk).exists()
        assert result == expect, "Queryset visibility of %s for %s as expected" % (category.identifier, customer)
        assert category.is_visible(customer) == expect, "Direct visibility of %s for %s as expected" % (category.identifier, customer)

    assert not Category.objects.all_except_deleted().filter(pk=deleted_public_category.pk).exists(), "Deleted category does not show up in 'all_except_deleted'"
Пример #11
0
def _get_price_info_cache_key_params(context, item, quantity, **context_args):
    shop_id = context.shop.pk if hasattr(context, "shop") else 0
    customer = getattr(context, "customer", None)

    if customer:
        cached_customer_groups = getattr(customer, "_cached_customer_groups",
                                         None)
        if cached_customer_groups:
            groups = customer._cached_customer_groups
        else:
            groups = list(
                customer.groups.order_by("pk").values_list("pk", flat=True))
            customer._cached_customer_groups = groups
    else:
        anonymous_group_id = getattr(AnonymousContact,
                                     "_cached_default_group_id", None)
        if anonymous_group_id:
            groups = [AnonymousContact._cached_default_group_id]
        else:
            anonymous_group_id = AnonymousContact().default_group.pk
            AnonymousContact._cached_default_group_id = anonymous_group_id
            groups = [anonymous_group_id]

    extra_kwargs = dict()
    for key, value in context_args.items():
        if hasattr(value, "pk"):
            extra_kwargs[key] = value.pk
        else:
            extra_kwargs[key] = value

    return dict(identifier="price_info_cache",
                item=_get_price_info_namespace_for_shop(shop_id),
                context={},
                customer_groups=groups,
                quantity=str(Decimal(quantity)),
                item_id=item.pk if hasattr(item, "pk") else str(item),
                **extra_kwargs)
Пример #12
0
def test_complex_order_tax(include_taxes):
    tax = get_default_tax()
    quantities = [44, 23, 65]
    product = get_default_product()
    supplier = get_default_supplier()
    shop = get_default_shop()
    shop.prices_include_tax = include_taxes
    shop.save()

    order = create_empty_order(shop=shop)
    order.full_clean()
    order.save()

    pricing_context = get_pricing_module().get_context_from_data(
        shop=shop,
        customer=order.customer or AnonymousContact(),
    )

    total_price = Decimal("0")
    price = Decimal("50")

    for quantity in quantities:
        total_price += quantity * price
        add_product_to_order(order, supplier, product, quantity, price,
                             tax.rate, pricing_context)
    order.cache_prices()
    order.save()

    currency = "EUR"
    summary = order.get_tax_summary()[0]

    assert summary.tax_rate == tax.rate
    assert summary.based_on == Money(total_price, currency)
    assert summary.tax_amount == Money(total_price * tax.rate, currency)
    assert summary.taxful == summary.based_on + summary.tax_amount
    assert order.get_total_tax_amount() == Money(total_price * tax.rate,
                                                 currency)
Пример #13
0
def test_multishop(rf):
    shop1 = get_default_shop()
    shop2 = get_shop()
    assert shop1.pk != shop2.pk

    request = apply_request_middleware(rf.get("/"))
    assert is_anonymous(request.user)
    user = request.user
    contact = get_person_contact(user)
    assert contact == AnonymousContact()

    # both shops have anonymous groups
    group = contact.get_default_group()  # ensure default group exists

    grp1 = group.set_price_display_options(shop=shop1, hide_prices=False)
    assert grp1
    assert isinstance(grp1, ContactGroup)
    dspl1 = get_price_display_for_group_and_shop(group, shop1)
    assert isinstance(dspl1, ContactGroupPriceDisplay)
    assert not get_price_display_for_group_and_shop(group, shop2)

    # shop 2 decides to setup options
    grp2 = group.set_price_display_options(shop=shop2, hide_prices=True)
    assert grp1 == grp2  # returns same group
    assert isinstance(grp2, ContactGroup)
    dspl2 = get_price_display_for_group_and_shop(group, shop2)
    assert isinstance(dspl2, ContactGroupPriceDisplay)

    # get returns proper values
    opts11 = contact.get_price_display_options(shop=shop1)
    assert isinstance(opts11, PriceDisplayOptions)
    opts12 = contact.get_price_display_options(shop=shop2)
    assert isinstance(opts12, PriceDisplayOptions)

    assert opts11 != opts12
    assert opts11.show_prices != opts12.show_prices
Пример #14
0
def test_filter_parameter_contact_groups():
    (engine, context) = _get_template_engine_and_context()
    customer_price = 10.3
    anonymous_price = 14.6

    def get_price_info_mock(context, product, quantity=1):
        if context.customer.get_default_group() == AnonymousContact().get_default_group():
            price = context.shop.create_price(anonymous_price)
        else:
            price = context.shop.create_price(customer_price)
        return PriceInfo(quantity * price, quantity * price, quantity)

    with patch.object(DummyPricingModule, 'get_price_info', side_effect=get_price_info_mock):
        # test with anonymous
        context['request'].customer = AnonymousContact()
        context['request'].person = context['request'].customer
        result = engine.from_string("{{ prod|price(quantity=2) }}")
        assert result.render(context) == "$%0.2f" % (anonymous_price * 2)

        # test with customer
        context['request'].customer = create_random_person()
        context['request'].person = context['request'].customer
        result = engine.from_string("{{ prod|price(quantity=2) }}")
        assert result.render(context) == "$%0.2f" % (customer_price * 2)
Пример #15
0
def test_discount_for_companies(rf):
    default_price = 10
    request, product = _init_test_for_product(rf, default_price)
    assert request.customer == AnonymousContact()

    product_discount_amount = 2
    Discount.objects.create(
        shop=request.shop,
        active=True,
        contact_group=CompanyContact.get_default_group(),
        discount_amount_value=product_discount_amount,
    )
    assert product.get_price_info(request).price == request.shop.create_price(
        default_price)

    # Setting customer to request activates the discount
    request.customer = factories.create_random_company()
    assert product.get_price_info(request).price == request.shop.create_price(
        default_price - product_discount_amount)

    # Using person contact as customer means no discount
    request.customer = factories.create_random_person()
    assert product.get_price_info(request).price == request.shop.create_price(
        default_price)
Пример #16
0
def test_product_orderability():
    anon_contact = AnonymousContact()
    shop_product = get_default_shop_product()
    supplier = get_default_supplier()

    with modify(shop_product,
                visibility_limit=ProductVisibility.VISIBLE_TO_ALL,
                orderable=True):
        shop_product.raise_if_not_orderable(supplier=supplier,
                                            customer=anon_contact,
                                            quantity=1)
        assert shop_product.is_orderable(supplier=supplier,
                                         customer=anon_contact,
                                         quantity=1)

    with modify(shop_product,
                visibility_limit=ProductVisibility.VISIBLE_TO_LOGGED_IN,
                orderable=True):
        with pytest.raises(ProductNotOrderableProblem):
            shop_product.raise_if_not_orderable(supplier=supplier,
                                                customer=anon_contact,
                                                quantity=1)
        assert not shop_product.is_orderable(
            supplier=supplier, customer=anon_contact, quantity=1)
Пример #17
0
def handle_set_customer(request,
                        basket,
                        customer,
                        orderer=None):  # noqa (C901)

    if isinstance(customer, AnonymousContact):
        basket.orderer = AnonymousContact()
    else:
        if not customer.is_active:
            raise ValidationError(_("Customer is not active."),
                                  code="invalid_customer")

        if customer.pk:
            customer_shops = customer.shops.all()
            if customer_shops and basket.shop not in customer_shops:
                raise ValidationError(_(
                    "Shop does not have all the necessary permissions for this customer."
                ),
                                      code="invalid_customer_shop")

        if is_authenticated(request.user):
            request_contact = PersonContact.objects.filter(
                user=request.user).first() or AnonymousContact()
        else:
            request_contact = AnonymousContact()

        is_superuser = getattr(request.user, "is_superuser", False)
        is_staff = getattr(
            request.user, "is_staff",
            False) and request.user in basket.shop.staff_members.all()

        if isinstance(customer, PersonContact):
            # to set a customer different from the current one
            # he must be a super user or at least staff
            # but allow to set a customer when the current one is not authenticated
            if customer != request_contact and is_authenticated(request.user):

                if not (is_superuser or is_staff):
                    raise ValidationError(_(
                        "You don't have the required permission to assign this customer."
                    ),
                                          code="no_permission")

            basket.orderer = customer

        elif isinstance(customer, CompanyContact):
            if not orderer:
                raise ValidationError(_(
                    "You must specify the order, in which customer is a company."
                ),
                                      code="invalid_orderer")

            # make sure the company is saved in db
            valid_customer = (customer and customer.pk)
            if not valid_customer:
                raise ValidationError(_("Invalid customer."),
                                      code="invalid_customer")

            company_members = customer.members.all()

            if orderer not in company_members:
                raise ValidationError(
                    _("Orderer is not a member of the company."),
                    code="orderer_not_company_member")

            elif not (is_superuser
                      or is_staff) and request_contact not in company_members:
                raise ValidationError(
                    _("You are not a member of the company."),
                    code="not_company_member")

            basket.orderer = orderer

    basket.customer = customer

    return {"ok": True}
Пример #18
0
 def matches(self, context):
     customer = (context.customer
                 if context.customer is not None else AnonymousContact())
     customers_groups = customer.groups.all()
     return self.contact_groups.filter(pk__in=customers_groups).exists()
Пример #19
0
def test_contact_groups(rf, regular_user):
    shop = get_default_shop()

    assert ContactGroupPriceDisplay.objects.count() == 0
    request = apply_request_middleware(rf.get("/"))

    # default groups created for non shop and shop
    assert ContactGroupPriceDisplay.objects.count() == 2

    assert is_anonymous(request.user)
    user = request.user
    contact = get_person_contact(user)
    assert contact == AnonymousContact()

    group = contact.get_default_group()

    assert group.is_protected

    groups = ContactGroup.objects.all()
    assert groups.count() == 1
    assert not groups.filter(shop=shop).exists()
    assert groups.filter(shop__isnull=True).exists()

    group = groups.first()
    assert group.identifier == AnonymousContact.default_contact_group_identifier

    assert ContactGroupPriceDisplay.objects.count() == 2

    g1 = ContactGroupPriceDisplay.objects.first()
    assert g1.group == group
    assert not g1.shop

    assert group.price_display_options.exists()
    assert group.price_display_options.for_group_and_shop(group, shop) != group.price_display_options.first()
    assert ContactGroupPriceDisplay.objects.count() == 2  # new one was created (shop + anonymous)

    g2 = ContactGroupPriceDisplay.objects.exclude(id=g1.id).first()
    assert g2.group == group   # same group as before
    assert g2.shop == shop

    assert group.price_display_options.count() == 2

    for cgpd in ContactGroupPriceDisplay.objects.all():
        assert not cgpd.group.members.count()

    options = group.get_price_display_options()
    assert options

    # create real contact
    contact = get_person_contact(regular_user)
    assert contact.groups.count()  # contact was added to default group
    contact.add_to_shop(shop)
    group_with_shop = contact.get_default_group()
    assert contact.groups.first() == group_with_shop

    assert group_with_shop.identifier == PersonContact.default_contact_group_identifier
    assert ContactGroupPriceDisplay.objects.count() == 3  # new one was created

    g3 = ContactGroupPriceDisplay.objects.exclude(id__in=[g1.id, g2.id]).first()
    assert g3.group != group  # same group as before
    assert g3.group == group_with_shop
    assert not g3.shop  # no group as it's the default group

    groups = ContactGroup.objects.all()
    assert groups.count() == 2  # two groups
    assert not groups.filter(shop=shop).exists()  # still not exists as we are using defaults
    assert groups.filter(shop__isnull=True).count() == 2
    assert groups.filter(identifier__in=[AnonymousContact.default_contact_group_identifier, PersonContact.default_contact_group_identifier]).count() == 2

    assert ContactGroupPriceDisplay.objects.count() == 3  # no new ones created

    assert group.price_display_options.count() == 2  # all in same group

    assert group.price_display_options.for_group_and_shop(group_with_shop, shop) not in group.price_display_options.all()

    assert ContactGroupPriceDisplay.objects.count() == 4  # new was created
Пример #20
0
def test_anonymous_contact_vs_person(regular_user):
    anon = AnonymousContact()
    person = get_person_contact(regular_user)
    assert anon != person
    assert person != anon
Пример #21
0
 def customer(self):
     return (self._customer or AnonymousContact())
Пример #22
0
def get_request():
    request = RequestFactory().get('/')
    request.shop = Shop(currency='USD', prices_include_tax=False)
    request.customer = AnonymousContact()
    request.person = request.customer
def test_simple_supplier_out_of_stock(rf, anonymous, hide_unorderable_product):
    if hide_unorderable_product:
        # Connect signal to hide products when they become unorderable
        stocks_updated.connect(
            receiver=shop_product_orderability_check, dispatch_uid="shop_product_orderability_check")

    supplier = get_simple_supplier()
    shop = get_default_shop()
    product = create_product("simple-test-product", shop, supplier, stock_behavior=StockBehavior.STOCKED)

    if anonymous:
        customer = AnonymousContact()
    else:
        customer = create_random_person()

    ss = supplier.get_stock_status(product.pk)
    assert ss.product == product
    assert ss.logical_count == 0

    num = random.randint(100, 500)
    supplier.adjust_stock(product.pk, +num)
    assert supplier.get_stock_status(product.pk).logical_count == num

    shop_product = product.get_shop_instance(shop)

    if hide_unorderable_product:
        # Since the shop product save calls update stocks
        # and the fact that signal handler doesn't automatically
        # change visibility back means that the product is not
        # visible at this point.
        assert not shop_product.is_visible(customer)
        assert not shop_product.is_orderable(supplier, customer, 1, allow_cache=False)
        shop_product.visibility = ShopProductVisibility.ALWAYS_VISIBLE
        shop_product.save()

    assert shop_product.is_orderable(supplier, customer, 1, allow_cache=False)

    # Create order
    order = create_order_with_product(product, supplier, num, 3, shop=shop)
    order.get_product_ids_and_quantities()
    pss = supplier.get_stock_status(product.pk)
    assert pss.logical_count == 0
    assert pss.physical_count == num

    assert not shop_product.is_orderable(supplier, customer, 1)

    # Create shipment
    shipment = order.create_shipment_of_all_products(supplier)
    assert isinstance(shipment, Shipment)
    pss = supplier.get_stock_status(product.pk)
    assert pss.logical_count == 0
    assert pss.physical_count == 0

    shop_product.refresh_from_db()
    if hide_unorderable_product:
        assert not shop_product.is_visible(customer)
        assert not shop_product.is_purchasable(supplier, customer, 1)
        assert not shop_product.is_orderable(supplier, customer, 1)
        # Disconnect signal just in case...
        stocks_updated.disconnect(
            receiver=shop_product_orderability_check, dispatch_uid="shop_product_orderability_check")
    else:
        assert shop_product.is_visible(customer)
        assert not shop_product.is_purchasable(supplier, customer, 1)
        assert not shop_product.is_orderable(supplier, customer, 1)
Пример #24
0
def test_omniscience(admin_user, regular_user):
    assert get_person_contact(admin_user).is_all_seeing
    assert not get_person_contact(regular_user).is_all_seeing
    assert not get_person_contact(None).is_all_seeing
    assert not get_person_contact(AnonymousUser()).is_all_seeing
    assert not AnonymousContact().is_all_seeing
Пример #25
0
def test_dev_onboarding(browser, admin_user, live_server, settings):
    Shop.objects.first().delete(
    )  # Delete first shop created by test initializations
    call_command("shuup_init", *[], **{})
    shop = Shop.objects.first()
    assert not shop.maintenance_mode
    initialize_admin_browser_test(browser,
                                  live_server,
                                  settings,
                                  onboarding=True)

    browser.fill("address-first_name", "Matti")
    browser.fill("address-last_name", "Teppo")
    browser.fill("address-phone", "112")
    browser.fill("address-street", "Teststreet")
    browser.fill("address-postal_code", "20540")
    browser.fill("address-city", "Turku")

    click_element(browser, "#select2-id_address-country-container")
    wait_until_appeared(browser, "input.select2-search__field")
    browser.find_by_css("input.select2-search__field").first.value = "Finland"
    wait_until_appeared(
        browser, ".select2-results__option:not([aria-live='assertive'])")
    browser.execute_script(
        '$($(".select2-results__option")[0]).trigger({type: "mouseup"})')
    click_element(browser, "button[name='next']")

    wait_until_condition(
        browser,
        lambda x: x.is_text_present("To start accepting payments right away"))
    click_element(browser,
                  "div[data-name='manual_payment'] button[name='activate']")
    browser.fill("manual_payment-service_name", "Laskulle")
    click_element(browser, "button[name='next']")

    wait_until_condition(
        browser,
        lambda x: x.is_text_present("To start shipping products right away"))
    click_element(browser,
                  "div[data-name='manual_shipping'] button[name='activate']")
    browser.fill("manual_shipping-service_name", "Kotiinkuljetus")
    click_element(browser, "button[name='next']")

    wait_until_condition(browser,
                         lambda x: x.is_text_present("theme for your shop"))
    click_element(
        browser,
        "div[data-identifier='candy_pink'] button[data-theme='shuup.themes.classic_gray']"
    )
    click_element(browser, "button[name='next']")

    wait_until_condition(
        browser, lambda x: x.is_text_present("initial content and configure"))
    click_element(browser, "button[name='next']")

    wait_until_condition(
        browser, lambda x: x.is_text_present("install some sample data"))
    browser.execute_script(
        'document.getElementsByName("sample-categories")[0].checked=true')
    browser.execute_script(
        'document.getElementsByName("sample-products")[0].checked=true')
    click_element(browser, "button[name='next']")

    wait_until_condition(browser,
                         lambda x: x.is_text_present("Welcome to Shuup!"))

    click_element(browser, "input[value='Publish shop']")

    shop.refresh_from_db()
    assert not shop.maintenance_mode
    assert Product.objects.count() == 10
    supplier = Supplier.objects.first()
    customer = AnonymousContact()
    assert (len([
        product for product in Product.objects.all()
        if product.get_shop_instance(shop).is_orderable(supplier, customer, 1)
    ]) == 10)
Пример #26
0
def test_package_orderability():
    package_product = get_package_product()
    shop = get_default_shop()
    sp = package_product.get_shop_instance(shop)
    supplier = sp.suppliers.get()
    assert not list(sp.get_orderability_errors(supplier=supplier, quantity=1, customer=AnonymousContact()))
Пример #27
0
def _get_pricing_context(shop, customer=None):
    return get_pricing_module().get_context_from_data(
        shop=shop,
        customer=(customer or AnonymousContact()),
    )
Пример #28
0
def test_anonymity(admin_user, regular_user):
    assert not get_person_contact(admin_user).is_anonymous
    assert not get_person_contact(regular_user).is_anonymous
    assert get_person_contact(None).is_anonymous
    assert get_person_contact(AnonymousUser()).is_anonymous
    assert AnonymousContact().is_anonymous
Пример #29
0
 def orderer(self):
     return (self._orderer or AnonymousContact())
Пример #30
0
 def get_price_info_mock(context, product, quantity=1):
     if context.customer.get_default_group() == AnonymousContact().get_default_group():
         price = context.shop.create_price(anonymous_price)
     else:
         price = context.shop.create_price(customer_price)
     return PriceInfo(quantity * price, quantity * price, quantity)