From 79ea2f366adf939bc00360e716199536804c9e67 Mon Sep 17 00:00:00 2001 From: jordi fita mas Date: Wed, 1 Mar 2023 11:40:23 +0100 Subject: [PATCH] =?UTF-8?q?Add=20grouping=20for=20form=E2=80=99s=20select?= =?UTF-8?q?=20field?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We will only allow to select a tax from each of the tax classes, but the user needs to know what class each tax belongs to, and grouping the taxes by class in the select helps with that. --- pkg/form.go | 24 ++++++++++++++++++++++++ pkg/invoices.go | 2 +- web/template/form.gohtml | 15 +++++++++++++-- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/pkg/form.go b/pkg/form.go index 8adcede..fe41570 100644 --- a/pkg/form.go +++ b/pkg/form.go @@ -66,6 +66,7 @@ func (field *InputField) Float64() float64 { type SelectOption struct { Value string Label string + Group string } type SelectField struct { @@ -158,6 +159,29 @@ func MustGetOptions(ctx context.Context, conn *Conn, sql string, args ...interfa return options } +func MustGetGroupedOptions(ctx context.Context, conn *Conn, sql string, args ...interface{}) []*SelectOption { + rows, err := conn.Query(ctx, sql, args...) + if err != nil { + panic(err) + } + defer rows.Close() + + var options []*SelectOption + for rows.Next() { + option := &SelectOption{} + err = rows.Scan(&option.Value, &option.Label, &option.Group) + if err != nil { + panic(err) + } + options = append(options, option) + } + if rows.Err() != nil { + panic(rows.Err()) + } + + return options +} + func mustGetCountryOptions(ctx context.Context, conn *Conn, locale *Locale) []*SelectOption { return MustGetOptions(ctx, conn, "select country.country_code, coalesce(i18n.name, country.name) as l10n_name from country left join country_i18n as i18n on country.country_code = i18n.country_code and i18n.lang_tag = $1 order by l10n_name", locale.Language) } diff --git a/pkg/invoices.go b/pkg/invoices.go index 0a2e9cc..6f2d6a3 100644 --- a/pkg/invoices.go +++ b/pkg/invoices.go @@ -418,7 +418,7 @@ func (form *invoiceForm) AddProducts(ctx context.Context, conn *Conn, productsId } func mustGetTaxOptions(ctx context.Context, conn *Conn, company *Company) []*SelectOption { - return MustGetOptions(ctx, conn, "select tax_id::text, name from tax where company_id = $1 order by name", company.Id) + return MustGetGroupedOptions(ctx, conn, "select tax_id::text, tax.name, tax_class.name from tax join tax_class using (tax_class_id) where tax.company_id = $1 order by tax_class.name, tax.name", company.Id) } type invoiceProductForm struct { diff --git a/web/template/form.gohtml b/web/template/form.gohtml index 486b012..6b9eadb 100644 --- a/web/template/form.gohtml +++ b/web/template/form.gohtml @@ -43,15 +43,26 @@