Ejemplo n.º 1
0
def test_contact_module_search_multishop(rf):
    with override_settings(WSHOP_MANAGE_CONTACTS_PER_SHOP=True,
                           WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        staff_user = create_random_user(is_staff=True)

        shop1 = get_shop(identifier="shop-1", enabled=True)
        shop2 = get_shop(identifier="shop-2", enabled=True)

        shop1.staff_members.add(staff_user)
        shop2.staff_members.add(staff_user)

        cm = ContactModule()
        contact = create_random_person(locale="en_US", minimum_name_comp_len=5)
        contact.shops.add(shop2)

        request = apply_request_middleware(rf.get("/"),
                                           user=staff_user,
                                           shop=shop2)

        # find the shop
        assert not empty_iterable(
            cm.get_search_results(request, query=contact.email))
        assert not empty_iterable(
            cm.get_search_results(request, query=contact.first_name))

        # no shop found
        request = apply_request_middleware(rf.get("/"),
                                           user=staff_user,
                                           shop=shop1)
        assert empty_iterable(
            cm.get_search_results(request, query=contact.email))
Ejemplo n.º 2
0
def test_admin_script_list(rf, admin_user):
    with override_settings(WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        shop1 = factories.get_shop(identifier="shop-1")
        shop2 = factories.get_shop(identifier="shop-2")

        shop1.staff_members.add(admin_user)
        shop2.staff_members.add(admin_user)

        script_shop1 = Script.objects.create(shop=shop1,
                                             event_identifier="order_received",
                                             name="SHOP 1",
                                             enabled=True)
        script_shop2 = Script.objects.create(shop=shop2,
                                             event_identifier="order_received",
                                             name="SHOP 2",
                                             enabled=True)

        view = ScriptEditView.as_view()
        request = apply_request_middleware(rf.get("/"), user=admin_user)
        set_shop(request, shop2)

        with pytest.raises(Http404):
            response = view(request, pk=script_shop1.id)

        response = view(request, pk=script_shop2.id)
        assert response.status_code == 200
Ejemplo n.º 3
0
def test_same_codes():
    shop1 = factories.get_shop(True, "EUR")
    shop2 = factories.get_shop(True, "USD")

    dc1 = Coupon.objects.create(code="TEST")
    dc2 = Coupon.objects.create(code="TEST")


    BasketCampaign.objects.create(name="test1", active=True, shop_id=shop1.id, coupon_id=dc1.id)
    with pytest.raises(ValidationError):
        BasketCampaign.objects.create(name="test1", active=True, shop_id=shop1.id, coupon_id=dc2.id)

    BasketCampaign.objects.create(name="test2", active=True, shop_id=shop2.id, coupon_id=dc2.id)
    with pytest.raises(ValidationError):
        BasketCampaign.objects.create(name="test2", active=True, shop_id=shop2.id, coupon_id=dc1.id)

    # Disable one campaigns for dc1 and you should be able to set the code to different campaign again
    dc3 = Coupon.objects.create(code="TEST")
    BasketCampaign.objects.filter(coupon=dc1).update(active=False)
    BasketCampaign.objects.create(name="test1", active=True, shop_id=shop1.id, coupon_id=dc3.id)

    # Try to reactivate the campaign for shop1
    c = BasketCampaign.objects.filter(coupon=dc1).first()
    assert c.active == False
    with pytest.raises(ValidationError):
        c.active = True
        c.save()

    # Try to sneak one duplicate code by saving the coupon
    dc4 = Coupon.objects.create(code="TEST1")
    BasketCampaign.objects.create(name="test4", active=True, shop_id=shop2.id, coupon_id=dc4.id)
    with pytest.raises(ValidationError):
        dc4.code = "TEST"
        dc4.save()
Ejemplo n.º 4
0
def test_manufacturer_admin_simple_shop(rf, staff_user, admin_user):
    with override_settings(WSHOP_ENABLE_MULTIPLE_SHOPS=False):
        shop1 = factories.get_default_shop()
        shop1.staff_members.add(staff_user)

        factories.get_shop(identifier="shop2")

        assert Manufacturer.objects.count() == 0

        # staff user
        request = apply_request_middleware(rf.post("/",
                                                   data=dict(name="Manuf 1")),
                                           user=staff_user)
        view_func = ManufacturerEditView.as_view()
        response = view_func(request)
        assert response.status_code == 302
        assert Manufacturer.objects.first().shops.first() == shop1

        # superuser
        request = apply_request_middleware(rf.post("/",
                                                   data=dict(name="Manuf 2")),
                                           user=admin_user)
        view_func = ManufacturerEditView.as_view()
        response = view_func(request)
        assert response.status_code == 302
        assert Manufacturer.objects.count() == 2
        assert Manufacturer.objects.last().shops.first() == shop1
Ejemplo n.º 5
0
def test_contact_company_list_multishop(rf):
    with override_settings(WSHOP_MANAGE_CONTACTS_PER_SHOP=True, WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        staff_user = create_random_user(is_staff=True)

        shop1 = get_shop(identifier="shop-1", enabled=True)
        shop2 = get_shop(identifier="shop-2", enabled=True)

        shop1.staff_members.add(staff_user)
        shop2.staff_members.add(staff_user)

        # only available in shop2
        contact = create_random_person(locale="en_US", minimum_name_comp_len=5)
        contact.shops.add(shop2)

        # only available in shop1
        company = create_random_company()
        company.shops.add(shop1)

        view = ContactListView()

        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop1)
        view.request = request
        assert company in view.get_queryset()
        assert contact not in view.get_queryset()

        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop2)
        view.request = request
        assert contact in view.get_queryset()
        assert company not in view.get_queryset()
Ejemplo n.º 6
0
def test_get_shipments(admin_user):
    client = _get_client(admin_user)
    shop1 = get_shop(True)
    shop2 = get_shop(True)
    customer1 = create_random_person()
    customer2 = create_random_person()
    order1 = create_random_order(customer1, shop=shop1, completion_probability=1)
    order2 = create_random_order(customer2, shop=shop1, completion_probability=1)
    order3 = create_random_order(customer1, shop=shop2, completion_probability=1)
    order4 = create_random_order(customer2, shop=shop1, completion_probability=1)

    # list shipments
    response = client.get("/api/wshop/shipment/")
    assert response.status_code == status.HTTP_200_OK
    shipment_data = json.loads(response.content.decode("utf-8"))
    assert len(shipment_data) == 4
    assert shipment_data[0]["id"] == order1.shipments.first().pk
    assert shipment_data[1]["id"] == order2.shipments.first().pk
    assert shipment_data[2]["id"] == order3.shipments.first().pk
    assert shipment_data[3]["id"] == order4.shipments.first().pk

    # get shipment by id
    response = client.get("/api/wshop/shipment/%s/" % order1.shipments.first().pk)
    assert response.status_code == status.HTTP_200_OK
    shipment_data = json.loads(response.content.decode("utf-8"))
    assert shipment_data["id"] == order1.shipments.first().pk
    assert shipment_data["order"] == order1.pk

    # get shipment by product
    product = order2.shipments.first().products.first()
    response = client.get("/api/wshop/shipment/?product=%s" % product.pk)
    assert response.status_code == status.HTTP_200_OK
    shipment_data = json.loads(response.content.decode("utf-8"))
    for ship in shipment_data:
        for ship_product in shipment_data["product"]:
            assert ship_product["id"] == product.pk
            assert ship_product["order"] == order2.pk

    # get shipment by order
    response = client.get("/api/wshop/shipment/?order=%s" % order3.pk)
    assert response.status_code == status.HTTP_200_OK
    shipment_data = json.loads(response.content.decode("utf-8"))
    for ship in shipment_data:
        assert ship["order"] == order3.pk

    # get shipment by shop
    response = client.get("/api/wshop/shipment/?shop=%s" % shop1.pk)
    assert response.status_code == status.HTTP_200_OK
    shipment_data = json.loads(response.content.decode("utf-8"))
    for ship in shipment_data:
        assert Shipment.objects.filter(pk=ship["id"], order__shop=shop1).exists()
Ejemplo n.º 7
0
def _get_source(user, prices_include_taxes, total_price_value):
    shop = get_shop(prices_include_taxes)
    payment_method = get_payment_method(shop)
    shipping_method = get_shipping_method(shop)
    source = _seed_source(shop, user)
    source.payment_method = payment_method
    source.shipping_method = shipping_method
    assert source.payment_method_id == payment_method.id
    assert source.shipping_method_id == shipping_method.id

    supplier = get_default_supplier()
    product = create_product(sku="test-%s--%s" %
                             (prices_include_taxes, total_price_value),
                             shop=source.shop,
                             supplier=supplier,
                             default_price=total_price_value)
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=product,
        supplier=supplier,
        quantity=1,
        base_unit_price=source.create_price(total_price_value),
    )
    if prices_include_taxes:
        assert source.taxful_total_price.value == total_price_value
    else:
        assert source.taxless_total_price.value == total_price_value
    assert payment_method == source.payment_method
    assert shipping_method == source.shipping_method
    return source, shipping_method
Ejemplo n.º 8
0
def test_set_non_shop_member_customer(rf):
    """
    Set some customer to the basket that is not member of the shop
    """
    with override_settings(**CORE_BASKET_SETTINGS):
        shop = factories.get_shop(False)
        assert shop != factories.get_default_shop()

        user = factories.create_random_user()
        request = apply_request_middleware(rf.get("/"), user=user)
        basket = get_basket(request, "basket")
        basket.customer = get_person_contact(user)
        assert basket.shop == factories.get_default_shop()

        person = factories.create_random_person()
        person.shops.add(shop)

        company = factories.create_random_company()
        company.shops.add(shop)

        for customer in [person, company]:
            with pytest.raises(ValidationError) as exc:
                basket_commands.handle_set_customer(request, basket, customer)
            assert exc.value.code == "invalid_customer_shop"
            assert basket.customer == get_person_contact(user)
Ejemplo n.º 9
0
def get_request_for_contact_tests(rf):
    activate("en")
    request = rf.get("/")
    request.shop = get_shop(prices_include_tax=True)
    get_payment_method(request.shop)
    apply_request_middleware(request)
    return request
Ejemplo n.º 10
0
def _get_source(user, shipping_country, billing_country):
    prices_include_taxes = True
    shop = get_shop(prices_include_taxes)
    payment_method = get_payment_method(shop)
    shipping_method = get_shipping_method(shop)
    source = _seed_source(shop, user, shipping_country, billing_country)
    source.payment_method = payment_method
    source.shipping_method = shipping_method
    assert source.payment_method_id == payment_method.id
    assert source.shipping_method_id == shipping_method.id

    supplier = get_default_supplier()
    product = create_product(
        sku="test-%s--%s" % (prices_include_taxes, 10),
        shop=source.shop,
        supplier=supplier,
        default_price=10
    )
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=product,
        supplier=supplier,
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    assert payment_method == source.payment_method
    assert shipping_method == source.shipping_method
    return source
