numerus/pkg/form.go

542 lines
13 KiB
Go
Raw Normal View History

package pkg
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"github.com/jackc/pgtype"
"html/template"
"io"
"net/http"
"net/mail"
"net/url"
"regexp"
"strconv"
"strings"
"time"
)
var tagsRegex = regexp.MustCompile("[^a-z0-9-]+")
type Attribute struct {
Key, Val string
}
type InputField struct {
Name string
Label string
Type string
Val string
Is string
Required bool
Attributes []template.HTMLAttr
Errors []error
}
func (field *InputField) Scan(value interface{}) error {
if value == nil {
field.Val = ""
return nil
}
switch v := value.(type) {
case time.Time:
if field.Type == "date" {
field.Val = v.Format("2006-01-02")
} else if field.Type == "time" {
field.Val = v.Format("15:04")
} else {
field.Val = v.Format(time.RFC3339)
}
default:
field.Val = fmt.Sprintf("%v", v)
}
return nil
}
func (field *InputField) Value() (driver.Value, error) {
return field.Val, nil
}
func (field *InputField) HasValue() bool {
return field.Val != ""
}
func (field *InputField) FillValue(r *http.Request) {
field.Val = strings.TrimSpace(r.FormValue(field.Name))
}
func (field *InputField) Integer() int {
value, err := strconv.Atoi(field.Val)
if err != nil {
panic(err)
}
return value
}
func (field *InputField) IntegerOrNil() interface{} {
if field.Val != "" {
if i := field.Integer(); i > 0 {
return i
}
}
return nil
}
func (field *InputField) Float64() float64 {
value, err := strconv.ParseFloat(field.Val, 64)
if err != nil {
panic(err)
}
return value
}
2023-03-13 13:55:10 +00:00
func (field *InputField) String() string {
return field.Val
}
type SelectOption struct {
Value string
Label string
Group string
}
type SelectField struct {
Name string
Label string
Selected []string
Options []*SelectOption
Attributes []template.HTMLAttr
Required bool
Multiple bool
EmptyLabel string
Errors []error
}
func (field *SelectField) Scan(value interface{}) error {
if value == nil {
field.Selected = append(field.Selected, "")
return nil
}
if str, ok := value.(string); ok {
if array, err := pgtype.ParseUntypedTextArray(str); err == nil {
for _, element := range array.Elements {
field.Selected = append(field.Selected, element)
}
return nil
}
}
field.Selected = append(field.Selected, fmt.Sprintf("%v", value))
return nil
}
func (field *SelectField) Value() (driver.Value, error) {
return field.String(), nil
}
func (field *SelectField) String() string {
if field.Selected == nil {
return ""
}
return field.Selected[0]
}
func (field *SelectField) OrNull() interface{} {
if field.String() == "" {
return sql.NullString{}
}
return field
}
func (field *SelectField) FillValue(r *http.Request) {
field.Selected = r.Form[field.Name]
}
func (field *SelectField) HasValidOptions() bool {
for _, selected := range field.Selected {
if !field.isValidOption(selected) {
return false
}
}
return true
}
func (field *SelectField) IsSelected(v string) bool {
for _, selected := range field.Selected {
if selected == v {
return true
}
}
return false
}
func (field *SelectField) FindOption(value string) *SelectOption {
for _, option := range field.Options {
if option.Value == value {
return option
}
}
return nil
}
func (field *SelectField) isValidOption(selected string) bool {
return field.FindOption(selected) != nil
}
func (field *SelectField) Clear() {
field.Selected = []string{}
}
func (field *SelectField) HasValue() bool {
return len(field.Selected) > 0 && field.Selected[0] != ""
}
func MustGetOptions(ctx context.Context, conn *Conn, sql string, args ...interface{}) []*SelectOption {
rows, err := conn.Query(ctx, sql, args...)
if err != nil {
panic(err)
}
defer rows.Close()
var options []*SelectOption
for rows.Next() {
option := &SelectOption{}
err = rows.Scan(&option.Value, &option.Label)
if err != nil {
panic(err)
}
options = append(options, option)
}
if rows.Err() != nil {
panic(rows.Err())
}
return options
}
func MustGetGroupedOptions(ctx context.Context, conn *Conn, sql string, args ...interface{}) []*SelectOption {
rows, err := conn.Query(ctx, sql, args...)
if err != nil {
panic(err)
}
defer rows.Close()
var options []*SelectOption
for rows.Next() {
option := &SelectOption{}
err = rows.Scan(&option.Value, &option.Label, &option.Group)
if err != nil {
panic(err)
}
options = append(options, option)
}
if rows.Err() != nil {
panic(rows.Err())
}
return options
}
func mustGetCountryOptions(ctx context.Context, conn *Conn, locale *Locale) []*SelectOption {
return MustGetOptions(ctx, conn, "select country.country_code, coalesce(i18n.name, country.name) as l10n_name from country left join country_i18n as i18n on country.country_code = i18n.country_code and i18n.lang_tag = $1 order by l10n_name", locale.Language)
}
type RadioOption struct {
Value string
Label string
}
type RadioField struct {
Name string
Label string
Selected string
Options []*RadioOption
Attributes []template.HTMLAttr
Required bool
Errors []error
}
func (field *RadioField) Scan(value interface{}) error {
if value == nil {
field.Selected = ""
return nil
}
field.Selected = fmt.Sprintf("%v", value)
return nil
}
func (field *RadioField) Value() (driver.Value, error) {
return field.Selected, nil
}
func (field *RadioField) String() string {
return field.Selected
}
func (field *RadioField) FillValue(r *http.Request) {
field.Selected = strings.TrimSpace(r.FormValue(field.Name))
}
func (field *RadioField) IsSelected(v string) bool {
return field.Selected == v
}
func (field *RadioField) FindOption(value string) *RadioOption {
for _, option := range field.Options {
if option.Value == value {
return option
}
}
return nil
}
func (field *RadioField) isValidOption(selected string) bool {
return field.FindOption(selected) != nil
}
Split contact relation into tax_details, phone, web, and email We need to have contacts with just a name: we need to assign freelancer’s quote as expense linked the government, but of course we do not have a phone or email for that “contact”, much less a VATIN or other tax details. It is also interesting for other expenses-only contacts to not have to input all tax details, as we may not need to invoice then, thus are useless for us, but sometimes it might be interesting to have them, “just in case”. Of course, i did not want to make nullable any of the tax details required to generate an invoice, otherwise we could allow illegal invoices. Therefore, that data had to go in a different relation, and invoice’s foreign key update to point to that relation, not just customer, or we would again be able to create invalid invoices. We replaced the contact’s trade name with just name, because we do not need _three_ names for a contact, but we _do_ need two: the one we use to refer to them and the business name for tax purposes. The new contact_phone, contact_web, and contact_email relations could be simply a nullable field, but i did not see the point, since there are not that many instances where i need any of this data. Now company.taxDetailsForm is no longer “the same as contactForm with some extra fields”, because i have to add a check whether the user needs to invoice the contact, to check that the required values are there. I have an additional problem with the contact form when not using JavaScript: i must set the required field to all tax details fields to avoid the “(optional)” suffix, and because they _are_ required when that checkbox is enabled, but i can not set them optional when the check is unchecked. My solution for now is to ignore the form validation, and later i will add some JavaScript that adds the validation again, so it will work in all cases.
2023-06-30 19:32:48 +00:00
type CheckField struct {
Name string
Label string
Checked bool
Attributes []template.HTMLAttr
Required bool
Errors []error
}
func (field *CheckField) FillValue(r *http.Request) {
field.Checked = len(r.Form[field.Name]) > 0
}
func (field *CheckField) Scan(value interface{}) error {
if value == nil {
field.Checked = false
return nil
}
switch v := value.(type) {
case bool:
field.Checked = v
default:
field.Checked, _ = strconv.ParseBool(fmt.Sprintf("%v", v))
}
return nil
}
func (field *CheckField) Value() (driver.Value, error) {
return field.Checked, nil
}
type FileField struct {
Name string
Label string
MaxSize int64
OriginalFileName string
ContentType string
Content []byte
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
Required bool
Errors []error
}
func (field *FileField) FillValue(r *http.Request) error {
file, header, err := r.FormFile(field.Name)
if err != nil {
if err == http.ErrMissingFile {
return nil
}
return err
}
defer file.Close()
field.Content, err = io.ReadAll(file)
if err != nil {
return err
}
field.OriginalFileName = header.Filename
field.ContentType = header.Header.Get("Content-Type")
if len(field.Content) == 0 {
field.ContentType = http.DetectContentType(field.Content)
}
return nil
}
type TagsField struct {
Name string
Label string
Tags []string
Attributes []template.HTMLAttr
Required bool
Errors []error
}
func (field *TagsField) Value() (driver.Value, error) {
if field.Tags == nil {
return []string{}, nil
}
return field.Tags, nil
}
func (field *TagsField) HasValue() bool {
return len(field.Tags) > 0 && field.Tags[0] != ""
}
func (field *TagsField) Scan(value interface{}) error {
if value == nil {
return nil
}
if str, ok := value.(string); ok {
if array, err := pgtype.ParseUntypedTextArray(str); err == nil {
for _, element := range array.Elements {
field.Tags = append(field.Tags, element)
}
return nil
}
}
field.Tags = append(field.Tags, fmt.Sprintf("%v", value))
return nil
}
func (field *TagsField) FillValue(r *http.Request) {
field.Tags = strings.Split(tagsRegex.ReplaceAllString(r.FormValue(field.Name), ","), ",")
if len(field.Tags) == 1 && len(field.Tags[0]) == 0 {
field.Tags = []string{}
}
}
func (field *TagsField) String() string {
return strings.Join(field.Tags, ",")
}
type ToggleField struct {
Name string
Label string
Selected string
FirstOption *ToggleOption
SecondOption *ToggleOption
Attributes []template.HTMLAttr
Errors []error
}
type ToggleOption struct {
Value string
Label string
Description string
}
func (field *ToggleField) FillValue(r *http.Request) {
field.Selected = strings.TrimSpace(r.FormValue(field.Name))
if field.Selected != field.FirstOption.Value && field.Selected != field.SecondOption.Value {
field.Selected = field.FirstOption.Value
}
}
Add option to export the list of quotes, invoices, and expenses to ODS This was requested by a potential user, as they want to be able to do whatever they want to do to these lists with a spreadsheet. In fact, they requested to be able to export to CSV, but, as always, using CSV is a minefield because of Microsoft: since their Excel product is fucking unable to write and read CSV from different locales, even if using the same exact Excel product, i can not also create a CSV file that is guaranteed to work on all locales. If i used the non-standard sep=; thing to tell Excel that it is a fucking stupid application, then proper applications would show that line as a row, which is the correct albeit undesirable behaviour. The solution is to use a spreadsheet file format that does not have this issue. As far as I know, by default Excel is able to read XLSX and ODS files, but i refuse to use the artificially complex, not the actually used in Excel, and lobbied standard that Microsoft somehow convinced ISO to publish, as i am using a different format because of the mess they made, and i do not want to bend over in front of them, so ODS it is. ODS is neither an elegant or good format by any means, but at least i can write them using simple strings, because there is no ODS library in Debian and i am not going to write yet another DEB package for an overengineered package to write a simple table—all i want is to say “here are these n columns, and these m columns; have a good day!”. Part of #51.
2023-07-18 11:29:36 +00:00
func (field *ToggleField) String() string {
return field.Selected
}
type FormValidator struct {
Valid bool
}
func newFormValidator() *FormValidator {
return &FormValidator{true}
}
func (v *FormValidator) AllOK() bool {
return v.Valid
}
func (v *FormValidator) CheckRequiredInput(field *InputField, message string) bool {
return v.checkInput(field, field.Val != "", message)
}
func (v *FormValidator) CheckInputMinLength(field *InputField, min int, message string) bool {
return v.checkInput(field, len(field.Val) >= min, message)
}
func (v *FormValidator) CheckValidEmailInput(field *InputField, message string) bool {
_, err := mail.ParseAddress(field.Val)
return v.checkInput(field, err == nil, message)
}
func (v *FormValidator) CheckValidVATINInput(ctx context.Context, conn *Conn, field *InputField, country string, message string) bool {
return v.checkInput(field, conn.MustGetBool(ctx, "select input_is_valid($1 || $2, 'vatin')", country, field.Val), message)
}
func (v *FormValidator) CheckValidPhoneInput(ctx context.Context, conn *Conn, field *InputField, country string, message string) bool {
return v.checkInput(field, conn.MustGetBool(ctx, "select input_is_valid_phone($1, $2)", field.Val, country), message)
}
func (v *FormValidator) CheckValidIBANInput(ctx context.Context, conn *Conn, field *InputField, message string) bool {
return v.checkInput(field, conn.MustGetBool(ctx, "select input_is_valid($1, 'iban')", field.Val), message)
}
func (v *FormValidator) CheckValidBICInput(ctx context.Context, conn *Conn, field *InputField, message string) bool {
return v.checkInput(field, conn.MustGetBool(ctx, "select input_is_valid($1, 'bic')", field.Val), message)
}
func (v *FormValidator) CheckPasswordConfirmation(password *InputField, confirm *InputField, message string) bool {
return v.checkInput(confirm, password.Val == confirm.Val, message)
}
func (v *FormValidator) CheckValidSelectOption(field *SelectField, message string) bool {
return v.checkSelect(field, field.HasValidOptions(), message)
}
func (v *FormValidator) CheckAtMostOneOfEachGroup(field *SelectField, message string) bool {
repeated := false
groups := map[string]bool{}
for _, selected := range field.Selected {
option := field.FindOption(selected)
if exists := groups[option.Group]; exists {
repeated = true
break
}
groups[option.Group] = true
}
return v.checkSelect(field, !repeated, message)
}
func (v *FormValidator) CheckValidURL(field *InputField, message string) bool {
_, err := url.ParseRequestURI(field.Val)
return v.checkInput(field, err == nil, message)
}
func (v *FormValidator) CheckValidDate(field *InputField, message string) bool {
_, err := time.Parse("2006-01-02", field.Val)
return v.checkInput(field, err == nil, message)
}
func (v *FormValidator) CheckValidPostalCode(ctx context.Context, conn *Conn, field *InputField, country string, message string) bool {
pattern := "^" + conn.MustGetText(ctx, ".{1,255}", "select postal_code_regex from country where country_code = $1", country) + "$"
match, err := regexp.MatchString(pattern, field.Val)
if err != nil {
panic(err)
}
return v.checkInput(field, match, message)
}
func (v *FormValidator) CheckValidInteger(field *InputField, min int, max int, message string) bool {
value, err := strconv.Atoi(field.Val)
return v.checkInput(field, err == nil && value >= min && value <= max, message)
}
func (v *FormValidator) CheckValidDecimal(field *InputField, min float64, max float64, message string) bool {
value, err := strconv.ParseFloat(field.Val, 64)
return v.checkInput(field, err == nil && value >= min && value <= max, message)
}
func (v *FormValidator) checkInput(field *InputField, ok bool, message string) bool {
if !ok {
field.Errors = append(field.Errors, errors.New(message))
v.Valid = false
}
return ok
}
func (v *FormValidator) checkSelect(field *SelectField, ok bool, message string) bool {
if !ok {
field.Errors = append(field.Errors, errors.New(message))
v.Valid = false
}
return ok
}