def toggle_all_seeing_for_user(user): if not getattr(user, "is_superuser", False): return all_seeing_key = ALL_SEEING_FORMAT % {"user_id": user.pk} is_all_seeing = configuration.get(None, all_seeing_key, False) configuration.set(None, all_seeing_key, not is_all_seeing)
def test_category_deletion(admin_user): admin = get_person_contact(admin_user) category = get_default_category() category.children.create(identifier="foo") shop_product = get_default_shop_product() shop_product.categories.add(category) shop_product.primary_category = category shop_product.save() configuration.set(None, get_all_seeing_key(admin), True) assert category.status == CategoryStatus.VISIBLE assert category.children.count() == 1 with pytest.raises(NotImplementedError): category.delete() category.soft_delete() shop_product.refresh_from_db() shop_product.product.refresh_from_db() assert shop_product.categories.count() == 0 assert shop_product.primary_category is None assert category.status == CategoryStatus.DELETED assert category.children.count() == 0 # the child category still exists assert Category.objects.all_visible(customer=admin).count() == 1 assert Category.objects.all_except_deleted().count() == 1 configuration.set(None, get_all_seeing_key(admin), False)
def test_register_bad_data(): get_default_shop() configuration.set(None, "api_permission_FrontUserViewSet", PermissionLevel.PUBLIC_WRITE) client = _get_client() # no username or email register_data = { "password": "******" } response = client.post("/api/E-Commerce/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "username and/or email is required" in response.content.decode("utf-8") # invalid email register_data = { "email": "invalidemail", "password": "******" } response = client.post("/api/E-Commerce/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "Enter a valid email address" in response.content.decode("utf-8") # no password register_data = { "email": "*****@*****.**", } response = client.post("/api/E-Commerce/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "password" in json.loads(response.content.decode("utf-8"))
def test_address_phase_anonymous_user(rf, allow_company_registration): shop = get_default_shop() configuration.set(shop, "allow_company_registration", allow_company_registration) request = apply_request_middleware(rf.get("/"), shop=shop) view_func = AddressesOnlyCheckoutView.as_view() resp = view_func(request, phase='addresses') assert bool('company' in resp.context_data['form'].form_defs) == allow_company_registration
def test_register_api(): get_default_shop() configuration.set(None, "api_permission_FrontUserViewSet", PermissionLevel.PUBLIC_WRITE) client = _get_client() register_data = { "username": "******", "password": "******" } response = client.post("/api/E-Commerce/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_201_CREATED response_json = json.loads(response.content.decode("utf-8")) assert "token" in response_json assert get_user_model().objects.count() == 1 # Try to register with same username register_data = { "username": "******", "password": "******" } response = client.post("/api/E-Commerce/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "User already exists" in response.content.decode("utf-8")
def test_global_configurations(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_global_configurations', } }): cache.init_cache() shop = get_default_shop() configuration.set(None, "key1", {"data": "test1"}) configuration.set(shop, "key2", {"data": "test2"}) # key1 from shop should come from global configuration assert configuration.get(shop, "key1").get("data") == "test1" # key2 shouldn't be in global configurations assert configuration.get(None, "key2") is None # Update global configuration configuration.set(None, "key1", {"data": "test_bump"}) assert configuration.get(shop, "key1").get("data") == "test_bump" # Override shop data for global key1 configuration.set(shop, "key1", "test_data") assert configuration.get(shop, "key1") == "test_data" # Update shop configuration for global key1 configuration.set(shop, "key1", "test_data1") assert configuration.get(shop, "key1") == "test_data1"
def set_configuration(): config = { "api_permission_ShopViewSet": 3, "api_permission_FrontShopProductViewSet": 3, "api_permission_PersonContactViewSet": 4, "api_permission_FrontUserViewSet": 2, "api_permission_FrontOrderViewSet": 4, "api_permission_AttributeViewSet": 5, "api_permission_TaxClassViewSet": 5, "api_permission_FrontProductViewSet": 3, "api_permission_ProductVariationVariableValueViewSet": 5, "api_permission_SalesUnitViewSet": 5, "api_permission_UserViewSet": 5, "api_permission_ShopReviewViewSet": 4, "api_permission_BasketViewSet": 2, "api_permission_CategoryViewSet": 1, "api_permission_ShipmentViewSet": 5, "api_permission_CgpPriceViewSet": 5, "api_permission_ShopProductViewSet": 3, "api_permission_ContactViewSet": 4, "api_permission_OrderViewSet": 5, "api_permission_ProductViewSet": 5, "api_permission_ProductTypeViewSet": 5, "api_permission_ProductVariationVariableViewSet": 5, "api_permission_SupplierViewSet": 5, "api_permission_ManufacturerViewSet": 5, "api_permission_ProductMediaViewSet": 5, "api_permission_ProductAttributeViewSet": 5, "api_permission_MutableAddressViewSet": 5, "api_permission_ProductPackageViewSet": 5, } for field, value in six.iteritems(config): configuration.set(None, field, value)
def post(self, request): """ Save admin menu for current user to the database """ menus = json.loads(request.POST.get('menus')) configuration.set(None, 'admin_menu_user_{}'.format(request.user.pk), menus) messages.add_message(request, messages.SUCCESS, _('Menu saved')) return HttpResponseRedirect(reverse_lazy('E-Commerce_admin:menu.arrange'))
def test_omniscience(admin_user, regular_user): assert not get_person_contact(admin_user).is_all_seeing configuration.set(None, get_all_seeing_key(admin_user), True) 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 configuration.set(None, get_all_seeing_key(admin_user), False)
def test_registration_company_multiple_shops(django_user_model, client): if "E-Commerce.front.apps.registration" not in settings.INSTALLED_APPS: pytest.skip("E-Commerce.front.apps.registration required in installed apps") configuration.set(None, "allow_company_registration", True) configuration.set(None, "company_registration_requires_approval", False) shop1 = Shop.objects.create(identifier="shop1", status=ShopStatus.ENABLED, domain="shop1.E-Commerce.com") shop2 = Shop.objects.create(identifier="shop2", status=ShopStatus.ENABLED, domain="shop2.E-Commerce.com") username = "******" % uuid.uuid4().time email = "*****@*****.**" % username with override_settings( E-Commerce_REGISTRATION_REQUIRES_ACTIVATION=False, E-Commerce_MANAGE_CONTACTS_PER_SHOP=True, E-Commerce_ENABLE_MULTIPLE_SHOPS=True ): url = reverse("E-Commerce:registration_register_company") client.post(url, data={ 'company-name': "Test company", 'company-name_ext': "test", 'company-tax_number': "12345", 'company-email': "*****@*****.**", 'company-phone': "123123", 'company-www': "", 'billing-street': "testa tesat", 'billing-street2': "", 'billing-postal_code': "12345", 'billing-city': "test test", 'billing-region': "", 'billing-region_code': "", 'billing-country': "FI", 'contact_person-first_name': "Test", 'contact_person-last_name': "Tester", 'contact_person-email': email, 'contact_person-phone': "123", 'user_account-username': username, 'user_account-password1': "password", 'user_account-password2': "password", }, HTTP_HOST="shop1.E-Commerce.com") user = django_user_model.objects.get(username=username) contact = PersonContact.objects.get(user=user) company = CompanyContact.objects.get(members__in=[contact]) assert contact.in_shop(shop1) assert company.in_shop(shop1) assert contact.in_shop(shop1, only_registration=True) assert company.in_shop(shop1, only_registration=True) assert contact.registered_in(shop1) assert company.registered_in(shop1) assert not contact.in_shop(shop2) assert not company.in_shop(shop2) assert not contact.in_shop(shop2, only_registration=True) assert not company.in_shop(shop2, only_registration=True) assert not contact.registered_in(shop2) assert not company.registered_in(shop2)
def test_notify_on_company_created(regular_user, allow_company_registration): if "E-Commerce.front.apps.customer_information" not in settings.INSTALLED_APPS: pytest.skip("E-Commerce.front.apps.customer_information required in installed apps") if "E-Commerce.notify" not in settings.INSTALLED_APPS: pytest.skip("E-Commerce.notify required in installed apps") configuration.set(None, "allow_company_registration", allow_company_registration) step = Step( cond_op=StepConditionOperator.NONE, actions=[ AddNotification({ "message": {"constant": "It Works. {{ customer_email }}"}, "message_identifier": {"constant": "company_created"}, }) ], next=StepNext.STOP ) script = Script( event_identifier=CompanyAccountCreated.identifier, name="Test Script", enabled=True, shop=get_default_shop()) script.set_steps([step]) script.save() assert not Notification.objects.filter(identifier="company_created").exists() assert get_person_contact(regular_user) assert not get_company_contact(regular_user) client = SmartClient() client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) company_edit_url = reverse("E-Commerce:company_edit") if allow_company_registration: client.soup(company_edit_url) data = _default_company_data() data.update(_default_address_data("billing")) data.update(_default_address_data("shipping")) response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert get_company_contact(regular_user) assert Notification.objects.filter(identifier="company_created").count() == 1 notification = Notification.objects.filter(identifier="company_created").first() assert notification assert data["contact-email"] in notification.message # New save should not add new notifications response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert Notification.objects.filter(identifier="company_created").count() == 1 script.delete() else: response = client.get(company_edit_url) assert reverse("E-Commerce:customer_edit") in response.url assert Notification.objects.filter(identifier="company_created").count() == 0
def set_shop_available_languages(shop, languages): available_codes = [code for code, name in settings.LANGUAGES] # validate languages for language in languages: if language not in available_codes: msg = _("{language_code} is an invalid language code").format(language_code=language) raise ValueError(msg) configuration.set(shop, FRONT_AVAILABLE_LANGUAGES_CONFIG_KEY, ",".join(languages))
def form_valid(self, form): if djangoenv.has_installed("E-Commerce.simple_cms") or djangoenv.has_installed("E-Commerce.xtheme"): content_form = form["content"] content_form.save() if djangoenv.has_installed("E-Commerce.notify"): behavior_form = form["behaviors"] behavior_form.save() configuration.set(None, "wizard_content_completed", True)
def post(self, request, *args, **kwargs): abort = request.POST.get("abort", False) if self.request.POST.get("pane_id") == self.get_final_pane_identifier(): configuration.set(Shop.objects.first(), "setup_wizard_complete", True) if abort: return JsonResponse({"success": "true"}, status=200) form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
def test_view_saved_columns(rf): shop = get_default_shop() visible_fields = sorted(["shopproduct_id", "product_name", "select"]) configuration.set(None, "view_configuration_shopproduct_saved", True) for field in visible_fields: configuration.set(None, "view_configuration_shopproduct_%s" % field, {"active": True, "ordering": 999}) listview = ProductListView() column_names = [c.id for c in sorted(listview.columns, key=lambda x: x.id)] assert len(listview.columns) == len(visible_fields) assert column_names == visible_fields
def test_regular_user_is_blind(rf, regular_user): shop = get_default_shop() contact = get_person_contact(regular_user) do_request_and_asserts(rf, contact, maintenance=False, expect_all_seeing=False, expect_toolbar=False) # user needs to be superuser to even get a glimpse assert not contact.is_all_seeing configuration.set(None, get_all_seeing_key(contact), True) assert not contact.is_all_seeing # only superusers can be allseeing # Contact might be all-seeing in database but toolbar requires superuser do_request_and_asserts(rf, contact, maintenance=False, expect_all_seeing=False, expect_toolbar=False)
def set_configuration(shop=None, category=None, data=None): if category and category.pk: configuration.set(None, _get_category_configuration_key(category), data) elif shop: configuration.set(shop, FACETED_DEFAULT_CONF_KEY, data) cache.bump_version(get_theme_cache_key(shop)) # clear active keys context_cache.bump_cache_for_item(category) if not category: from E-Commerce.core.models import Category for cat_pk in Category.objects.all().values_list("pk", flat=True): context_cache.bump_cache_for_pk(Category, cat_pk)
def test_admin(rf, admin_user): shop = get_default_shop() configuration.set(shop, "setup_wizard_complete", True) # just visit to make sure everything is ok request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 200 categories = [CategoryFactory().pk, CategoryFactory().pk, CategoryFactory().pk] manager.save_categories(shop, categories) request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 200
def test_simple_set_and_get_cascading(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_simple_set_and_get_cascading', } }): cache.init_cache() shop = get_default_shop() configuration.set(None, "answer", 42) assert configuration.get(None, "answer") == 42 assert configuration.get(shop, "answer", 42) assert configuration.get(None, "non-existing") is None assert configuration.get(shop, "non-existing") is None configuration.set(shop, "non-existing", "hello") assert configuration.get(None, "non-existing") is None assert configuration.get(shop, "non-existing") == "hello" assert configuration.get(None, "foo") is None assert configuration.get(shop, "foo") is None configuration.set(None, "foo", "bar") configuration.set(shop, "foo", "baz") assert configuration.get(None, "foo") == "bar" assert configuration.get(shop, "foo") == "baz"
def form_valid(self, form): if self.name in form.forms: used_form = form[self.name] if not used_form.has_changed(): return None # no need to save for key in used_form.fields.keys(): try: ConfigurationItem.objects.get(shop=self.object, key=key).delete() except ConfigurationItem.DoesNotExist: continue for key, value in six.iteritems(used_form.cleaned_data): configuration.set(shop=self.object, key=key, value=value)
def save(self, form): if not form.has_changed(): return False # no need to save for key in form.fields.keys(): try: ConfigurationItem.objects.get(shop=None, key=key).delete() except ConfigurationItem.DoesNotExist: continue for key, value in six.iteritems(form.cleaned_data): if isinstance(value, Enum): value = value.value configuration.set(None, key, value) return True
def _save_template(self, data, identifier=None): shop = get_shop(self.request) saved_templates = self.get_variation_templates() if identifier: for template in saved_templates: if(template["identifier"] == identifier): template["data"] = data # Edit tempalte else: template_name = self.cleaned_data.get("template_name", _("Unnamed %s") % random.randint(1, 9999)) payload = { "name": template_name, "identifier": template_name.lower().replace(" ", "_") + ("%s" % random.randint(1, 9999)), "data": data } saved_templates.append(payload) configuration.set(shop, self.configuration_key, saved_templates)
def test_configuration_set_and_get(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_set_and_get', } }): cache.init_cache() shop = get_default_shop() test_conf_data = {"data": "test"} configuration.set(shop, "key", test_conf_data) # Get the configuration via configuration API assert configuration.get(shop, "key") == test_conf_data # Check that configuration is saved to database assert ConfigurationItem.objects.get(shop=shop, key="key").value == test_conf_data
def form_valid(self, form): current_language = translation.get_language() default_language = getattr(settings, "PARLER_DEFAULT_LANGUAGE_CODE", None) # change the language to the PARLER_DEFAULT_LANGUAGE # so sample data will have data on fallback languages if default_language: translation.activate(default_language) shop = self.object form_data = form["sample"].cleaned_data business_segment = form_data["business_segment"] current_categories = sample_manager.get_installed_categories(shop) current_products = sample_manager.get_installed_products(shop) current_carousel = sample_manager.get_installed_carousel(shop) # only saves the business segment if there is no data installed # otherwise user can't change the segment if sample_manager.has_installed_samples(shop): business_segment = sample_manager.get_installed_business_segment(shop) else: sample_manager.save_business_segment(shop, business_segment) # user wants to install sample categories if form_data.get("categories", False) and not current_categories: categories = self._create_sample_categories(shop, business_segment) if categories: sample_manager.save_categories(shop, categories) # user wants to install sample products if form_data.get("products", False) and not current_products: products = self._create_sample_products(shop, business_segment) if products: sample_manager.save_products(shop, products) # user wants a carousel if form_data.get("carousel") and not current_carousel: carousel = self._create_sample_carousel(shop, business_segment) if carousel: sample_manager.save_carousel(shop, carousel.pk) # back to current language translation.activate(current_language) # user will no longer see this pane configuration.set(None, "sample_data_wizard_completed", True)
def test_behavior_form(): shop = get_default_shop() assert Script.objects.count() == 0 assert configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) is None form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": True}) assert form._get_saved_script() is None form.save() # check if the form creates a order notification correctely script = Script.objects.first() assert script.pk == configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) assert form._get_saved_script().pk == script.pk assert len(script.get_steps()) == 1 step = script.get_steps()[0] step_data = step.serialize() assert step_data["next"] == StepNext.STOP.value action = step._actions[0] assert isinstance(action, SendEmail) action_data = action.serialize() assert action_data["recipient"]["variable"] == "customer_email" assert action_data["language"]["variable"] == "language" lang = translation.get_language() assert action_data["fallback_language"]["constant"] == lang assert action_data["template_data"][lang]["content_type"] == "html" assert action_data["template_data"][lang]["subject"] == force_text(data.ORDER_CONFIRMATION["subject"]) context = {"shop": shop} content = loader.render_to_string(data.ORDER_CONFIRMATION["body_template"], context).strip() assert action_data["template_data"][lang]["body"] == content # the widget must be disabled form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": True}) assert form.fields["order_confirm_notification"].widget.attrs["disabled"] is True # clear scripts Script.objects.all().delete() configuration.set(shop, BEHAVIOR_ORDER_CONFIRM_KEY, None) # save the form but do not create the order confirmation notification form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": False}) form.save() # nothing created assert Script.objects.count() == 0 assert configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) is None
def test_all_seeing_and_maintenance(rf, admin_user): shop = get_default_shop() admin_contact = get_person_contact(admin_user) do_request_and_asserts(rf, admin_contact, maintenance=False, expect_toolbar=True) assert not admin_contact.is_all_seeing configuration.set(None, get_all_seeing_key(admin_user), True) assert admin_contact.is_all_seeing assert admin_contact.user.is_superuser do_request_and_asserts(rf, admin_contact, maintenance=False, expect_all_seeing=True, expect_toolbar=True) configuration.set(None, get_all_seeing_key(admin_contact), False) # Test maintenance mode badge shop.maintenance_mode = True shop.save() do_request_and_asserts(rf, admin_contact, maintenance=True, expect_toolbar=True)
def form_valid(self, form): if self.name not in form.forms: return form = form.forms[self.name] if not form.has_changed(): return for key in form.fields.keys(): try: ConfigurationItem.objects.get(shop=self.request.shop, key=key).delete() except ConfigurationItem.DoesNotExist: continue for key, value in six.iteritems(form.cleaned_data): if isinstance(value, Enum): value = value.value configuration.set(self.request.shop, key, value)
def test_configuration_cache(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() shop = get_default_shop() configuration.set(None, "key1", "test1") configuration.set(shop, "key2", "test2") # Shop configurations cache should be bumped assert cache.get(configuration._get_cache_key(shop)) is None configuration.get(shop, "key1") # Now shop configurations and key2 should found from cache assert cache.get(configuration._get_cache_key(shop)).get("key2") == "test2"
def run(self): for schema in self.schemata: self.objects[schema["model"]] = self.process_schema(schema) # Ensure default statuses are available print_("Creating order statuses...", end=" ") create_default_order_statuses() print_("done.") if not settings.DEBUG and is_telemetry_enabled(): try: data = json.dumps({ "key": get_installation_key() }) resp = requests.get(url=settings.E-Commerce_SUPPORT_ID_URL, data=data, timeout=5) if resp.json().get("support_id"): configuration.set(None, "E-Commerce_support_id", resp.json().get("support_id")) except Exception: print_("Failed to get support id") print_("Initialization done.")
def test_product_available(admin_user, regular_user, available_until, visible): shop = get_default_shop() product = create_product("test-sku", shop=shop) shop_product = product.get_shop_instance(shop) regular_contact = get_person_contact(regular_user) admin_contact = get_person_contact(admin_user) shop_product.available_until = available_until shop_product.save() assert (product in Product.objects.listed(shop=shop)) == visible assert (product in Product.objects.searchable(shop=shop)) == visible assert (product in Product.objects.listed(shop=shop, customer=admin_contact)) == visible assert (product in Product.objects.searchable(shop=shop, customer=admin_contact)) == visible assert (product in Product.objects.searchable(shop=shop, customer=regular_contact)) == visible 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) configuration.set(None, get_all_seeing_key(admin_contact), False)