numerus/pkg/router.go

117 lines
4.5 KiB
Go
Raw Normal View History

package pkg
import (
"github.com/julienschmidt/httprouter"
"mime"
"net/http"
)
func NewRouter(db *Db) http.Handler {
companyRouter := httprouter.New()
companyRouter.GET("/profile", GetProfileForm)
companyRouter.POST("/profile", HandleProfileForm)
companyRouter.GET("/tax-details", GetCompanyTaxDetailsForm)
companyRouter.POST("/tax-details", HandleCompanyTaxDetailsForm)
companyRouter.POST("/tax", HandleAddCompanyTax)
companyRouter.DELETE("/tax/:taxId", HandleDeleteCompanyTax)
companyRouter.POST("/payment-method", HandleAddPaymentMethod)
companyRouter.DELETE("/payment-method/:paymentMethodId", HandleDeletePaymentMethod)
companyRouter.GET("/contacts", IndexContacts)
companyRouter.POST("/contacts", HandleAddContact)
2023-02-03 12:29:10 +00:00
companyRouter.GET("/contacts/:slug", GetContactForm)
companyRouter.PUT("/contacts/:slug", HandleUpdateContact)
2023-05-12 09:32:39 +00:00
companyRouter.PUT("/contacts/:slug/tags", HandleUpdateContactTags)
companyRouter.GET("/contacts/:slug/tags/edit", ServeEditContactTags)
companyRouter.GET("/products", IndexProducts)
companyRouter.POST("/products", HandleAddProduct)
companyRouter.GET("/products/:slug", GetProductForm)
companyRouter.PUT("/products/:slug", HandleUpdateProduct)
2023-05-09 10:18:31 +00:00
companyRouter.PUT("/products/:slug/tags", HandleUpdateProductTags)
companyRouter.GET("/products/:slug/tags/edit", ServeEditProductTags)
2023-02-11 21:16:48 +00:00
companyRouter.GET("/invoices", IndexInvoices)
companyRouter.POST("/invoices", HandleAddInvoice)
Convert invoices to PDF with WeasyPrint Although it is possible to just print the invoice from the browser, many people will not even try an assume that they can not create a PDF for the invoice. I thought of using Groff or TeX to create the PDF, but it would mean maintaining two templates in two different systems (HTML and whatever i would use), and would probably look very different, because i do not know Groff or TeX that well. I wish there was a way to tell the browser to print to PDF, and it can be done, but only with the Chrome Protocol to a server-side running Chrome instance. This works, but i would need a Chrome running as a daemon. I also wrote a Qt application that uses QWebEngine to print the PDF, much like wkhtmltopdf, but with support for more recent HTML and CSS standards. Unfortunately, Qt 6.4’s embedded Chromium does not follow break-page-inside as well as WeasyPrint does. To use WeasyPrint, at first i wanted to reach the same URL as the user, passing the cookie to WeasyPrint so that i can access the same invoice as the user, something that can be done with wkhtmltopdf, but WeasyPrint does not have such option. I did it with a custom Python script, but then i need to package and install that script, that is not that much work, but using the Debian-provided script is even less work, and less likely to drift when WeasyPrint changes API. Also, it is unnecessary to do a network round-trip from Go to Python back to Go, because i can already write the invoice HTML as is to WeasyPrint’s stdin.
2023-02-26 16:26:09 +00:00
companyRouter.GET("/invoices/:slug", ServeInvoice)
companyRouter.PUT("/invoices/:slug", HandleUpdateInvoice)
companyRouter.POST("/invoices/:slug", HandleNewInvoiceAction)
companyRouter.GET("/invoices/:slug/edit", ServeEditInvoice)
companyRouter.POST("/invoices/:slug/edit", HandleEditInvoiceAction)
companyRouter.PUT("/invoices/:slug/tags", HandleUpdateInvoiceTags)
companyRouter.GET("/invoices/:slug/tags/edit", ServeEditInvoiceTags)
companyRouter.GET("/search/products", HandleProductSearch)
2023-05-03 10:46:25 +00:00
companyRouter.GET("/expenses", IndexExpenses)
companyRouter.POST("/expenses", HandleAddExpense)
companyRouter.GET("/expenses/:slug", ServeExpenseForm)
companyRouter.PUT("/expenses/:slug", HandleUpdateExpense)
2023-05-08 10:58:54 +00:00
companyRouter.PUT("/expenses/:slug/tags", HandleUpdateExpenseTags)
companyRouter.GET("/expenses/:slug/tags/edit", ServeEditExpenseTags)
companyRouter.GET("/expenses/:slug/download/:filename", ServeExpenseAttachment)
companyRouter.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
mustRenderMainTemplate(w, r, "dashboard.gohtml", nil)
})
router := httprouter.New()
router.ServeFiles("/static/*filepath", http.Dir("web/static"))
router.GET("/login", GetLoginForm)
router.POST("/login", HandleLoginForm)
router.POST("/logout", Authenticated(HandleLogout))
companyHandler := Authenticated(CompanyHandler(companyRouter))
router.GET("/company/:slug/*rest", companyHandler)
router.POST("/company/:slug/*rest", companyHandler)
router.PUT("/company/:slug/*rest", companyHandler)
router.DELETE("/company/:slug/*rest", companyHandler)
router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
user := getUser(r)
if user.LoggedIn {
conn := getConn(r)
company := &Company{
Slug: conn.MustGetText(r.Context(), "", "select slug::text from company order by company_id limit 1"),
}
http.Redirect(w, r, companyURI(company, "/"), http.StatusFound)
} else {
Add Catalan and Spanish translation with gotext[3] I had to choose between [1], [2], and [3]. As far as i could find, [1] is not easy to work with templates[4] and at the moment is not maintained[5]. Both [2] and [3] use the same approach to be used from within templates: you have to define a FuncMap with template functions that call the message catalog. Also, both libraries seems to be reasonably maintained, and have packages in Debian’s repository. However, [2] repeats the same mistakes that POSIX did with its catalogs—using identifiers that are not the strings in the source language—, however this time the catalogs are written in JSON or YAML! This, somehow, makes things worse…. [3], the one i settled with, is fine and decently maintained. There are some surprising things, such as to be able to use directly the PO file, and that it has higher priority over the corresponding MO, or that the order of parameters is reversed in respect to gettext. However, it uses a saner format, and is a lot easier to work with than [3]. The problem, of course, is that xgettext does not know how to find translatable strings inside the template. [3] includes a CLI tool similar to xgettext, but is not a drop-in replacement[6] and does not process templates. The proper way to handle this would be to add a parser to xgettext, but for now i found out that if i surround the call to the translation functions from within the template with parentheses, i can trick xgettext into believing it is parsing Scheme code, and extracts the strings successfully—at least, for what i have tried. Had to add the keyword for pgettext, because Schemed does not have it, but at least i can do that with command line parameters. For now i left only Spanish and Catalan as the two available languages, even though the source text is written in English, because that way i can make sure i do not leave strings untranslated. [1]: https://golang.org/x/text [2]: https://github.com/nicksnyder/go-i18n [3]: https://github.com/leonelquinteros/gotext [4]: https://github.com/golang/go/issues/39954 [5]: https://github.com/golang/go/issues/12750 [6]: https://github.com/leonelquinteros/gotext/issues/38
2023-01-18 18:07:42 +00:00
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
})
var handler http.Handler = router
handler = MethodOverrider(handler)
handler = LocaleSetter(db, handler)
handler = LoginChecker(db, handler)
handler = Recoverer(handler)
handler = Logger(handler)
return handler
}
func MethodOverrider(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
contentType := r.Header.Get("Content-Type")
contentType, _, err := mime.ParseMediaType(contentType)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if contentType == "multipart/form-data" {
if err := r.ParseMultipartForm(20 << 20); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
} else {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
2023-02-03 12:29:10 +00:00
override := r.FormValue(overrideMethodName)
if override == http.MethodDelete || override == http.MethodPut {
r2 := new(http.Request)
*r2 = *r
r2.Method = override
r = r2
}
}
next.ServeHTTP(w, r)
})
}