def login(request, **kwargs): if not is_anonymous(request.user) and request.method == "POST": # We're logging in, so log out first do_logout(request) kwargs.setdefault("extra_context", {})["error"] = request.GET.get("error") if django.VERSION < (2, 0): return auth_views.login( request=request, authentication_form=cached_load("SHUUP_ADMIN_AUTH_FORM_SPEC"), **kwargs ) else: return auth_views.LoginView.as_view( form_class=cached_load("SHUUP_ADMIN_AUTH_FORM_SPEC"), **kwargs )(request)
def get_object(self): uuid = get_key(self.kwargs.get(self.lookup_field, "")) shop = self.request.shop loaded_basket = Basket.objects.filter(key=uuid).first() # ensure correct owner if not self.request.user.is_superuser: if not loaded_basket.shop == shop: raise exceptions.PermissionDenied("No permission") customer_id = (loaded_basket.customer.pk if loaded_basket.customer else None) controlled_contact_ids = self._get_controlled_contacts_by_user(self.request.user) is_staff = self.is_staff_user(shop, self.request.user) if customer_id and customer_id not in controlled_contact_ids and not is_staff: raise exceptions.PermissionDenied("No permission") # actually load basket basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(self.request._request, basket_name=uuid) try: basket._data = basket.storage.load(basket) except BasketCompatibilityError as error: raise exceptions.ValidationError(str(error)) # Hack: the storage should do this already # set the correct basket customer if loaded_basket and loaded_basket.customer: basket.customer = loaded_basket.customer return basket
def new(self, request, *args, **kwargs): """ Create a brand new basket object """ serializer = NewBasketSerializer(data=request.data) serializer.is_valid(True) data = serializer.validated_data self.process_request(with_basket=False, shop=data.get("shop")) basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(request._request) if "customer" in data: customer = data["customer"] else: customer = get_company_contact(request.user) or get_person_contact( request.user) orderer = data.get("orderer", get_person_contact(request.user)) # set the request basket to perform the basket command self.request.basket = basket self._handle_set_customer(request=self.request._request, basket=basket, customer=customer, orderer=orderer) stored_basket = basket.save() response_data = { "uuid": "%s-%s" % (request.shop.pk, stored_basket.key) } response_data.update(self.get_serializer(basket).data) return Response(data=response_data, status=status.HTTP_201_CREATED)
def get_form(self, form_class=None): fg = FormGroup(**self.get_form_kwargs()) default_address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") for kind in self.address_kinds: fg.add_form_def(kind, form_class=self.address_form_classes.get( kind, default_address_form_class)) fg.add_form_def( "saved_{}".format(kind), form_class=SavedAddressForm, required=False, kwargs={ "kind": kind, "owner": self.basket.customer }, ) if self.company_form_class and allow_company_registration( self.request.shop) and not self.request.customer: fg.add_form_def("company", self.company_form_class, required=False, kwargs={"request": self.request}) return fg
def _configure_basket(request): """ Search for some needed keys in the checkout phases storages """ # (src key, destination key) pair search_keys = [ ('payment_method_id', 'payment_method_id'), ('shipping_method_id', 'shipping_method_id'), ('shipping', 'shipping_address'), ('shipping_extra', 'shipping_address_extra'), ('payment', 'payment_address'), ('payment_extra', 'payment_address_extra'), ] for phase in cached_load("SHUUP_CHECKOUT_VIEW_SPEC").phase_specs: phase_class = load(phase) storage = CheckoutPhaseStorage(request, phase_class.identifier) for key, dst_key in search_keys: value = storage.get(key) # key found, set it to request.basket on dst_key if value: setattr(request.basket, dst_key, value)
def new(self, request, *args, **kwargs): """ Create a brand new basket object """ self.process_request(with_basket=False) basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(request._request) customer_id = request.POST.get("customer_id") if not customer_id: customer_id = request.data.get("customer_id") if customer_id: is_staff = self.is_staff_user(self.request.shop, self.request.user) is_superuser = self.request.user.is_superuser if int(customer_id) in self._get_controlled_contacts_by_user(self.request.user) or is_superuser or is_staff: basket.customer = Contact.objects.get(pk=int(customer_id)) else: raise exceptions.PermissionDenied("No permission") stored_basket = basket.save() response_data = { "uuid": "%s-%s" % (request.shop.pk, stored_basket.key) } response_data.update(BasketSerializer(basket, context=self.get_serializer_context()).data) return Response(data=response_data, status=status.HTTP_201_CREATED)
def get_object(self): basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") shop = self.request.shop uuid = get_key(self.kwargs.get(self.lookup_field, "")) storage = get_storage() if not storage.basket_exists(uuid, shop): raise exceptions.NotFound() basket = basket_class(self.request._request, basket_name=uuid) try: basket._data = basket.storage.load(basket) except BasketCompatibilityError as error: raise exceptions.ValidationError(str(error)) # ensure correct creator if not self.request.user.is_superuser: if not basket.shop == shop: raise exceptions.PermissionDenied("No permission") customer_id = (basket.customer.pk if basket.customer else None) controlled_contact_ids = self._get_controlled_contacts_by_user(self.request.user) is_staff = self.is_staff_user(shop, self.request.user) if customer_id and customer_id not in controlled_contact_ids and not is_staff: raise exceptions.PermissionDenied("No permission") return basket
def get_form(self, form_class=None): user = self.request.user company = get_company_contact(user) person = get_person_contact(user) form_group = FormGroup(**self.get_form_kwargs()) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") form_group.add_form_def("billing", address_form_class, kwargs={ "instance": _get_default_address_for_contact( company, "default_billing_address", person) }) form_group.add_form_def("shipping", address_form_class, kwargs={ "instance": _get_default_address_for_contact( company, "default_shipping_address", person) }) form_group.add_form_def("contact", CompanyContactForm, kwargs={"instance": company}) return form_group
def __init__(self, *args, **kwargs): super(CompanyRegistrationForm, self).__init__(*args, **kwargs) address_form_cls = cached_load('SHUUP_ADDRESS_MODEL_FORM') self.add_form_def('company', CompanyForm) self.add_form_def('billing', address_form_cls) self.add_form_def('contact_person', ContactPersonForm) self.add_form_def('user_account', UserCreationForm)
def get_context_data(self, **kwargs): context = super(CartDetailView, self).get_context_data(**kwargs) basket_class = None if self.object.class_spec: basket_class = load(self.object.class_spec) if not basket_class: basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(self.request, basket_name=self.object.key, shop=self.object.shop) context["basket"] = basket sources = [ basket.shipping_address, basket.billing_address, basket.customer, basket.orderer, ] fields = ("email", "phone", "tax_number") for field in fields: for source in sources: val = getattr(source, field, None) if val: context[field] = val break return context
def new(self, request, *args, **kwargs): """ Create a brand new basket object """ serializer = NewBasketSerializer(data=request.data) serializer.is_valid(True) data = serializer.validated_data self.process_request(with_basket=False, shop=data.get("shop")) basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(request._request) if "customer" in data: customer = data["customer"] else: customer = get_company_contact(request.user) or get_person_contact(request.user) orderer = data.get("orderer", get_person_contact(request.user)) # set the request basket to perform the basket command self.request.basket = basket self._handle_set_customer( request=self.request._request, basket=basket, customer=customer, orderer=orderer ) stored_basket = basket.save() response_data = { "uuid": "%s-%s" % (request.shop.pk, stored_basket.key) } response_data.update(self.get_serializer(basket).data) return Response(data=response_data, status=status.HTTP_201_CREATED)
def get_object(self): uuid = get_key(self.kwargs.get(self.lookup_field, "")) user = self.request.user shop = self.request.shop # ensure correct owner if not self.request.user.is_superuser: loaded_basket = Basket.objects.filter(key=uuid).first() if not loaded_basket.shop == shop: raise exceptions.PermissionDenied("No permission") customer_id = (loaded_basket.customer.pk if loaded_basket.customer else None) controlled_contact_ids = self._get_controlled_contacts_by_user(self.request.user) is_staff = ( shop and self.request.user.is_staff and user.pk in shop.staff_members.all().values_list("pk", flat=True) ) if customer_id and customer_id not in controlled_contact_ids and not is_staff: raise exceptions.PermissionDenied("No permission") # actually load basket basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(self.request._request, basket_name=uuid) try: basket._data = basket.storage.load(basket) except BasketCompatibilityError as error: raise exceptions.ValidationError(str(error)) return basket
def get_price_info(self, context, product, quantity=1): product_id = product if isinstance(product, six.integer_types) else product.pk shop = context.shop # By default let's use supplier passed to context. supplier = context.supplier if not supplier: # Since supplier is optional I am pretty sure # there is cases that supplier is not passed to # pricing context. This is not a problem. The # pricing module which decides to use supplier # for product prices mjust need to have some sane # fallback. supplier_strategy = cached_load("SHUUP_SHOP_PRODUCT_SUPPLIERS_STRATEGY") kwargs = { "product_id": product_id, "shop": context.shop, "customer": context.customer, "quantity": quantity, "basket": context.basket, } # Since this is custom pricing module it # requires also custom supplier strategy. # Some example is provided in # `shuup.testing.supplier_pricing.supplier_strategy:CheapestSupplierPriceSupplierStrategy` supplier = supplier_strategy().get_supplier(**kwargs) # Like now in customer group pricing let's take default price from shop product shop_product = ShopProduct.objects.filter(product_id=product_id, shop=shop).only("default_price_value").first() if not shop_product: return PriceInfo(price=shop.create_price(0), base_price=shop.create_price(0), quantity=quantity) default_price = shop_product.default_price_value # Then the actual supplier price in case we have # been able to figure out some supplier. I guess # it is problem for supplier strategy if it allows # supplier to be None in some weird scenarios. # Not sure though what would happen in shop product # orderability checks and so on. price = None if supplier: result = ( SupplierPrice.objects.filter(shop=shop, product_id=product_id, supplier=supplier) .order_by("amount_value")[:1] .values_list("amount_value", flat=True) ) if result: price = result[0] if not price: price = default_price return PriceInfo( price=shop.create_price(price * quantity), base_price=shop.create_price(price * quantity), quantity=quantity, )
def get_task_runner(): """ Returns the task runner configured in settings. :rtype: TaskRunner """ return cached_load("SHUUP_TASK_RUNNER")()
def get_basket(request, basket_name="basket", basket_class=None): """ Get the basket cached in the request or create and cache a new one. The basket_class is used when creating a new basket, i.e. when the request doesn't already have a basket cached with the given name. If no basket_class is given, will load a class using the `~shuup.front.settings.SHUUP_BASKET_CLASS_SPEC` setting. :type request: django.http.request.HttpRequest :type basket_name: str :type basket_class: type|None :rtype: shuup.front.basket.objects.BaseBasket """ basket = _get_basket_from_request(request, basket_name) if basket: return basket if basket_class is None: basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(request, basket_name=basket_name) _save_basket_to_request(request, basket_name, basket) return basket
def new(self, request, *args, **kwargs): """ Create a brand new basket object """ self.process_request(with_basket=False) basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(request._request) customer_id = request.POST.get("customer_id") if not customer_id: customer_id = request.data.get("customer_id") if customer_id: is_staff = self.is_staff_user(self.request.shop, self.request.user) is_superuser = self.request.user.is_superuser if int(customer_id) in self._get_controlled_contacts_by_user( self.request.user) or is_superuser or is_staff: basket.customer = Contact.objects.get(pk=int(customer_id)) else: raise exceptions.PermissionDenied("No permission") stored_basket = basket.save() return Response( data={"uuid": "%s-%s" % (request.shop.pk, stored_basket.key)}, status=status.HTTP_201_CREATED)
def get_object(self): basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") shop = self.request.shop uuid = get_key(self.kwargs.get(self.lookup_field, "")) storage = get_storage() if not storage.basket_exists(uuid, shop): raise exceptions.NotFound() basket = basket_class(self.request._request, basket_name=uuid) try: basket._data = basket.storage.load(basket) except BasketCompatibilityError as error: raise exceptions.ValidationError(str(error)) # ensure correct creator if not self.request.user.is_superuser: if not basket.shop == shop: raise exceptions.PermissionDenied("No permission") customer_id = (basket.customer.pk if basket.customer else None) controlled_contact_ids = self._get_controlled_contacts_by_user( self.request.user) is_staff = self.is_staff_user(shop, self.request.user) if customer_id and customer_id not in controlled_contact_ids and not is_staff: raise exceptions.PermissionDenied("No permission") return basket
def handle_update(request, basket, **kwargs): """ Handle updating a basket, i.e. deleting some lines or updating quantities. This dispatches further to whatever is declared by the `SHUUP_BASKET_UPDATE_METHODS_SPEC` configuration entry. """ methods = cached_load("SHUUP_BASKET_UPDATE_METHODS_SPEC")(request=request, basket=basket) prefix_method_dict = methods.get_prefix_to_method_map() basket_changed = False # If any POST items match a prefix defined in prefix_method_dict, call the appropriate model method. for key, value in six.iteritems(kwargs): for prefix, method in six.iteritems(prefix_method_dict): if key.startswith(prefix): line_id = key[len(prefix):] line = basket.find_line_by_line_id(line_id) field_changed = method(key=key, value=value, line=line) basket_changed = (basket_changed or field_changed) break if basket_changed: # pragma: no branch basket.clean_empty_lines() basket.dirty = True basket.uncache()
def get_object(self): uuid = get_key(self.kwargs.get(self.lookup_field, "")) shop = self.request.shop loaded_basket = Basket.objects.filter(key=uuid).first() # ensure correct owner if not self.request.user.is_superuser: if not loaded_basket.shop == shop: raise exceptions.PermissionDenied("No permission") customer_id = (loaded_basket.customer.pk if loaded_basket.customer else None) controlled_contact_ids = self._get_controlled_contacts_by_user( self.request.user) is_staff = self.is_staff_user(shop, self.request.user) if customer_id and customer_id not in controlled_contact_ids and not is_staff: raise exceptions.PermissionDenied("No permission") # actually load basket basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(self.request._request, basket_name=uuid) try: basket._data = basket.storage.load(basket) except BasketCompatibilityError as error: raise exceptions.ValidationError(str(error)) # Hack: the storage should do this already # set the correct basket customer if loaded_basket and loaded_basket.customer: basket.customer = loaded_basket.customer return basket
def get_object(self): uuid = get_key(self.kwargs.get(self.lookup_field, "")) user = self.request.user shop = self.request.shop # ensure correct owner loaded_basket = Basket.objects.filter(key=uuid).first() if not self.request.user.is_superuser: # TODO: THIS IS REALLY UGLY if loaded_basket: if user.is_staff: if not shop or user.pk not in shop.staff_members.all().values_list("pk", flat=True): raise exceptions.PermissionDenied("No permission") else: if loaded_basket.customer and not loaded_basket.customer.user.pk == self.request.user.pk: raise exceptions.PermissionDenied("No permission") elif not loaded_basket.shop == shop: raise exceptions.PermissionDenied("No permission") # actually load basket basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(self.request._request, basket_name=uuid) try: basket._data = basket.storage.load(basket) except BasketCompatibilityError as error: raise exceptions.ValidationError(str(error)) return basket
def handle_update(request, basket, **kwargs): """ Handle updating a basket, i.e. deleting some lines or updating quantities. This dispatches further to whatever is declared by the `SHUUP_BASKET_UPDATE_METHODS_SPEC` configuration entry. """ methods = cached_load("SHUUP_BASKET_UPDATE_METHODS_SPEC")(request=request, basket=basket) prefix_method_dict = methods.get_prefix_to_method_map() basket_changed = False # If any POST items match a prefix defined in prefix_method_dict, call the appropriate model method. for key, value in six.iteritems(kwargs): for prefix, method in six.iteritems(prefix_method_dict): if key.startswith(prefix): line_id = key[len(prefix):] line = basket.find_line_by_line_id(line_id) field_changed = method( key=key, value=value, line=line ) basket_changed = (basket_changed or field_changed) break if basket_changed: # pragma: no branch basket.clean_empty_lines() basket.dirty = True basket.uncache()
def get_form_defs(self): initial = { } # TODO: should we do this? model_to_dict(self.object, AddressForm._meta.fields) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") yield FormDef( name="shipping_address", form_class=address_form_class, required=False, kwargs={ "instance": self.object.default_shipping_address, "initial": initial }, ) yield FormDef( name="billing_address", form_class=address_form_class, required=False, kwargs={ "instance": self.object.default_billing_address, "initial": initial }, ) # Using a pseudo formdef to group the two actual formdefs... yield TemplatedFormDef( name="addresses", form_class=forms.Form, required=False, template_name="shuup/admin/contacts/_edit_addresses_form.jinja", )
def get_form(self, form_class): contact = get_person_contact(self.request.user) form_group = FormGroup(**self.get_form_kwargs()) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") form_group.add_form_def("billing", address_form_class, kwargs={"instance": contact.default_billing_address}) form_group.add_form_def("shipping", address_form_class, kwargs={"instance": contact.default_shipping_address}) form_group.add_form_def("contact", PersonContactForm, kwargs={"instance": contact}) return form_group
def get_price_info(self, context, product, quantity=1): product_id = (product if isinstance(product, six.integer_types) else product.pk) shop = context.shop # By default let's use supplier passed to context. supplier = context.supplier if not supplier: # Since supplier is optional I am pretty sure # there is cases that supplier is not passed to # pricing context. This is not a problem. The # pricing module which decides to use supplier # for product prices mjust need to have some sane # fallback. supplier_strategy = cached_load("SHUUP_SHOP_PRODUCT_SUPPLIERS_STRATEGY") kwargs = { "product_id": product_id, "shop": context.shop, "customer": context.customer, "quantity": quantity, "basket": context.basket } # Since this is custom pricing module it # requires also custom supplier strategy. # Some example is provided in # `shuup.testing.supplier_pricing.supplier_strategy:CheapestSupplierPriceSupplierStrategy` supplier = supplier_strategy().get_supplier(**kwargs) # Like now in customer group pricing let's take default price from shop product default_price_values = list(ShopProduct.objects.filter( product_id=product_id, shop=shop).values_list("default_price_value", flat=True)) if len(default_price_values) == 0: # No shop product return PriceInfo(price=shop.create_price(0), base_price=shop.create_price(0), quantity=quantity) else: default_price = default_price_values[0] or 0 # Then the actual supplier price in case we have # been able to figure out some supplier. I guess # it is problem for supplier strategy if it allows # supplier to be None in some weird scenarios. # Not sure though what would happen in shop product # orderability checks and so on. price = None if supplier: result = SupplierPrice.objects.filter( shop=shop, product_id=product_id, supplier=supplier ).order_by("amount_value")[:1].values_list("amount_value", flat=True) if result: price = result[0] if not price: price = default_price return PriceInfo( price=shop.create_price(price * quantity), base_price=shop.create_price(price * quantity), quantity=quantity, )
def get_supplier(self, customer=None, quantity=None, shipping_address=None): supplier_strategy = cached_load("SHUUP_SHOP_PRODUCT_SUPPLIERS_STRATEGY") kwargs = { "shop_product": self, "customer": customer, "quantity": quantity, "shipping_address": shipping_address } return supplier_strategy().get_supplier(**kwargs)
def get_storage(): """ Retrieve a basket storage object. :return: A basket storage object :rtype: BasketStorage """ storage_class = cached_load("SHUUP_BASKET_STORAGE_CLASS_SPEC") return storage_class()
def get(self, request, *args, **kwargs): shop_product = self.get_object() current_supplier = None if request.user.is_superuser else get_supplier(request) cloner = cached_load("SHUUP_ADMIN_PRODUCT_CLONER")(request.shop, current_supplier) copied_shop_product = cloner.clone_product(shop_product=shop_product) messages.success( request, _("{product_name} was successfully copied".format(product_name=copied_shop_product.product)) ) return HttpResponseRedirect(self.get_success_url(copied_shop_product))
def get_form(self, form_class): fg = FormGroup(**self.get_form_kwargs()) default_address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") for kind in self.address_kinds: fg.add_form_def(kind, form_class=self.address_form_classes.get( kind, default_address_form_class)) if self.company_form_class and not self.request.customer: fg.add_form_def("company", self.company_form_class, required=False) return fg
def handle_get_folders(self, data): shop = get_shop(self.request) users_owned_folders = Folder.objects.filter( media_folder__owners=self.user) root_folders = None # If the user has a root folder and not permission to view all folders if len(users_owned_folders) > 0 and not has_permission( self.user, "media.view-all"): all_accessed_folders = list( Folder._tree_manager.filter( _get_folder_query_filter(shop, self.user)).order_by( users_owned_folders.first()._mptt_meta.level_attr)) get_media_folder = cached_load( "SHUUP_GET_MEDIA_FOLDER_FROM_FOLDER") # We will need to change the tree ordering of folders that the user owns, # so the owning folders shows up under the root folder. # This is because if admin gives view access to a folder that has a lower level (closer to the root), # then the folder the user owns. It would be stacked under the folder that the admin has given access to, # insted of under the root folder. ordered_folders = [] for index, folder in enumerate(all_accessed_folders): media_folder = get_media_folder(folder) if self.user in media_folder.owners.all(): setattr(all_accessed_folders[index], folder._mptt_meta.level_attr, 0) ordered_folders.insert(0, all_accessed_folders[index]) else: in_path = False for folder_on_path in folder.logical_path: print(folder_on_path) if folder_on_path in all_accessed_folders: ordered_folders.append(folder) in_path = True break if not in_path: setattr(folder, folder._mptt_meta.level_attr, 0) ordered_folders.insert(0, folder) root_folders = get_cached_trees(ordered_folders) else: # Everything is shown under the fake root folder that is actually not a real folder root_folders = get_cached_trees( Folder._tree_manager.filter( _get_folder_query_filter(shop, self.user))) return JsonResponse({ "rootFolder": filer_folder_to_json_dict(None, root_folders, self.user) })
def get_context_data(self, context): context_data = super(ShippingSimulatorPlugin, self).get_context_data(context) resolved = resolve(context["request"].path) # Only works on ProductDetailView if resolved.view_name in ("shuup:product", "shuup:basket"): context_data["title"] = self.get_translated_value("title") context_data["form"] = cached_load("SHIPPING_SIMULATOR_CLASS_SPEC")().get_form() context_data["from_session"] = (resolved.view_name == "shuup:basket") return context_data
def get_form(self, form_class): kwargs = self.get_form_kwargs() fg = FormGroup(data=kwargs.get("data"), files=kwargs.get("files")) default_address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") fg.add_form_def("billing", default_address_form_class) fg.add_form_def("shipping", default_address_form_class) fg.add_form_def("order", self.order_form_class, kwargs={ "basket": self.request.basket, "shop": self.request.shop }) return fg
def login(request, **kwargs): if not request.user.is_anonymous( ) and request.method == "POST": # We're logging in, so log out first do_logout(request) kwargs.setdefault("extra_context", {})["error"] = request.GET.get("error") return auth_views.login( request=request, authentication_form=cached_load("SHUUP_ADMIN_AUTH_FORM_SPEC"), **kwargs)
def handle_get_edit_url(self, data): """ Get's the urls for the view to edit access to the folder """ shop = get_shop(self.request) folder = _get_folder_query(shop, self.user).get(pk=data["id"]) get_media_folder = cached_load("SHUUP_GET_MEDIA_FOLDER_FROM_FOLDER") media_folder = get_media_folder(folder) url = reverse("shuup_admin:media.edit-access", kwargs={"pk": media_folder.id}) return JsonResponse({"success": True, "url": url})
def __init__(self, *args, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.fields['name'].required = True self.fields['tax_number'].required = True address_form = cached_load('SHUUP_ADDRESS_MODEL_FORM')() for field in self.fields: if field not in ('name', 'tax_number', 'www'): address_formfield = address_form.fields.get(field) if address_formfield: self.fields[field].required = address_formfield.required else: del self.fields[field]
def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(CustomerInformationFormGroup, self).__init__(*args, **kwargs) contact = get_person_contact(self.request.user) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") for form_name in self.address_forms: self.add_form_def(form_name, address_form_class, kwargs={ "instance": getattr(contact, "default_%s_address" % form_name) }) self.add_form_def("contact", PersonContactForm, kwargs={"instance": contact})
def get_basket(request, basket_name="basket", basket_class=None): """ :type request: django.http.request.HttpRequest :rtype: shuup.front.basket.objects.BaseBasket """ if basket_name == "basket" and hasattr(request, "basket"): return request.basket if basket_class is None: basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") return basket_class(request, basket_name=basket_name)
def get_form(self, form_class): fg = FormGroup(**self.get_form_kwargs()) default_address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") for kind in self.address_kinds: fg.add_form_def(kind, form_class=self.address_form_classes.get(kind, default_address_form_class)) fg.add_form_def("saved_{}".format(kind), form_class=SavedAddressForm, required=False, kwargs={"kind": kind, "owner": self.basket.customer}) if self.company_form_class and not self.request.customer: fg.add_form_def("company", self.company_form_class, required=False) return fg
def get_basket(request): """ :type request: django.http.request.HttpRequest :rtype: shuup.front.basket.objects.BaseBasket """ if not hasattr(request, "basket"): basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") # This is a little weird in that this is likely to be called from `BasketMiddleware`, # which would do the following assignment anyway. However, in case it's _not_ called # from there, for some reason, we want to still be able to cache the basket. request.basket = basket_class(request) return request.basket
def get_form(self, form_class=None): order = self.get_object() form_group = FormGroup(**self.get_form_kwargs()) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") form_group.add_form_def( "billing_address", address_form_class, kwargs={"initial": get_data_dict(order.billing_address) if order.billing_address else {}}) form_group.add_form_def( "shipping_address", address_form_class, kwargs={"initial": get_data_dict(order.shipping_address) if order.shipping_address else {}}) return form_group
def _pack_source(self, source): """ Empacota itens do pedido :rtype: Iterable[shuup_order_packager.package.AbstractPackage|None] :return: Lista de pacotes ou None se for impossível empacotar pedido """ packager = cached_load("CORREIOS_PRODUCTS_PACKAGER_CLASS")() packager.add_constraint(SimplePackageDimensionConstraint(self.max_width, self.max_length, self.max_height, self.max_edges_sum)) packager.add_constraint(WeightPackageConstraint(self.max_weight * KG_TO_G)) return packager.pack_source(source)
def test_basket_with_custom_shop(rf): """ Set a different shop for basket """ with override_settings(**CORE_BASKET_SETTINGS): shop1 = factories.get_default_shop() shop2 = factories.get_shop(identifier="shop2") user = factories.create_random_user() request = apply_request_middleware(rf.get("/"), user=user, shop=shop1) basket_class = cached_load("SHUUP_BASKET_CLASS_SPEC") basket = basket_class(request, "basket", shop=shop2) assert basket.shop == shop2 product_shop2 = factories.create_product("product_shop2", shop2, factories.get_default_supplier(), 10) line = basket.add_product(factories.get_default_supplier(), shop2, product_shop2, 1) assert line.shop == shop2
def get_form_defs(self): initial = {} # TODO: should we do this? model_to_dict(self.object, AddressForm._meta.fields) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") yield FormDef( name="shipping_address", form_class=address_form_class, required=False, kwargs={"instance": self.object.default_shipping_address, "initial": initial} ) yield FormDef( name="billing_address", form_class=address_form_class, required=False, kwargs={"instance": self.object.default_billing_address, "initial": initial} ) # Using a pseudo formdef to group the two actual formdefs... yield TemplatedFormDef( name="addresses", form_class=forms.Form, required=False, template_name="shuup/admin/contacts/_edit_addresses_form.jinja" )
def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") self.instance = kwargs.pop("instance") super(AddressBookFormGroup, self).__init__(*args, **kwargs) address_kwargs = {} saved_address_kwargs = {} if self.instance: address_kwargs["instance"] = self.instance.address saved_address_kwargs["initial"] = { "role": self.instance.role, "status": self.instance.status, "title": self.instance.title, } self.add_form_def("address", cached_load("SHUUP_ADDRESS_MODEL_FORM"), kwargs=address_kwargs) self.add_form_def("saved_address", self.saved_address_form, kwargs=saved_address_kwargs)
def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(CompanyRegistrationForm, self).__init__(*args, **kwargs) address_form_cls = cached_load('SHUUP_ADDRESS_MODEL_FORM') self.add_form_def('company', CompanyForm, kwargs={"request": self.request}) self.add_form_def('billing', address_form_cls) self.add_form_def('contact_person', ContactPersonForm) self.add_form_def('user_account', UserCreationForm) for provider_cls in get_provide_objects("front_company_registration_form_provider"): provider = provider_cls(self, self.request) for definition in provider.get_definitions(): self.add_form_def( name=definition.form_name, form_class=definition.form_class, required=definition.required, kwargs=dict(shop=self.request.shop, request=self.request))
def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(CompanyInformationFormGroup, self).__init__(*args, **kwargs) user = self.request.user company = get_company_contact(user) person = get_person_contact(user) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") for form_name in self.address_forms: self.add_form_def( form_name, address_form_class, kwargs={ "instance": _get_default_address_for_contact(company, "default_%s_address" % form_name, person) } ) self.add_form_def("contact", CompanyContactForm, kwargs={"instance": company})
def get_form(self, form_class): form_group = FormGroup(**self.get_form_kwargs()) address_kwargs = {} saved_address_kwargs = {} if self.instance: address_kwargs["instance"] = self.instance.address saved_address_kwargs["initial"] = { "role": self.instance.role, "status": self.instance.status, "title": self.instance.title, } form_group.add_form_def("address", cached_load("SHUUP_ADDRESS_MODEL_FORM"), kwargs=address_kwargs) form_group.add_form_def( "saved_address", SavedAddressForm, kwargs=saved_address_kwargs ) return form_group
def get_form_defs(self): shop = self.object context = cached_load("SHUUP_XTHEME_ADMIN_THEME_CONTEXT")(shop) context.update({"shop": shop}) current_theme_class = (context["current_theme"] or context["theme_classes"][0]) current_theme_settings = ThemeSettings.objects.get_or_create( shop=shop, theme_identifier=current_theme_class.identifier )[0] context["active_stylesheet"] = current_theme_settings.data.get("settings", {}).get("stylesheet", None) return [ TemplatedWizardFormDef( template_name="shuup/xtheme/admin/wizard.jinja", name="theme", form_class=ActivationForm, context=context ) ]
def get_form(self, form_class): user = self.request.user company = get_company_contact(user) person = get_person_contact(user) form_group = FormGroup(**self.get_form_kwargs()) address_form_class = cached_load("SHUUP_ADDRESS_MODEL_FORM") form_group.add_form_def( "billing", address_form_class, kwargs={ "instance": _get_default_address_for_contact(company, "default_billing_address", person) } ) form_group.add_form_def( "shipping", address_form_class, kwargs={ "instance": _get_default_address_for_contact(company, "default_shipping_address", person) } ) form_group.add_form_def("contact", CompanyContactForm, kwargs={"instance": company}) return form_group
def get_basket_command_dispatcher(request): """ :type request: django.http.request.HttpRequest :rtype: shuup.front.basket.command_dispatcher.BasketCommandDispatcher """ return cached_load("SHUUP_BASKET_COMMAND_DISPATCHER_SPEC")(request=request)
def get_basket_view(): view = cached_load("SHUUP_BASKET_VIEW_SPEC") if hasattr(view, "as_view"): # pragma: no branch view = view.as_view() return view
def get_basket_order_creator(request=None): return cached_load("SHUUP_BASKET_ORDER_CREATOR_SPEC")(request=request)