Optimize product id validation on counter click

This commit is contained in:
Antoine Bartuccio 2024-12-22 02:14:14 +01:00
parent ff475c2b87
commit 73bb53bfe0

View File

@ -55,7 +55,7 @@ class ProductForm(Form):
self, self,
customer: Customer, customer: Customer,
counter: Counter, counter: Counter,
allowed_products: list[Product], allowed_products: dict[int, Product],
*args, *args,
**kwargs, **kwargs,
): ):
@ -64,25 +64,24 @@ class ProductForm(Form):
self.allowed_products = allowed_products self.allowed_products = allowed_products
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def clean(self): def clean_id(self):
cleaned_data = super().clean() data = self.cleaned_data["id"]
if len(self.errors) > 0:
return
# We store self.product so we can use it later on the formset validation # We store self.product so we can use it later on the formset validation
self.product = next( # And also in the global clean
( self.product = self.allowed_products.get(data, None)
product
for product in self.allowed_products
if product.id == cleaned_data["id"]
),
None,
)
if self.product is None: if self.product is None:
raise ValidationError( raise ValidationError(
_("The selected product isn't available for this user") _("The selected product isn't available for this user")
) )
return data
def clean(self):
cleaned_data = super().clean()
if len(self.errors) > 0:
return
# Compute prices # Compute prices
cleaned_data["bonus_quantity"] = 0 cleaned_data["bonus_quantity"] = 0
if self.product.tray: if self.product.tray:
@ -183,7 +182,9 @@ class CounterClick(CounterTabsMixin, CanViewMixin, SingleObjectMixin, FormView):
kwargs["form_kwargs"] = { kwargs["form_kwargs"] = {
"customer": self.customer, "customer": self.customer,
"counter": self.object, "counter": self.object,
"allowed_products": self.get_products(), "allowed_products": {
product.id: product for product in self.get_products()
},
} }
return kwargs return kwargs