Ejemplo n.º 11
0
def test_stacked_tax_taxful_price():
    shop = get_shop(prices_include_tax=True, currency='EUR')
    source = OrderSource(shop)
    assert source.prices_include_tax
    source.add_line(type=OrderLineType.OTHER,
                    quantity=1,
                    base_unit_price=source.create_price(20))
    with override_provides("tax_module", TAX_MODULE_SPEC):
        with override_settings(WSHOP_TAX_MODULE="irvine"):
            source.shipping_address = MutableAddress(
                street="16215 Alton Pkwy",
                postal_code="92602",
            )
            line = source.get_final_lines(with_taxes=True)[0]
            assert isinstance(line, SourceLine)
            assert line.taxes
            assert line.taxful_price == TaxfulPrice(20, 'EUR')
            assert_almost_equal(line.taxless_price,
                                TaxlessPrice("18.52", 'EUR'))
            source.uncache()

            # Let's move out to a taxless location.
            source.shipping_address.postal_code = "11111"
            line = source.get_final_lines(with_taxes=True)[0]
            assert isinstance(line, SourceLine)
            assert not line.taxes
            assert line.taxful_price == TaxfulPrice(20, source.currency)
            assert line.taxless_price.value == Decimal("20")
Ejemplo n.º 12
0
def test_order_creator_account_manager():
    company = create_random_company()
    shop = get_shop(identifier="random-shop", enabled=True)
    source = seed_source(create_random_user(), shop)
    source.customer = company
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=get_default_product(),
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    creator = OrderCreator()
    order = creator.create_order(source)
    assert order.account_manager is None  # Company contact doesn't have account manager field

    person = create_random_person()
    person.account_manager = create_random_person()
    person.save()

    source = seed_source(create_random_user(), shop)
    source.customer = person
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=get_default_product(),
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    creator = OrderCreator()
    order = creator.create_order(source)
    assert order.account_manager is not None
    assert order.account_manager == person.account_manager
    with pytest.raises(ProtectedError):
        person.account_manager.delete()
