Restore form when form submit fails due to error

This commit is contained in:
Antoine Bartuccio 2024-12-20 19:41:38 +01:00
parent 8ebea00896
commit f9d7dc7d3a
3 changed files with 42 additions and 8 deletions

View File

@ -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<string, Product>;
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

View File

@ -169,21 +169,36 @@
{{ super() }}
<script>
const products = {
{%- for p in products -%}
{{ p.id }}: {
id: "{{ p.id }}",
name: "{{ p.name }}",
price: {{ p.price }},
hasTrayPrice: {{ p.tray | tojson }},
{%- for product in products -%}
{{ product.id }}: {
id: "{{ product.id }}",
name: "{{ product.name }}",
price: {{ product.price }},
hasTrayPrice: {{ product.tray | tojson }},
},
{%- endfor -%}
};
const formInitial = [
{%- for f in form -%}
{%- if f.cleaned_data -%}
{
{%- if f.cleaned_data["id"] -%}
id: '{{ f.cleaned_data["id"] | tojson }}',
{%- endif -%}
{%- if f.cleaned_data["quantity"] -%}
quantity: {{ f.cleaned_data["quantity"] | tojson }},
{%- endif -%}
},
{%- endif -%}
{%- endfor -%}
];
window.addEventListener("DOMContentLoaded", () => {
loadCounter({
csrfToken: "{{ csrf_token }}",
clickApiUrl: "{{ url('counter:click', counter_id=counter.id, user_id=customer.user.id) }}", customerBalance: {{ customer.amount }},
products: products,
customerId: {{ customer.pk }},
formInitial: formInitial,
});
});
</script>

View File

@ -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: