2023-01-31 14:40:12 +00:00
package pkg
import (
"context"
Allow empty contact and payment method for quotes
I have to use a value to be used as “none” for payment method and
contact. In PL/pgSQL add_quote and edit_quote functions, that value is
NULL, while in forms it is the empty string. I can not simply pass the
empty string for either of these fields because PL/pgSQL expects
(nullable) integers, and "" is not a valid integer and is not NULL
either. A conversion is necessary.
Apparently, Go’s nil is not a valid representation for SQL’s NULL with
pgx, and had to use sql.NullString instead.
I also needed to coalesce contact’s VATIN and phone, because null values
can not be scanned to *string. I did not do that before because
`coalesce(vatin, '')` throws an error that '' is not a valid VATIN and
just left as is, wrongly expecting that pgx would do the job of leaving
the string blank for me. It does not.
Lastly, i can not blindly write Quotee’s tax details in the quote’s view
page, or we would see the (), characters for the empty address info.
2023-06-08 11:05:41 +00:00
"database/sql"
2023-02-01 13:15:02 +00:00
"database/sql/driver"
2023-02-01 10:30:30 +00:00
"errors"
2023-02-01 13:15:02 +00:00
"fmt"
2023-02-12 20:06:48 +00:00
"github.com/jackc/pgtype"
2023-02-01 13:15:02 +00:00
"html/template"
2023-07-02 18:04:45 +00:00
"io"
2023-02-01 10:02:32 +00:00
"net/http"
2023-01-31 14:40:12 +00:00
"net/mail"
2023-02-01 13:15:02 +00:00
"net/url"
"regexp"
"strconv"
2023-02-01 10:02:32 +00:00
"strings"
2023-02-12 20:06:48 +00:00
"time"
2023-01-31 14:40:12 +00:00
)
Add tags for contacts too
With Oriol we agreed that contacts should have tags, too, and that the
“tag pool”, as it were, should be shared with the one for invoices (and
all future tags we might add).
I added the contact_tag relation and tag_contact function, just like
with invoices, and then realized that the SQL queries that Go had to
execute were becoming “complex” enough: i had to get not only the slug,
but the contact id to call tag_contact, and all inside a transaction.
Therefore, i opted to create the add_contact and edit_contact functions,
that mirror those for invoice and products, so now each “major” section
has these functions. They also simplified a bit the handling of the
VATIN and phone numbers, because it is now encapsuled inside the
PL/pgSQL function and Go does not know how to assemble the parts.
2023-03-26 00:32:53 +00:00
var tagsRegex = regexp . MustCompile ( "[^a-z0-9-]+" )
2023-02-01 10:02:32 +00:00
type Attribute struct {
Key , Val string
}
2023-01-31 14:40:12 +00:00
type InputField struct {
2023-02-01 10:02:32 +00:00
Name string
Label string
Type string
2023-02-01 13:15:02 +00:00
Val string
2023-04-24 00:00:38 +00:00
Is string
2023-02-01 10:02:32 +00:00
Required bool
2023-02-01 13:15:02 +00:00
Attributes [ ] template . HTMLAttr
2023-02-01 10:02:32 +00:00
Errors [ ] error
}
2023-02-01 13:15:02 +00:00
func ( field * InputField ) Scan ( value interface { } ) error {
if value == nil {
field . Val = ""
return nil
}
2023-03-13 13:54:28 +00:00
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 )
}
2023-02-01 13:15:02 +00:00
return nil
}
func ( field * InputField ) Value ( ) ( driver . Value , error ) {
return field . Val , nil
}
2023-07-16 18:56:11 +00:00
func ( field * InputField ) HasValue ( ) bool {
return field . Val != ""
}
2023-02-01 10:02:32 +00:00
func ( field * InputField ) FillValue ( r * http . Request ) {
2023-02-01 13:15:02 +00:00
field . Val = strings . TrimSpace ( r . FormValue ( field . Name ) )
}
func ( field * InputField ) Integer ( ) int {
2023-02-20 10:42:21 +00:00
value , err := strconv . Atoi ( field . Val )
if err != nil {
panic ( err )
}
return value
}
2023-05-22 09:06:06 +00:00
func ( field * InputField ) IntegerOrNil ( ) interface { } {
if field . Val != "" {
if i := field . Integer ( ) ; i > 0 {
return i
}
}
return nil
}
2023-02-20 10:42:21 +00:00
func ( field * InputField ) Float64 ( ) float64 {
value , err := strconv . ParseFloat ( field . Val , 64 )
if err != nil {
panic ( err )
}
2023-02-01 13:15:02 +00:00
return value
2023-01-31 14:40:12 +00:00
}
2023-03-13 13:55:10 +00:00
func ( field * InputField ) String ( ) string {
return field . Val
}
2023-01-31 14:40:12 +00:00
type SelectOption struct {
Value string
Label string
2023-03-01 10:40:23 +00:00
Group string
2023-01-31 14:40:12 +00:00
}
type SelectField struct {
2023-02-01 13:15:02 +00:00
Name string
Label string
2023-02-08 12:47:36 +00:00
Selected [ ] string
2023-02-01 13:15:02 +00:00
Options [ ] * SelectOption
Attributes [ ] template . HTMLAttr
2023-02-05 13:06:33 +00:00
Required bool
2023-02-08 12:47:36 +00:00
Multiple bool
2023-02-05 13:06:33 +00:00
EmptyLabel string
2023-02-01 13:15:02 +00:00
Errors [ ] error
}
func ( field * SelectField ) Scan ( value interface { } ) error {
if value == nil {
2023-02-08 12:47:36 +00:00
field . Selected = append ( field . Selected , "" )
2023-02-01 13:15:02 +00:00
return nil
}
2023-02-12 20:06:48 +00:00
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
}
}
2023-02-08 12:47:36 +00:00
field . Selected = append ( field . Selected , fmt . Sprintf ( "%v" , value ) )
2023-02-01 13:15:02 +00:00
return nil
}
func ( field * SelectField ) Value ( ) ( driver . Value , error ) {
Add filters form for invoices
Instead of using links in the invoice tags, that we will replace with a
“click-to-edit field”, with Oriol agreed to add a form with filters that
includes not only the tags but also dates, customer, status, and the
invoice number.
This means i now need dynamic SQL, and i do not think this belongs to
the database (i.e., no PL/pgSQL function for that). I have looked at
query builder libraries for Golang, and did not find anything that
suited me: either they wanted to manage not only the SQL query but also
all structs, or they managed to confuse Goland’s SQL analyzer.
For now, at least, i am using a very simple approach with arrays, that
still confuses Goland’s analyzer, but just in a very specific part,
which i find tolerable—not that their analyzer is that great to begin
with, but that’s a story for another day.
2023-03-29 14:16:31 +00:00
return field . String ( ) , nil
}
func ( field * SelectField ) String ( ) string {
2023-02-08 12:47:36 +00:00
if field . Selected == nil {
Add filters form for invoices
Instead of using links in the invoice tags, that we will replace with a
“click-to-edit field”, with Oriol agreed to add a form with filters that
includes not only the tags but also dates, customer, status, and the
invoice number.
This means i now need dynamic SQL, and i do not think this belongs to
the database (i.e., no PL/pgSQL function for that). I have looked at
query builder libraries for Golang, and did not find anything that
suited me: either they wanted to manage not only the SQL query but also
all structs, or they managed to confuse Goland’s SQL analyzer.
For now, at least, i am using a very simple approach with arrays, that
still confuses Goland’s analyzer, but just in a very specific part,
which i find tolerable—not that their analyzer is that great to begin
with, but that’s a story for another day.
2023-03-29 14:16:31 +00:00
return ""
2023-02-08 12:47:36 +00:00
}
Add filters form for invoices
Instead of using links in the invoice tags, that we will replace with a
“click-to-edit field”, with Oriol agreed to add a form with filters that
includes not only the tags but also dates, customer, status, and the
invoice number.
This means i now need dynamic SQL, and i do not think this belongs to
the database (i.e., no PL/pgSQL function for that). I have looked at
query builder libraries for Golang, and did not find anything that
suited me: either they wanted to manage not only the SQL query but also
all structs, or they managed to confuse Goland’s SQL analyzer.
For now, at least, i am using a very simple approach with arrays, that
still confuses Goland’s analyzer, but just in a very specific part,
which i find tolerable—not that their analyzer is that great to begin
with, but that’s a story for another day.
2023-03-29 14:16:31 +00:00
return field . Selected [ 0 ]
2023-01-31 14:40:12 +00:00
}
Allow empty contact and payment method for quotes
I have to use a value to be used as “none” for payment method and
contact. In PL/pgSQL add_quote and edit_quote functions, that value is
NULL, while in forms it is the empty string. I can not simply pass the
empty string for either of these fields because PL/pgSQL expects
(nullable) integers, and "" is not a valid integer and is not NULL
either. A conversion is necessary.
Apparently, Go’s nil is not a valid representation for SQL’s NULL with
pgx, and had to use sql.NullString instead.
I also needed to coalesce contact’s VATIN and phone, because null values
can not be scanned to *string. I did not do that before because
`coalesce(vatin, '')` throws an error that '' is not a valid VATIN and
just left as is, wrongly expecting that pgx would do the job of leaving
the string blank for me. It does not.
Lastly, i can not blindly write Quotee’s tax details in the quote’s view
page, or we would see the (), characters for the empty address info.
2023-06-08 11:05:41 +00:00
func ( field * SelectField ) OrNull ( ) interface { } {
if field . String ( ) == "" {
return sql . NullString { }
}
return field
}
2023-02-01 10:02:32 +00:00
func ( field * SelectField ) FillValue ( r * http . Request ) {
2023-02-08 12:47:36 +00:00
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
2023-02-01 10:02:32 +00:00
}
2023-03-01 10:55:26 +00:00
func ( field * SelectField ) FindOption ( value string ) * SelectOption {
2023-01-31 14:40:12 +00:00
for _ , option := range field . Options {
2023-03-01 10:55:26 +00:00
if option . Value == value {
return option
2023-01-31 14:40:12 +00:00
}
}
2023-03-01 10:55:26 +00:00
return nil
}
func ( field * SelectField ) isValidOption ( selected string ) bool {
return field . FindOption ( selected ) != nil
2023-01-31 14:40:12 +00:00
}
2023-03-08 10:26:02 +00:00
func ( field * SelectField ) Clear ( ) {
field . Selected = [ ] string { }
}
2023-07-16 18:56:11 +00:00
func ( field * SelectField ) HasValue ( ) bool {
return len ( field . Selected ) > 0 && field . Selected [ 0 ] != ""
}
2023-01-31 14:40:12 +00:00
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
}
2023-02-01 10:30:30 +00:00
2023-03-01 10:40:23 +00:00
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
}
2023-02-01 13:15:02 +00:00
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 )
}
2023-05-17 10:05:30 +00:00
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
}
2023-05-14 16:46:16 +00:00
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
2023-05-14 16:46:16 +00:00
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 ( )
2023-07-02 18:04:45 +00:00
field . Content , err = io . ReadAll ( file )
2023-05-14 16:46:16 +00:00
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
}
Add tags for contacts too
With Oriol we agreed that contacts should have tags, too, and that the
“tag pool”, as it were, should be shared with the one for invoices (and
all future tags we might add).
I added the contact_tag relation and tag_contact function, just like
with invoices, and then realized that the SQL queries that Go had to
execute were becoming “complex” enough: i had to get not only the slug,
but the contact id to call tag_contact, and all inside a transaction.
Therefore, i opted to create the add_contact and edit_contact functions,
that mirror those for invoice and products, so now each “major” section
has these functions. They also simplified a bit the handling of the
VATIN and phone numbers, because it is now encapsuled inside the
PL/pgSQL function and Go does not know how to assemble the parts.
2023-03-26 00:32:53 +00:00
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
}
2023-07-16 18:56:11 +00:00
func ( field * TagsField ) HasValue ( ) bool {
return len ( field . Tags ) > 0 && field . Tags [ 0 ] != ""
}
Add tags for contacts too
With Oriol we agreed that contacts should have tags, too, and that the
“tag pool”, as it were, should be shared with the one for invoices (and
all future tags we might add).
I added the contact_tag relation and tag_contact function, just like
with invoices, and then realized that the SQL queries that Go had to
execute were becoming “complex” enough: i had to get not only the slug,
but the contact id to call tag_contact, and all inside a transaction.
Therefore, i opted to create the add_contact and edit_contact functions,
that mirror those for invoice and products, so now each “major” section
has these functions. They also simplified a bit the handling of the
VATIN and phone numbers, because it is now encapsuled inside the
PL/pgSQL function and Go does not know how to assemble the parts.
2023-03-26 00:32:53 +00:00
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 , "," )
}
2023-04-15 02:05:59 +00:00
type ToggleField struct {
Name string
Label string
Selected string
2023-04-16 17:01:11 +00:00
FirstOption * ToggleOption
SecondOption * ToggleOption
2023-04-15 02:05:59 +00:00
Attributes [ ] template . HTMLAttr
Errors [ ] error
}
2023-04-16 17:01:11 +00:00
type ToggleOption struct {
Value string
Label string
Description string
}
2023-04-15 02:05:59 +00:00
func ( field * ToggleField ) FillValue ( r * http . Request ) {
field . Selected = strings . TrimSpace ( r . FormValue ( field . Name ) )
2023-04-15 18:45:19 +00:00
if field . Selected != field . FirstOption . Value && field . Selected != field . SecondOption . Value {
field . Selected = field . FirstOption . Value
}
2023-04-15 02:05:59 +00:00
}
2023-02-01 10:30:30 +00:00
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 {
2023-02-01 13:15:02 +00:00
return v . checkInput ( field , field . Val != "" , message )
2023-02-01 10:30:30 +00:00
}
2023-04-18 19:01:29 +00:00
func ( v * FormValidator ) CheckInputMinLength ( field * InputField , min int , message string ) bool {
return v . checkInput ( field , len ( field . Val ) >= min , message )
}
2023-02-01 10:30:30 +00:00
func ( v * FormValidator ) CheckValidEmailInput ( field * InputField , message string ) bool {
2023-02-01 13:15:02 +00:00
_ , err := mail . ParseAddress ( field . Val )
2023-02-01 10:30:30 +00:00
return v . checkInput ( field , err == nil , message )
}
Create validation function for SQL domains and for phones
When i wrote the functions to import contact, i already created a couple
of “temporary” functions to validate whether the input given from the
Excel files was correct according to the various domains used in the
relations, so i can know whether i can import that data.
I realized that i could do exactly the same when validating forms: check
that the value conforms to the domain, in the exact same way, so i can
make sure that the value will be accepted without duplicating the logic,
at the expense of a call to the database.
In an ideal world, i would use pg_input_is_valid, but this function is
only available in PostgreSQL 16 and Debian 12 uses PostgreSQL 15.
These functions are in the public schema because initially i wanted to
use them to also validate email, which is needed in the login form, but
then i recanted and kept the same email validation in Go, because
something felt off about using the database for that particular form,
but i do not know why.
2023-07-03 09:31:59 +00:00
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 )
2023-02-01 13:15:02 +00:00
}
Create validation function for SQL domains and for phones
When i wrote the functions to import contact, i already created a couple
of “temporary” functions to validate whether the input given from the
Excel files was correct according to the various domains used in the
relations, so i can know whether i can import that data.
I realized that i could do exactly the same when validating forms: check
that the value conforms to the domain, in the exact same way, so i can
make sure that the value will be accepted without duplicating the logic,
at the expense of a call to the database.
In an ideal world, i would use pg_input_is_valid, but this function is
only available in PostgreSQL 16 and Debian 12 uses PostgreSQL 15.
These functions are in the public schema because initially i wanted to
use them to also validate email, which is needed in the login form, but
then i recanted and kept the same email validation in Go, because
something felt off about using the database for that particular form,
but i do not know why.
2023-07-03 09:31:59 +00:00
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 )
2023-02-01 13:15:02 +00:00
}
Create validation function for SQL domains and for phones
When i wrote the functions to import contact, i already created a couple
of “temporary” functions to validate whether the input given from the
Excel files was correct according to the various domains used in the
relations, so i can know whether i can import that data.
I realized that i could do exactly the same when validating forms: check
that the value conforms to the domain, in the exact same way, so i can
make sure that the value will be accepted without duplicating the logic,
at the expense of a call to the database.
In an ideal world, i would use pg_input_is_valid, but this function is
only available in PostgreSQL 16 and Debian 12 uses PostgreSQL 15.
These functions are in the public schema because initially i wanted to
use them to also validate email, which is needed in the login form, but
then i recanted and kept the same email validation in Go, because
something felt off about using the database for that particular form,
but i do not know why.
2023-07-03 09:31:59 +00:00
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 )
Add IBAN and BIC fields to contacts
These two fields are just for information purposes, as Numerus does not
have any way to wire transfer using these, but people might want to keep
these in the contact’s info as a convenience.
Since not every contact should have an IBAN, e.g., customers, and inside
SEPA (European Union and some more countries) the BIC is not required,
they are in two different relations in order to be optional without
using NULL.
For the IBAN i found an already made PostgreSQL module, but for BIC i
had to write a regular expression based on the information i gathered
from Wikipedia, because the ISO standard is not free.
These two parameters for the add_contact and edit_contact functions are
TEXT because i realized that these functions are intended to be used
from the web application, that only deals with texts, so the
ValueOrNil() function was unnecessarily complex and PostreSQL’s
functions were better suited to “convert” from TEXT to IBAN or BIC.
The same is true for EMAIL and URI domains, so i changed their parameter
types to TEXT too.
Closes #54.
2023-07-02 00:08:45 +00:00
}
Create validation function for SQL domains and for phones
When i wrote the functions to import contact, i already created a couple
of “temporary” functions to validate whether the input given from the
Excel files was correct according to the various domains used in the
relations, so i can know whether i can import that data.
I realized that i could do exactly the same when validating forms: check
that the value conforms to the domain, in the exact same way, so i can
make sure that the value will be accepted without duplicating the logic,
at the expense of a call to the database.
In an ideal world, i would use pg_input_is_valid, but this function is
only available in PostgreSQL 16 and Debian 12 uses PostgreSQL 15.
These functions are in the public schema because initially i wanted to
use them to also validate email, which is needed in the login form, but
then i recanted and kept the same email validation in Go, because
something felt off about using the database for that particular form,
but i do not know why.
2023-07-03 09:31:59 +00:00
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 )
Add IBAN and BIC fields to contacts
These two fields are just for information purposes, as Numerus does not
have any way to wire transfer using these, but people might want to keep
these in the contact’s info as a convenience.
Since not every contact should have an IBAN, e.g., customers, and inside
SEPA (European Union and some more countries) the BIC is not required,
they are in two different relations in order to be optional without
using NULL.
For the IBAN i found an already made PostgreSQL module, but for BIC i
had to write a regular expression based on the information i gathered
from Wikipedia, because the ISO standard is not free.
These two parameters for the add_contact and edit_contact functions are
TEXT because i realized that these functions are intended to be used
from the web application, that only deals with texts, so the
ValueOrNil() function was unnecessarily complex and PostreSQL’s
functions were better suited to “convert” from TEXT to IBAN or BIC.
The same is true for EMAIL and URI domains, so i changed their parameter
types to TEXT too.
Closes #54.
2023-07-02 00:08:45 +00:00
}
2023-02-01 10:30:30 +00:00
func ( v * FormValidator ) CheckPasswordConfirmation ( password * InputField , confirm * InputField , message string ) bool {
2023-02-01 13:15:02 +00:00
return v . checkInput ( confirm , password . Val == confirm . Val , message )
2023-02-01 10:30:30 +00:00
}
func ( v * FormValidator ) CheckValidSelectOption ( field * SelectField , message string ) bool {
2023-02-08 12:47:36 +00:00
return v . checkSelect ( field , field . HasValidOptions ( ) , message )
2023-02-01 10:30:30 +00:00
}
2023-03-01 10:55:26 +00:00
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 )
}
2023-02-12 20:01:20 +00:00
func ( v * FormValidator ) CheckValidURL ( field * InputField , message string ) bool {
2023-02-01 13:15:02 +00:00
_ , err := url . ParseRequestURI ( field . Val )
return v . checkInput ( field , err == nil , message )
}
2023-02-12 20:06:48 +00:00
func ( v * FormValidator ) CheckValidDate ( field * InputField , message string ) bool {
2023-02-13 09:34:55 +00:00
_ , err := time . Parse ( "2006-01-02" , field . Val )
2023-02-12 20:06:48 +00:00
return v . checkInput ( field , err == nil , message )
}
2023-02-01 13:15:02 +00:00
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 )
}
Convert from cents to “price” and back
I do not want to use floats in the Go lang application, because it is
not supposed to do anything with these values other than to print and
retrieve them from the user; all computations will be performed by
PostgreSQL in cents.
That means i have to “convert” from the price format that users expect
to see (e.g., 1.234,56) to cents (e.g., 123456) and back when passing
data between Go and PostgreSQL, and that conversion depends on the
currency’s decimal places.
At first i did everything in Go, but saw that i would need to do it in
a loop when retrieving the list of products, and immediately knew it was
a mistake—i needed a PL/pgSQL function for that.
I still need to convert from string to float, however, when printing the
value to the user. Because the string representation is in C, but i
need to format it according to the locale with golang/x/text. That
package has the information of how to correctly format numbers, but it
is in an internal package that i can not use, and numbers.Digit only
accepts numeric types, not a string.
2023-02-05 12:55:12 +00:00
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 )
}
2023-02-01 10:30:30 +00:00
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
}