Ejemplo n.º 13
0
def test_media_view_images(rf):
    with override_settings(WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        shop1 = factories.get_shop(identifier="shop1")
        shop1_staff1 = _create_random_staff(shop1)
        shop1_staff2 = _create_random_staff(shop1)

        shop2 = factories.get_shop(identifier="shop2")
        shop2_staff = _create_random_staff(shop2)

        # Let's agree this folder is created by for example carousel
        # so it would be shared with all the shops.
        folder = Folder.objects.create(name="Root")
        assert MediaFolder.objects.count() == 0
        path = "/%s" % folder.name

        File.objects.create(name="normalfile",
                            folder=folder)  # Shared between shops

        # Let's create 4 images for shop 1
        _mbv_upload(shop1, shop1_staff1, path=path)
        _mbv_upload(shop1, shop1_staff1, path=path)
        _mbv_upload(shop1, shop1_staff2, path=path)
        _mbv_upload(shop1, shop1_staff2, path=path)
        assert MediaFile.objects.count() == 4

        # Let's create 3 images for shop 2
        _mbv_upload(shop2, shop2_staff, path=path)
        _mbv_upload(shop2, shop2_staff, path=path)
        _mbv_upload(shop2, shop2_staff, path=path)
        assert MediaFile.objects.count() == 7

        # All files were created to same folder and while uploading
        # the each shop declared that they own the folder.
        assert Folder.objects.count() == 1
        assert MediaFolder.objects.count() == 1
        assert MediaFolder.objects.filter(shops=shop1).exists()
        assert shop1.media_folders.count() == 1
        assert shop1.media_files.count() == 4
        assert MediaFolder.objects.filter(shops=shop2).exists()
        assert shop2.media_folders.count() == 1
        assert shop2.media_files.count() == 3

        # Now let's make sure that each staff can view the folder
        # and all the files she should see.
        _check_that_staff_can_see_folder(rf, shop1, shop1_staff1, folder, 5)
        _check_that_staff_can_see_folder(rf, shop1, shop1_staff1, folder, 5)
        _check_that_staff_can_see_folder(rf, shop2, shop2_staff, folder, 4)
Ejemplo n.º 14
0
def initialize_test(rf, include_tax=False, customer=create_customer):
    shop = get_shop(prices_include_tax=include_tax)

    if callable(customer):
        customer = customer()

    request = apply_request_middleware(rf.get("/"))
    request.shop = shop
    request.customer = customer
    return request, shop, customer.groups.first()
Ejemplo n.º 15
0
def test_can_complete_productless_order(rf, admin_user):
    shop = get_shop(prices_include_tax=False)
    supplier = get_default_supplier()
    request = rf.get('/')
    request.shop = shop
    apply_request_middleware(request)
    customer = get_person_contact(admin_user)
    order =  create_simple_order(request, admin_user, customer)
    assert not order.has_products()
    assert order.can_set_complete()
    assert not order.is_fully_shipped()
Ejemplo n.º 16
0
def test_basic_order(rf, admin_user, mode):
    prices_include_tax = (mode == "taxful")
    shop = get_shop(prices_include_tax=prices_include_tax)

    request = rf.get('/')
    request.shop = shop
    apply_request_middleware(request)
    product = get_default_product()
    customer = get_person_contact(admin_user)
    for x in range(10):
        create_order(request, creator=admin_user, customer=customer, product=product)
    assert Order.objects.filter(customer=customer).count() == 10
Ejemplo n.º 17
0
def test_page_different_shops(rf):
    shop1 = get_shop(status=ShopStatus.ENABLED,
                     identifier="shop-1",
                     name="Shop 1",
                     domain="shop1")
    shop2 = get_shop(status=ShopStatus.ENABLED,
                     identifier="shop-2",
                     name="Shop 2",
                     domain="shop2")

    # dreate page only for shop2
    page = create_page(available_from=datetime.date(1988, 1, 1), shop=shop2)
    view_func = PageView.as_view()

    request = apply_request_middleware(rf.get("/", HTTP_HOST=shop1.domain))
    with pytest.raises(Http404):
        response = view_func(request, url=page.url)

    request = apply_request_middleware(rf.get("/", HTTP_HOST=shop2.domain))
    response = view_func(request, url=page.url)
    assert response.status_code == 200
    response.render()
    assert "<h1>Bacon ipsum" in response.rendered_content
Ejemplo n.º 18
0
def test_contact_company_edit_multishop(rf):
    with override_settings(WSHOP_MANAGE_CONTACTS_PER_SHOP=True, WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        staff_user = create_random_user(is_staff=True)

        shop1 = get_shop(identifier="shop-1", enabled=True)
        shop2 = get_shop(identifier="shop-2", enabled=True)

        shop1.staff_members.add(staff_user)
        shop2.staff_members.add(staff_user)

        # only available in shop2
        contact = create_random_person(locale="en_US", minimum_name_comp_len=5)
        contact.shops.add(shop2)

        # only available in shop1
        company = create_random_company()
        company.shops.add(shop1)

        view = ContactEditView.as_view()

        # permission denied for contact and shop1
        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop1)
        with pytest.raises(PermissionDenied):
            response = view(request, pk=contact.id)
        # permission granted for contact and shop2
        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop2)
        response = view(request, pk=contact.id)
        assert response.status_code == 200

        # permission denied for company and shop2
        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop2)
        with pytest.raises(PermissionDenied):
            response = view(request, pk=company.id)
        # permission granted for company and shop1
        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop1)
        response = view(request, pk=company.id)
        assert response.status_code == 200
