From c6e95bc3454d468cab8337ce2b22b1fcec541a89 Mon Sep 17 00:00:00 2001 From: Sli Date: Fri, 20 Dec 2024 19:41:38 +0100 Subject: [PATCH] Restore form when form submit fails due to error --- .../bundled/counter/counter-click-index.ts | 15 +++++++++++ counter/templates/counter/counter_click.jinja | 27 ++++++++++++++----- counter/views/click.py | 8 ++++-- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/counter/static/bundled/counter/counter-click-index.ts b/counter/static/bundled/counter/counter-click-index.ts index a33dfa25..e736857d 100644 --- a/counter/static/bundled/counter/counter-click-index.ts +++ b/counter/static/bundled/counter/counter-click-index.ts @@ -2,12 +2,19 @@ import { exportToHtml } from "#core:utils/globals"; const quantityForTrayPrice = 6; +interface InitialFormData { + /* Used to refill the form when the backend raises an error */ + id?: string; + quantity?: number; +} + interface CounterConfig { csrfToken: string; clickApiUrl: string; customerBalance: number; customerId: number; products: Record; + formInitial: InitialFormData[]; } interface Product { @@ -48,8 +55,16 @@ exportToHtml("loadCounter", (config: CounterConfig) => { codeField: undefined, init() { + // Fill the basket with the initial data + for (const entry of config.formInitial) { + if (entry.id !== undefined && entry.quantity !== undefined) { + this.addToBasket(entry.id, entry.quantity); + } + } + this.codeField = this.$refs.codeField; this.codeField.widget.focus(); + // It's quite tricky to manually apply attributes to the management part // of a formset so we dynamically apply it here this.$refs.basketManagementForm diff --git a/counter/templates/counter/counter_click.jinja b/counter/templates/counter/counter_click.jinja index cfc4794f..35249b33 100644 --- a/counter/templates/counter/counter_click.jinja +++ b/counter/templates/counter/counter_click.jinja @@ -169,21 +169,36 @@ {{ super() }} diff --git a/counter/views/click.py b/counter/views/click.py index cbde55b5..a8abf638 100644 --- a/counter/views/click.py +++ b/counter/views/click.py @@ -117,12 +117,16 @@ class BaseBasketForm(BaseFormSet): super().clean() if len(self) == 0: return - if len(self.errors) > 0: - return + self._check_forms_have_errors() self._check_recorded_products(self[0].customer) self._check_enough_money(self[0].counter, self[0].customer) + def _check_forms_have_errors(self): + for form in self: + if len(form.errors): + raise ValidationError(_("Submmited basket is invalid")) + def _check_enough_money(self, counter: Counter, customer: Customer): self.total_price = sum([data["total_price"] for data in self.cleaned_data]) if self.total_price > customer.amount: