Add the product filter form

I need a way to search products by name in the invoice form, when the
user adds or changes a product.  Since this is something that i have to
add too to the product list, i added it now so the function will already
be ready.
This commit is contained in:
jordi fita mas 2023-04-23 03:20:01 +02:00
parent c2f6d299b4
commit 2ced61d304
2 changed files with 106 additions and 12 deletions

View File

@ -8,6 +8,7 @@ import (
"math" "math"
"net/http" "net/http"
"strconv" "strconv"
"strings"
) )
type ProductEntry struct { type ProductEntry struct {
@ -19,14 +20,21 @@ type ProductEntry struct {
type productsIndexPage struct { type productsIndexPage struct {
Products []*ProductEntry Products []*ProductEntry
Filters *productFilterForm
} }
func IndexProducts(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { func IndexProducts(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
conn := getConn(r) conn := getConn(r)
company := mustGetCompany(r) company := mustGetCompany(r)
tag := r.URL.Query().Get("tag") locale := getLocale(r)
filters := newProductFilterForm(locale)
if err := filters.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
page := &productsIndexPage{ page := &productsIndexPage{
Products: mustCollectProductEntries(r.Context(), conn, company, tag), Products: mustCollectProductEntries(r.Context(), conn, company, filters),
Filters: filters,
} }
mustRenderMainTemplate(w, r, "products/index.gohtml", page) mustRenderMainTemplate(w, r, "products/index.gohtml", page)
} }
@ -152,8 +160,72 @@ func HandleUpdateProduct(w http.ResponseWriter, r *http.Request, params httprout
} }
} }
func mustCollectProductEntries(ctx context.Context, conn *Conn, company *Company, tag string) []*ProductEntry { type productFilterForm struct {
rows, err := conn.Query(ctx, ` Name *InputField
Tags *TagsField
TagsCondition *ToggleField
}
func newProductFilterForm(locale *Locale) *productFilterForm {
return &productFilterForm{
Name: &InputField{
Name: "number",
Label: pgettext("input", "Invoice Number", locale),
Type: "search",
},
Tags: &TagsField{
Name: "tags",
Label: pgettext("input", "Tags", locale),
},
TagsCondition: &ToggleField{
Name: "tags_condition",
Label: pgettext("input", "Tags Condition", locale),
Selected: "and",
FirstOption: &ToggleOption{
Value: "and",
Label: pgettext("tag condition", "All", locale),
Description: gettext("Invoices must have all the specified labels.", locale),
},
SecondOption: &ToggleOption{
Value: "or",
Label: pgettext("tag condition", "Any", locale),
Description: gettext("Invoices must have at least one of the specified labels.", locale),
},
},
}
}
func (form *productFilterForm) Parse(r *http.Request) error {
if err := r.ParseForm(); err != nil {
return err
}
form.Name.FillValue(r)
form.Tags.FillValue(r)
form.TagsCondition.FillValue(r)
return nil
}
func mustCollectProductEntries(ctx context.Context, conn *Conn, company *Company, filters *productFilterForm) []*ProductEntry {
args := []interface{}{company.Id}
where := []string{"product.company_id = $1"}
appendWhere := func(expression string, value interface{}) {
args = append(args, value)
where = append(where, fmt.Sprintf(expression, len(args)))
}
if filters != nil {
name := strings.TrimSpace(filters.Name.String())
if name != "" {
appendWhere("product.name ilike $%d", "%"+name+"%")
}
if len(filters.Tags.Tags) > 0 {
if filters.TagsCondition.Selected == "and" {
appendWhere("product.tags @> $%d", filters.Tags)
} else {
appendWhere("product.tags && $%d", filters.Tags)
}
}
}
rows := conn.MustQuery(ctx, fmt.Sprintf(`
select product.slug select product.slug
, product.name , product.name
, to_price(price, decimal_digits) , to_price(price, decimal_digits)
@ -161,19 +233,15 @@ func mustCollectProductEntries(ctx context.Context, conn *Conn, company *Company
from product from product
join company using (company_id) join company using (company_id)
join currency using (currency_code) join currency using (currency_code)
where product.company_id = $1 and (($2 = '') or (tags @> array[$2]::tag_name[])) where (%s)
order by name order by name
`, company.Id, tag) `, strings.Join(where, ") AND (")), args...)
if err != nil {
panic(err)
}
defer rows.Close() defer rows.Close()
var entries []*ProductEntry var entries []*ProductEntry
for rows.Next() { for rows.Next() {
entry := &ProductEntry{} entry := &ProductEntry{}
err = rows.Scan(&entry.Slug, &entry.Name, &entry.Price, &entry.Tags) if err := rows.Scan(&entry.Slug, &entry.Name, &entry.Price, &entry.Tags); err != nil {
if err != nil {
panic(err) panic(err)
} }
entries = append(entries, entry) entries = append(entries, entry)
@ -281,3 +349,15 @@ func (form *productForm) MustFillFromDatabase(ctx context.Context, conn *Conn, s
form.Tax, form.Tax,
form.Tags)) form.Tags))
} }
func HandleProductSearch(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var name string
query := r.URL.Query()
for k := range query {
vs := query[k]
if len(vs) > 0 {
name = vs[0]
}
}
w.Write([]byte(name))
}

View File

@ -19,6 +19,20 @@
{{ define "content" }} {{ define "content" }}
{{- /*gotype: dev.tandem.ws/tandem/numerus/pkg.productsIndexPage*/ -}} {{- /*gotype: dev.tandem.ws/tandem/numerus/pkg.productsIndexPage*/ -}}
<div aria-label="{{( pgettext "Filters" "title" )}}">
<form method="GET" action="{{ companyURI "/products"}}"
data-hx-target="main"
data-hx-boost="true"
data-hx-trigger="change,search,submit"
>
{{ with .Filters }}
{{ template "input-field" .Name }}
{{ template "tags-field" .Tags | addTagsAttr (print `data-conditions="` .TagsCondition.Name `-field"`) }}
{{ template "toggle-field" .TagsCondition }}
{{ end }}
<button type="submit">{{( pgettext "Filter" "action" )}}</button>
</form>
</div>
<table> <table>
<thead> <thead>
<tr> <tr>
@ -37,7 +51,7 @@
<td> <td>
{{- range $index, $tag := .Tags }} {{- range $index, $tag := .Tags }}
{{- if gt $index 0 }}, {{ end -}} {{- if gt $index 0 }}, {{ end -}}
<a href="?tag={{ . }}" data-hx-target="main" data-hx-boost="true">{{ . }}</a> <a href="?tags={{ . }}" data-hx-target="main" data-hx-boost="true">{{ . }}</a>
{{- end }} {{- end }}
</td> </td>
<td class="numeric">{{ .Price | formatPrice }}</td> <td class="numeric">{{ .Price | formatPrice }}</td>