Ejemplo n.º 19
0
def create_order_source(prices_include_tax, line_data, tax_rates):
    """
    Get order source with some testing data.

    :rtype: OrderSource
    """
    lines = [Line.from_text(x) for x in line_data]
    shop = get_shop(prices_include_tax, currency='USD')
    tax_classes = create_assigned_tax_classes(tax_rates)
    products = create_products(shop, lines, tax_classes)
    services = create_services(shop, lines, tax_classes)

    source = OrderSource(shop)
    fill_order_source(source, lines, products, services)
    return source
Ejemplo n.º 20
0
def test_company_contact_detail_multishop(rf):
    with override_settings(WSHOP_MANAGE_CONTACTS_PER_SHOP=True, WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        staff_user = create_random_user(is_staff=True)

        shop1 = get_shop(identifier="shop-1", enabled=True)
        shop2 = get_shop(identifier="shop-2", enabled=True)

        shop1.staff_members.add(staff_user)
        shop2.staff_members.add(staff_user)

        company = create_random_company()
        # only available in shop1
        company.shops.add(shop1)

        view = ContactDetailView.as_view()

        # company not found for this shop
        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop2)
        with pytest.raises(PermissionDenied):
            response = view(request, pk=company.id)

        request = apply_request_middleware(rf.get("/"), user=staff_user, shop=shop1)
        response = view(request, pk=company.id)
        assert response.status_code == 200
Ejemplo n.º 21
0
def _get_custom_order(regular_user, **kwargs):
    prices_include_tax = kwargs.pop("prices_include_tax", False)
    include_basket_campaign = kwargs.pop("include_basket_campaign", False)
    include_catalog_campaign = kwargs.pop("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()

    contact = get_person_contact(regular_user)
    source = BasketishOrderSource(shop)
    source.status = get_initial_order_status()
    source.customer = contact

    ctx = get_pricing_module().get_context_from_data(shop, contact)
    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
Ejemplo n.º 22
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)
    order.create_payment(Money("1", "EUR"))
    assert not order.has_refunds()
    assert order.can_create_refund()
    assert order.shipping_status == ShippingStatus.NOT_SHIPPED
    assert order.payment_status == PaymentStatus.PARTIALLY_PAID
    return order
