numerus/pkg/router.go

160 lines
6.7 KiB
Go
Raw Normal View History

package pkg
import (
"github.com/julienschmidt/httprouter"
"mime"
"net/http"
)
func NewRouter(db *Db, demo bool) http.Handler {
companyRouter := httprouter.New()
companyRouter.GET("/profile", GetProfileForm)
companyRouter.POST("/profile", HandleProfileForm)
companyRouter.GET("/tax-details", GetCompanyTaxDetailsForm)
companyRouter.POST("/tax-details", HandleCompanyTaxDetailsForm)
companyRouter.GET("/invoicing", serveCompanyInvoicingForm)
companyRouter.POST("/invoicing", handleCompanyInvoicingForm)
companyRouter.GET("/switch-company", GetCompanySwitcher)
companyRouter.GET("/taxes", serveCompanyTaxes)
companyRouter.POST("/taxes", HandleAddCompanyTax)
companyRouter.DELETE("/taxes/:taxId", HandleDeleteCompanyTax)
companyRouter.GET("/payment-methods", servePaymentMethods)
companyRouter.POST("/payment-methods", HandleAddPaymentMethod)
companyRouter.DELETE("/payment-methods/:paymentMethodId", HandleDeletePaymentMethod)
companyRouter.GET("/contacts", IndexContacts)
companyRouter.POST("/contacts", HandleAddContact)
Allow importing contacts from Holded This allows to import an Excel file exported from Holded, because it is our own user case. When we have more customers, we will give out an Excel template file to fill out. Why XLSX files instead of CSV, for instance? First, because this is the output from Holded, but even then we would have more trouble with CSV than with XLSX because of Microsoft: they royally fucked up interoperability when decided that CSV files, the files that only other applications or programmers see, should be “localized”, and use a comma or a **semicolon** to separate a **comma** separated file depending on the locale’s decimal separator. This is ridiculous because it means that CSV files created with an Excel in USA uses comma while the same Excel but with a French locale expects the fields to be separated by semicolon. And for no good reason, either. Since they fucked up so bad, decided to add a non-standard “meta” field to specify the separator, writing a `sep=,` in the first line, but this only works for reading, because saving the same file changes the separator back to the locale-dependent character and removes the “meta” field. And since everyone expects to open spreadsheet with Excel, i can not use CSV if i do not want a bunch of support tickets telling me that the template is all in a single line. I use an extremely old version of a xlsx reading library for golang[0] because it is already available in Debian repositories, and the only thing i want from it is to convert the convoluted XML file into a string array. Go is only responsible to read the file and dump its contents into a temporary table, so that it can execute the PL/pgSQL function that will actually move that data to the correct relations, much like add_contact does but in batch. In PostgreSQL version 16 they added a pg_input_is_valid function that i would use to test whether input values really conform to domains, but i will have to wait for Debian to pick up the new version. Meanwhile, i use a couple of temporary functions, in lieu of nested functions support in PostgreSQL. Part of #45 [0]: https://github.com/tealeg/xlsx
2023-07-02 22:05:47 +00:00
companyRouter.POST("/contacts/import", HandleImportContacts)
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("/invoices/:slug/download/:filename", ServeInvoiceAttachment)
companyRouter.GET("/quotes", IndexQuotes)
companyRouter.POST("/quotes", HandleAddQuote)
companyRouter.GET("/quotes/:slug", ServeQuote)
companyRouter.PUT("/quotes/:slug", HandleUpdateQuote)
companyRouter.POST("/quotes/:slug", HandleNewQuoteAction)
companyRouter.GET("/quotes/:slug/edit", ServeEditQuote)
companyRouter.POST("/quotes/:slug/edit", HandleEditQuoteAction)
companyRouter.PUT("/quotes/:slug/tags", HandleUpdateQuoteTags)
companyRouter.GET("/quotes/:slug/tags/edit", ServeEditQuoteTags)
companyRouter.GET("/search/products", HandleProductSearch)
2023-05-03 10:46:25 +00:00
companyRouter.GET("/expenses", IndexExpenses)
companyRouter.POST("/expenses", HandleNewExpenseAction)
2023-05-03 10:46:25 +00:00
companyRouter.GET("/expenses/:slug", ServeExpenseForm)
companyRouter.POST("/expenses/:slug", HandleEditExpenseAction)
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("/payments", servePaymentIndex)
companyRouter.POST("/payments", handleAddPayment)
companyRouter.GET("/payments/:slug", servePaymentForm)
companyRouter.PUT("/payments/:slug", handleEditPayment)
companyRouter.DELETE("/payments/:slug", handleRemovePayment)
2024-08-15 02:18:35 +00:00
companyRouter.PUT("/payments/:slug/tags", handleUpdatePaymentTags)
companyRouter.GET("/payments/:slug/tags/edit", servePaymentTagsEditForm)
2024-08-11 22:08:18 +00:00
companyRouter.GET("/payments/:slug/download/:filename", servePaymentAttachment)
companyRouter.GET("/payment-accounts", servePaymentAccountIndex)
companyRouter.POST("/payment-accounts", handleAddPaymentAccount)
companyRouter.GET("/payment-accounts/:slug", servePaymentAccountForm)
companyRouter.PUT("/payment-accounts/:slug", handleEditPaymentAccount)
companyRouter.GET("/", ServeDashboard)
router := httprouter.New()
router.ServeFiles("/static/*filepath", http.Dir("web/static"))
router.GET("/login", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
GetLoginForm(w, r, demo)
})
router.POST("/login", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
HandleLoginForm(w, r, demo)
})
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("/legal", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
mustRenderWebTemplate(w, r, "legal.gohtml", nil)
})
router.GET("/privacy", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
mustRenderWebTemplate(w, r, "privacy.gohtml", nil)
})
router.GET("/cookies", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
mustRenderWebTemplate(w, r, "cookies.gohtml", nil)
})
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 {
mustRenderWebTemplate(w, r, "home.gohtml", nil)
}
})
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)
})
}