Refactor duplicated logic in invoice for HTMx trigger and location

This commit is contained in:
jordi fita mas 2023-04-06 12:20:40 +02:00
parent 2df6947577
commit 4b4d7ad87d
1 changed files with 26 additions and 41 deletions

View File

@ -457,22 +457,7 @@ func HandleAddInvoice(w http.ResponseWriter, r *http.Request, _ httprouter.Param
return
}
slug := conn.MustGetText(r.Context(), "", "select add_invoice($1, $2, $3, $4, $5, $6, $7)", company.Id, form.Date, form.Customer, form.Notes, form.PaymentMethod, form.Tags, NewInvoiceProductArray(form.Products))
viewUrl := companyURI(company, "/invoices/"+slug)
if IsHTMxRequest(r) {
w.Header().Set(HxTrigger, "closeModal")
location := &HTMxLocation{
Target: "main",
}
if form.Location.Val == "view" {
location.Path = viewUrl
} else {
location.Path = companyURI(company, "/invoices")
}
w.Header().Set(HxLocation, MustMarshalHTMxLocation(location))
w.WriteHeader(http.StatusNoContent)
} else {
http.Redirect(w, r, viewUrl, http.StatusSeeOther)
}
closeModalAndRedirect(w, r, form.Location.Val, "/invoices/"+slug, "/invoices")
}
func HandleNewInvoiceAction(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
@ -847,16 +832,7 @@ func HandleUpdateInvoice(w http.ResponseWriter, r *http.Request, params httprout
if slug == "" {
http.NotFound(w, r)
}
indexUrl := companyURI(mustGetCompany(r), "/invoices")
if IsHTMxRequest(r) {
w.Header().Set(HxLocation, MustMarshalHTMxLocation(&HTMxLocation{
Path: indexUrl,
Target: "main",
}))
w.WriteHeader(http.StatusNoContent)
} else {
http.Redirect(w, r, indexUrl, http.StatusSeeOther)
}
htmxRedirect(w, r, companyURI(mustGetCompany(r), "/invoices"))
} else {
slug := params[0].Value
if !form.Validate() {
@ -869,22 +845,31 @@ func HandleUpdateInvoice(w http.ResponseWriter, r *http.Request, params httprout
http.NotFound(w, r)
return
}
viewUrl := companyURI(company, "/invoices/"+slug)
closeModalAndRedirect(w, r, form.Location.Val, "/invoices/"+slug, "/invoices")
}
}
func closeModalAndRedirect(w http.ResponseWriter, r *http.Request, selector string, viewUri string, indexUri string) {
company := mustGetCompany(r)
nextUri := companyURI(company, indexUri)
if IsHTMxRequest(r) {
w.Header().Set(HxTrigger, "closeModal")
location := &HTMxLocation{
if selector == "view" {
nextUri = companyURI(company, viewUri)
}
}
htmxRedirect(w, r, nextUri)
}
func htmxRedirect(w http.ResponseWriter, r *http.Request, uri string) {
if IsHTMxRequest(r) {
w.Header().Set(HxLocation, MustMarshalHTMxLocation(&HTMxLocation{
Path: uri,
Target: "main",
}
if form.Location.Val == "view" {
location.Path = viewUrl
} else {
location.Path = companyURI(company, "/invoices")
}
w.Header().Set(HxLocation, MustMarshalHTMxLocation(location))
}))
w.WriteHeader(http.StatusNoContent)
} else {
http.Redirect(w, r, viewUrl, http.StatusSeeOther)
}
http.Redirect(w, r, uri, http.StatusSeeOther)
}
}