Ejemplo n.º 23
0
def test_order_creator_company_multishop():
    with override_settings(WSHOP_MANAGE_CONTACTS_PER_SHOP=True,
                           WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        company = create_random_company()
        shop = get_shop(identifier="random-shop", enabled=True)

        source = seed_source(create_random_user(), shop)
        source.customer = company
        source.add_line(
            type=OrderLineType.PRODUCT,
            product=get_default_product(),
            supplier=get_default_supplier(),
            quantity=1,
            base_unit_price=source.create_price(10),
        )
        creator = OrderCreator()
        creator.create_order(source)
        company.refresh_from_db()
        assert shop in company.shops.all()
Ejemplo n.º 24
0
def test_run_multishop():
    shop1 = factories.get_default_shop()
    shop2 = factories.get_shop(identifier="shop2")
    event = get_initialized_test_event()
    step = Step(actions=[AddOrderLogEntry({
        "order": {"variable": "order"},
        "message": {"constant": "It Works."},
        "message_identifier": {"constant": "test_run"},
    })], next=StepNext.STOP)
    script = Script(event_identifier=event.identifier, name="Test Script", shop=shop2, enabled=True)
    script.set_steps([step])
    script.save()

    # runs for shop1 - no script exists
    event.run(shop1)
    assert not event.variable_values["order"].log_entries.filter(identifier="test_run").exists()

    # run for shop2 - ok
    event.run(shop2)
    assert event.variable_values["order"].log_entries.filter(identifier="test_run").exists()
    script.delete()
Ejemplo n.º 25
0
def initialize_test(rf, include_tax=False):
    activate("en")
    shop = get_shop(prices_include_tax=include_tax)
    shop.domain = "campaign"
    shop.save()

    # Valid baskets needs some payment methods to be available
    get_payment_method(shop)
    # Since some of the baskets are created for the default shop:
    get_payment_method(None)

    group = get_default_customer_group()
    customer = create_random_person()
    customer.groups.add(group)
    customer.save()

    request = rf.get("/")
    request.shop = shop
    request.META["HTTP_HOST"] = "campaign.wshop.com"
    apply_request_middleware(request)
    request.customer = customer
    return request, shop, group
Ejemplo n.º 26
0
def test_order_received_variables(rf, with_shop_contact):
    activate("en")
    shop = get_shop(True)
    shop.contact_address = get_address(**SHOP_ADDRESS_DATA)
    shop.contact_address.save()
    shop.save()
    get_default_product()
    get_default_supplier()

    STEP_DATA = [{
        "cond_op":
        "all",
        "enabled":
        True,
        "next":
        "continue",
        "actions": [{
            "template_data": {
                "en": {
                    "body": "{{ customer_email }}",
                    "content_type": "plain",
                    "subject": "{{ customer_phone }}"
                }
            },
            "identifier": "send_email",
            "language": {
                "constant": "en"
            },
            "recipient": {
                "constant": "*****@*****.**"
            }
        }]
    }]

    if with_shop_contact:
        STEP_DATA[0]['actions'].insert(
            0, {
                "template_data": {
                    "en": {
                        "body": "{{ shop_email }}",
                        "content_type": "plain",
                        "subject": "{{ shop_phone }}"
                    }
                },
                "identifier": "send_email",
                "language": {
                    "constant": "en"
                },
                "recipient": {
                    "constant": "*****@*****.**"
                }
            })

    sc = Script.objects.create(name="variables script",
                               event_identifier="order_received",
                               enabled=True,
                               shop=shop)
    sc.set_serialized_steps(STEP_DATA)
    sc.save()

    n_outbox_pre = len(mail.outbox)
    customer = create_random_person(locale='en')
    customer.default_shipping_address = get_address(**DEFAULT_ADDRESS_DATA)
    customer.default_shipping_address.save()
    customer.save()

    create_random_order(customer, shop=shop)
    assert (len(mail.outbox) == n_outbox_pre +
            (2 if with_shop_contact else 1)), "Sending email failed"

    latest_mail = mail.outbox[-1]
    assert latest_mail.subject == customer.default_shipping_address.phone
    assert latest_mail.body == customer.default_shipping_address.email

    if with_shop_contact:
        # shop email is sent first - we use insert(0, shop_step_data)
        penult_mail = mail.outbox[-2]
        assert penult_mail.subject == shop.contact_address.phone
        assert penult_mail.body == shop.contact_address.email
Ejemplo n.º 27
0
def test_get_best_selling_products(admin_user):
    shop1 = get_default_shop()
    shop2 = get_shop(True)
    person1 = create_random_person()
    person1.user = admin_user
    person1.save()

    supplier = create_simple_supplier("supplier1")
    client = _get_client(admin_user)

    # list best selling products
    response = client.get("/api/wshop/front/shop_products/best_selling/", {"shop": shop2.pk, "limit": 20})
    assert response.status_code == status.HTTP_200_OK
    products = json.loads(response.content.decode("utf-8"))
    assert len(products["results"]) == 0

    # THIS IS IMPORTANT!
    cache.clear()

    products = [create_product("Standard-%d" % x, supplier=supplier, shop=shop2) for x in range(10)]

    # create 1 product with 4 variations
    parent_product = create_product("ParentProduct1", supplier=supplier, shop=shop2)
    children = [create_product("SimpleVarChild-%d" % x, supplier=supplier, shop=shop2) for x in range(4)]
    for child in children:
        child.link_to_parent(parent_product)

    best_selling = defaultdict(int)

    # create orders with standard products
    for p_index in range(len(products)):
        order = create_empty_order(shop=shop2)
        order.save()
        qty = (len(products)-p_index)
        add_product_to_order(order, supplier, products[p_index], qty, Decimal(1.0))
        order.create_shipment_of_all_products()
        order.status = OrderStatus.objects.get_default_complete()
        order.save(update_fields=("status",))

        best_selling[products[p_index].id] = qty

    # create orders with variation products - the parent product is counted instead of its children
    for p_index in range(2):
        variation = random.choice(children)
        qty = 5
        order = create_empty_order(shop=shop2)
        order.save()
        add_product_to_order(order, supplier, variation, qty, Decimal(1.0))
        order.create_shipment_of_all_products()
        order.status = OrderStatus.objects.get_default_complete()
        order.save(update_fields=("status",))
        best_selling[parent_product.id] = best_selling[parent_product.id] + qty

    # get the top 100 best selling products
    response = client.get("/api/wshop/front/shop_products/best_selling/", {"shop": shop2.pk, "limit": 100})
    assert response.status_code == status.HTTP_200_OK
    products = json.loads(response.content.decode("utf-8"))
    assert len(products["results"]) == len(best_selling) # as we added less then 100, this must be true
    assert products["next"] is None

    # check the if all IDS are part of best selling
    for ix in range(len(products)):
        assert products["results"][ix]["product_id"] in best_selling.keys()

    # get the top 5 best selling products (we should get paginated results)
    response = client.get("/api/wshop/front/shop_products/best_selling/", {"shop": shop2.pk, "limit": 5})
    assert response.status_code == status.HTTP_200_OK
    products = json.loads(response.content.decode("utf-8"))
    assert len(products["results"]) == 5
    assert products["count"] == len(best_selling)
    assert products["next"] is not None
    sorted_best_selling_ids = [prod[0] for prod in sorted(best_selling.items(), key=lambda prod: -prod[1])][:5]

    # check the if all the 5 best sellers are part of best selling
    for ix in range(len(products)):
        assert products["results"][ix]["product_id"] in sorted_best_selling_ids
Ejemplo n.º 28
0
def test_edit_shared_folder(admin_user):
    with override_settings(WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        shop1 = factories.get_shop(identifier="shop1")
        shop2 = factories.get_shop(identifier="shop2")

        folder = Folder.objects.create(name="Test folder")  # Shared folder
        folder_count = Folder.objects.count()

        response = _mbv_command(shop1, admin_user, {
            "action": "rename_folder",
            "id": folder.pk,
            "name": "Space"
        })
        assert not response["success"]
        response = _mbv_command(shop1, admin_user, {
            "action": "delete_folder",
            "id": folder.pk
        })
        assert not response["success"]

        # Let's make sure rename works when only one shop owns the folder
        media_folder = MediaFolder.objects.create(folder=folder)
        media_folder.shops.add(shop1)
        response = _mbv_command(shop1, admin_user, {
            "action": "rename_folder",
            "id": folder.pk,
            "name": "Space"
        })
        assert response["success"]
        assert Folder.objects.get(pk=folder.pk).name == "Space"

        # Then add second shop for the folder and let's check and
        # renaming should be disabled again.
        media_folder.shops.add(shop2)
        response = _mbv_command(shop1, admin_user, {
            "action": "rename_folder",
            "id": folder.pk,
            "name": "Space"
        })
        assert not response["success"]
        response = _mbv_command(shop1, admin_user, {
            "action": "delete_folder",
            "id": folder.pk
        })
        assert not response["success"]
        response = _mbv_command(shop2, admin_user, {
            "action": "delete_folder",
            "id": folder.pk
        })
        assert not response["success"]

        # Finally remove the folder as shop2
        media_folder.shops.remove(shop1)
        response = _mbv_command(shop1, admin_user, {
            "action": "delete_folder",
            "id": folder.pk
        })
        assert response["error"] == "Folder matching query does not exist."
        response = _mbv_command(shop2, admin_user, {
            "action": "delete_folder",
            "id": folder.pk
        })
        assert response["success"]
        assert Folder.objects.count() == folder_count - 1
Ejemplo n.º 29
0
def test_manufacturer_admin_multishop_shop(rf, staff_user, admin_user,
                                           superuser):
    with override_settings(WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        shop1 = factories.get_shop(identifier="shop1")
        shop2 = factories.get_shop(identifier="shop2")
        shop1.staff_members.add(staff_user)
        shop2.staff_members.add(staff_user)

        assert Manufacturer.objects.count() == 0
        user = admin_user if superuser else staff_user

        request = apply_request_middleware(rf.post(
            "/", data=dict(name="Manuf shop2")),
                                           user=user,
                                           shop=shop2)
        set_shop(request, shop2)
        view_func = ManufacturerEditView.as_view()
        response = view_func(request)
        assert response.status_code == 302

        if superuser:
            assert Manufacturer.objects.first().shops.count() == 0
        else:
            assert Manufacturer.objects.first().shops.first() == shop2

        for view_class in (ManufacturerEditView, ManufacturerListView):
            view_instance = view_class()
            view_instance.request = request

            assert view_instance.get_queryset().count() == 1
            if superuser:
                assert view_instance.get_queryset().first().shops.count() == 0
            else:
                assert view_instance.get_queryset().first().shops.count() == 1
                assert view_instance.get_queryset().first().shops.first(
                ) == shop2

        request = apply_request_middleware(rf.post(
            "/", data=dict(name="Manuf shop1")),
                                           user=user,
                                           shop=shop1)
        set_shop(request, shop1)
        view_func = ManufacturerEditView.as_view()
        response = view_func(request)
        assert response.status_code == 302

        if superuser:
            assert Manufacturer.objects.last().shops.count() == 0
        else:
            assert Manufacturer.objects.last().shops.first() == shop1

        for view_class in (ManufacturerEditView, ManufacturerListView):
            view_instance = view_class()
            view_instance.request = request

            assert view_instance.get_queryset().count() == (2 if superuser else
                                                            1)

            if superuser:
                assert view_instance.get_queryset().first().shops.count() == 0
                assert view_instance.get_queryset().last().shops.count() == 0
            else:
                assert view_instance.get_queryset().first().shops.count() == 1
                assert view_instance.get_queryset().first().shops.first(
                ) == shop1
Ejemplo n.º 30
0
def test_edit_shared_file(admin_user):
    with override_settings(WSHOP_ENABLE_MULTIPLE_SHOPS=True):
        shop1 = factories.get_shop(identifier="shop1")
        shop2 = factories.get_shop(identifier="shop2")

        folder1 = Folder.objects.create(name="folder1")
        folder2 = Folder.objects.create(name="folder2")
        file = File.objects.create(original_filename="test.jpg",
                                   folder=folder1)  # Shared file
        file_count = File.objects.count()
        assert force_text(file) == "test.jpg"

        response = _mbv_command(shop1, admin_user, {
            "action": "rename_file",
            "id": file.pk,
            "name": "test.tiff"
        })
        assert not response["success"]
        response = _mbv_command(shop1, admin_user, {
            "action": "move_file",
            "file_id": file.pk,
            "folder_id": folder2.pk
        })
        assert not response["success"]
        assert File.objects.get(pk=file.pk).folder == folder1
        response = _mbv_command(shop1, admin_user, {
            "action": "delete_file",
            "id": file.pk
        })
        assert not response["success"]

        # Let's make sure rename works when only one shop owns the file
        media_file = MediaFile.objects.create(file=file)
        media_file.shops.add(shop1)
        response = _mbv_command(shop1, admin_user, {
            "action": "rename_file",
            "id": file.pk,
            "name": "test.tiff"
        })
        assert response["success"]
        file = File.objects.get(pk=file.pk)
        assert force_text(file) == "test.tiff"

        # Let's move the file to different folder
        response = _mbv_command(shop1, admin_user, {
            "action": "move_file",
            "file_id": file.pk,
            "folder_id": folder2.pk
        })
        assert response["success"]
        assert File.objects.get(pk=file.pk).folder == folder2

        # Then add second shop for the file and let's check and
        # renaming should be disabled again.
        media_file.shops.add(shop2)
        response = _mbv_command(shop1, admin_user, {
            "action": "rename_file",
            "id": file.pk,
            "name": "test.tiff"
        })
        assert not response["success"]
        response = _mbv_command(shop1, admin_user, {
            "action": "delete_file",
            "id": file.pk
        })
        assert not response["success"]
        response = _mbv_command(shop2, admin_user, {
            "action": "rename_file",
            "id": file.pk,
            "name": "test.tiff"
        })
        assert not response["success"]
        response = _mbv_command(shop2, admin_user, {
            "action": "delete_file",
            "id": file.pk
        })
        assert not response["success"]

        # Finally remove the file as shop2
        media_file.shops.remove(shop1)
        response = _mbv_command(shop1, admin_user, {
            "action": "delete_file",
            "id": file.pk
        })
        assert response["error"] == "File matching query does not exist."
        response = _mbv_command(shop2, admin_user, {
            "action": "delete_file",
            "id": file.pk
        })
        assert response["success"]
        assert File.objects.count() == file_count - 1