2023-01-17 09:40:22 +00:00
|
|
|
package pkg
|
2023-01-13 19:43:42 +00:00
|
|
|
|
|
|
|
import (
|
2023-02-03 11:30:56 +00:00
|
|
|
"github.com/julienschmidt/httprouter"
|
2023-05-14 16:46:16 +00:00
|
|
|
"mime"
|
|
|
|
"net/http"
|
2023-01-13 19:43:42 +00:00
|
|
|
)
|
|
|
|
|
Prefill login form when using the demo database
This is to help up “sell” the service: people can look around the demo
to see whether it fits them. Of course, everyone should have the same
username in the demo.
We talked about having the username and password displayed above the
form in the template, but i think it makes more sense to give users as
little work as necessary. Plus, that means i do not have to write them
down while developing.
Whether the database is demo or not is not something that directly
depends on the environment, but rather on which database we are
connected to, thus an environment variable would not make much sense—it
has to be something of the database.
PostgreSQL has no PRAGMA application_id or PRAGMA user_version as with
SQLite to include application-specific values to the database. The
equivalent would be customized options[0], intended for modules
configuration, but that would require me to execute an ALTER DATABASE
in demo.sql with an specific datbase name, or force the use of psql to
run script the script, because then i can use the :DBNAME placeholder.
I guess that the most “standard” way is to just create a function that
returns a know value if the database is demo. Sqitch does not add that
function, therefore it is unlikely to be there by change unless it is
the demo database.
https://www.postgresql.org/docs/15/runtime-config-custom.html
2024-01-20 19:23:18 +00:00
|
|
|
func NewRouter(db *Db, demo bool) http.Handler {
|
2023-02-03 11:30:56 +00:00
|
|
|
companyRouter := httprouter.New()
|
|
|
|
companyRouter.GET("/profile", GetProfileForm)
|
|
|
|
companyRouter.POST("/profile", HandleProfileForm)
|
|
|
|
companyRouter.GET("/tax-details", GetCompanyTaxDetailsForm)
|
2023-11-06 12:52:34 +00:00
|
|
|
companyRouter.GET("/switch-company", GetCompanySwitcher)
|
2023-02-03 11:30:56 +00:00
|
|
|
companyRouter.POST("/tax-details", HandleCompanyTaxDetailsForm)
|
|
|
|
companyRouter.POST("/tax", HandleAddCompanyTax)
|
|
|
|
companyRouter.DELETE("/tax/:taxId", HandleDeleteCompanyTax)
|
2023-03-03 15:49:06 +00:00
|
|
|
companyRouter.POST("/payment-method", HandleAddPaymentMethod)
|
|
|
|
companyRouter.DELETE("/payment-method/:paymentMethodId", HandleDeletePaymentMethod)
|
2023-02-03 11:30:56 +00:00
|
|
|
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)
|
2023-02-04 10:32:39 +00:00
|
|
|
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)
|
2023-03-07 10:52:09 +00:00
|
|
|
companyRouter.PUT("/invoices/:slug", HandleUpdateInvoice)
|
2023-03-13 14:00:35 +00:00
|
|
|
companyRouter.POST("/invoices/:slug", HandleNewInvoiceAction)
|
|
|
|
companyRouter.GET("/invoices/:slug/edit", ServeEditInvoice)
|
|
|
|
companyRouter.POST("/invoices/:slug/edit", HandleEditInvoiceAction)
|
Allow editing invoice tags inline from the index table
I use the same pattern as HTMx’s “Click to Edit” example[0], except that
my edit form is triggered by submit and by focus out of the tags input.
I could not, however, use the standard focus out event because it would
also trigger when removing a tag with the mouse, as for a moment the
remove button has the focus and the search input dispatches a bubbling
focusout. I had to resort to a custom event for that, but i am not
happy with it.
The autofocus attribute seems to do nothing in this case, so i need to
manually change the focus to the new input with JavaScript. However,
this means that i can not use the same input ID for all the forms
because getElementById would always return the first in document order,
changing the focus to that same element and automatically submit the
form due to focus out. That’s why in this form i append the invoice’s
slug to the input’s ID.
Finally, this is the first time i am using an HTMx-only solution and i
needed a way to return back just the HTML for the <td>, without <title>,
breadcrumbs, or <dialog>. In principle, the template would be the
“layout”, but then i would need to modify everything to check whether
the template file is empty, or something to that effect, so instead i
created a “standalone” template for these cases.
[0]: https://htmx.org/examples/click-to-edit/
2023-04-11 08:46:27 +00:00
|
|
|
companyRouter.PUT("/invoices/:slug/tags", HandleUpdateInvoiceTags)
|
|
|
|
companyRouter.GET("/invoices/:slug/tags/edit", ServeEditInvoiceTags)
|
2023-07-12 18:06:53 +00:00
|
|
|
companyRouter.GET("/invoices/:slug/download/:filename", ServeInvoiceAttachment)
|
2023-06-07 14:35:31 +00:00
|
|
|
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)
|
2023-04-24 00:00:38 +00:00
|
|
|
companyRouter.GET("/search/products", HandleProductSearch)
|
2023-05-03 10:46:25 +00:00
|
|
|
companyRouter.GET("/expenses", IndexExpenses)
|
Compute the total amount, base plus taxes, of all expenses
This works mostly like invoices: i have to “update” the expense form
to compute its total based on the subtotal and the selected taxes,
although in this case i do no need to compute the subtotal because that
is given by the user.
Nevertheless, i added a new function to compute that total because it
was already hairy enough for the dashboard, that also needs to compute
the tota, not just the base, and i wanted to test that function.
There is no need for a custom input type for that function as it only
needs a couple of simple domains. I have created the output type,
though, because otherwise i would need to have records or “reuse” any
other “amount” output type, which would be confusing.\
Part of #68.
2023-07-13 18:50:26 +00:00
|
|
|
companyRouter.POST("/expenses", HandleNewExpenseAction)
|
2023-05-03 10:46:25 +00:00
|
|
|
companyRouter.GET("/expenses/:slug", ServeExpenseForm)
|
Compute the total amount, base plus taxes, of all expenses
This works mostly like invoices: i have to “update” the expense form
to compute its total based on the subtotal and the selected taxes,
although in this case i do no need to compute the subtotal because that
is given by the user.
Nevertheless, i added a new function to compute that total because it
was already hairy enough for the dashboard, that also needs to compute
the tota, not just the base, and i wanted to test that function.
There is no need for a custom input type for that function as it only
needs a couple of simple domains. I have created the output type,
though, because otherwise i would need to have records or “reuse” any
other “amount” output type, which would be confusing.\
Part of #68.
2023-07-13 18:50:26 +00:00
|
|
|
companyRouter.POST("/expenses/:slug", HandleEditExpenseAction)
|
2023-05-05 08:59:35 +00:00
|
|
|
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)
|
2023-05-14 16:46:16 +00:00
|
|
|
companyRouter.GET("/expenses/:slug/download/:filename", ServeExpenseAttachment)
|
2023-05-16 12:56:49 +00:00
|
|
|
companyRouter.GET("/", ServeDashboard)
|
Add the company relation and read-only form to edit
I do not have more time to update the update to the company today, but i
believe this is already a good amount of work for a commit.
The company is going to be used for row level security, as users will
only have access to the data from companies they are granted access, by
virtue of being in the company_user relation.
I did not know how add a row level security policy to the company_user
because i needed the to select on the same relation and this is not
allowed, because it would create an infinite loop.
Had to add the vat, pg_libphonenumber, and uri extensions in order to
validate VAT identification numbers, phone numbers, and URIs,
repectively. These libraries are not in Debian, but i created packages
for them all in https://dev.tandem.ws/tandem.
2023-01-24 20:46:07 +00:00
|
|
|
|
2023-02-03 11:30:56 +00:00
|
|
|
router := httprouter.New()
|
|
|
|
router.ServeFiles("/static/*filepath", http.Dir("web/static"))
|
Prefill login form when using the demo database
This is to help up “sell” the service: people can look around the demo
to see whether it fits them. Of course, everyone should have the same
username in the demo.
We talked about having the username and password displayed above the
form in the template, but i think it makes more sense to give users as
little work as necessary. Plus, that means i do not have to write them
down while developing.
Whether the database is demo or not is not something that directly
depends on the environment, but rather on which database we are
connected to, thus an environment variable would not make much sense—it
has to be something of the database.
PostgreSQL has no PRAGMA application_id or PRAGMA user_version as with
SQLite to include application-specific values to the database. The
equivalent would be customized options[0], intended for modules
configuration, but that would require me to execute an ALTER DATABASE
in demo.sql with an specific datbase name, or force the use of psql to
run script the script, because then i can use the :DBNAME placeholder.
I guess that the most “standard” way is to just create a function that
returns a know value if the database is demo. Sqitch does not add that
function, therefore it is unlikely to be there by change unless it is
the demo database.
https://www.postgresql.org/docs/15/runtime-config-custom.html
2024-01-20 19:23:18 +00:00
|
|
|
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)
|
|
|
|
})
|
2023-02-03 11:30:56 +00:00
|
|
|
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)
|
|
|
|
|
2024-01-19 22:05:01 +00:00
|
|
|
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)
|
|
|
|
})
|
|
|
|
|
2023-02-03 11:30:56 +00:00
|
|
|
router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
Implement login cookie, its verification, and logout
At first i thought that i would need to implement sessions, the ones
that keep small files onto the disk, to know which user is talking to
the server, but then i realized that, for now at least, i only need a
very large number, plus the email address, to be used as a lookup, and
that can be stored in the user table, in a separate schema.
Had to change login to avoid raising exceptions when login failed
because i now keep a record of login attemps, and functions are always
run in a single transaction, thus the exception would prevent me to
insert into login_attempt. Even if i use a separate procedure, i could
not keep the records.
I did not want to add a parameter to the logout function because i was
afraid that it could be called from separate users. I do not know
whether it is possible with the current approach, since the settings
variable is also set by the same applications; time will tell.
2023-01-17 19:48:50 +00:00
|
|
|
user := getUser(r)
|
|
|
|
if user.LoggedIn {
|
Add the company relation and read-only form to edit
I do not have more time to update the update to the company today, but i
believe this is already a good amount of work for a commit.
The company is going to be used for row level security, as users will
only have access to the data from companies they are granted access, by
virtue of being in the company_user relation.
I did not know how add a row level security policy to the company_user
because i needed the to select on the same relation and this is not
allowed, because it would create an infinite loop.
Had to add the vat, pg_libphonenumber, and uri extensions in order to
validate VAT identification numbers, phone numbers, and URIs,
repectively. These libraries are not in Debian, but i created packages
for them all in https://dev.tandem.ws/tandem.
2023-01-24 20:46:07 +00:00
|
|
|
conn := getConn(r)
|
2023-02-04 09:43:42 +00:00
|
|
|
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)
|
Implement login cookie, its verification, and logout
At first i thought that i would need to implement sessions, the ones
that keep small files onto the disk, to know which user is talking to
the server, but then i realized that, for now at least, i only need a
very large number, plus the email address, to be used as a lookup, and
that can be stored in the user table, in a separate schema.
Had to change login to avoid raising exceptions when login failed
because i now keep a record of login attemps, and functions are always
run in a single transaction, thus the exception would prevent me to
insert into login_attempt. Even if i use a separate procedure, i could
not keep the records.
I did not want to add a parameter to the logout function because i was
afraid that it could be called from separate users. I do not know
whether it is possible with the current approach, since the settings
variable is also set by the same applications; time will tell.
2023-01-17 19:48:50 +00:00
|
|
|
} else {
|
2023-06-11 20:24:25 +00:00
|
|
|
mustRenderWebTemplate(w, r, "home.gohtml", nil)
|
2023-01-13 19:43:42 +00:00
|
|
|
}
|
|
|
|
})
|
2023-02-03 11:30:56 +00:00
|
|
|
|
2023-01-13 19:43:42 +00:00
|
|
|
var handler http.Handler = router
|
2023-02-03 11:30:56 +00:00
|
|
|
handler = MethodOverrider(handler)
|
|
|
|
handler = LocaleSetter(db, handler)
|
|
|
|
handler = LoginChecker(db, handler)
|
Implement login cookie, its verification, and logout
At first i thought that i would need to implement sessions, the ones
that keep small files onto the disk, to know which user is talking to
the server, but then i realized that, for now at least, i only need a
very large number, plus the email address, to be used as a lookup, and
that can be stored in the user table, in a separate schema.
Had to change login to avoid raising exceptions when login failed
because i now keep a record of login attemps, and functions are always
run in a single transaction, thus the exception would prevent me to
insert into login_attempt. Even if i use a separate procedure, i could
not keep the records.
I did not want to add a parameter to the logout function because i was
afraid that it could be called from separate users. I do not know
whether it is possible with the current approach, since the settings
variable is also set by the same applications; time will tell.
2023-01-17 19:48:50 +00:00
|
|
|
handler = Recoverer(handler)
|
2023-01-17 09:40:22 +00:00
|
|
|
handler = Logger(handler)
|
2023-01-13 19:43:42 +00:00
|
|
|
return handler
|
|
|
|
}
|
2023-02-03 11:30:56 +00:00
|
|
|
|
|
|
|
func MethodOverrider(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if r.Method == http.MethodPost {
|
2023-05-14 16:46:16 +00:00
|
|
|
contentType := r.Header.Get("Content-Type")
|
|
|
|
contentType, _, err := mime.ParseMediaType(contentType)
|
|
|
|
if err != nil {
|
2023-02-03 11:30:56 +00:00
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2023-05-14 16:46:16 +00:00
|
|
|
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)
|
2023-02-03 11:30:56 +00:00
|
|
|
if override == http.MethodDelete || override == http.MethodPut {
|
|
|
|
r2 := new(http.Request)
|
|
|
|
*r2 = *r
|
|
|
|
r2.Method = override
|
|
|
|
r = r2
|
|
|
|
}
|
|
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|