numerus/pkg/contacts.go

587 lines
16 KiB
Go

package pkg
import (
"context"
"fmt"
"github.com/julienschmidt/httprouter"
"github.com/tealeg/xlsx"
"html/template"
"net/http"
"strings"
)
type ContactEntry struct {
Slug string
Name string
Email string
Phone string
Tags []string
}
type ContactsIndexPage struct {
Contacts []*ContactEntry
Filters *contactFilterForm
}
func IndexContacts(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
conn := getConn(r)
company := mustGetCompany(r)
locale := getLocale(r)
filters := newContactFilterForm(locale)
if err := filters.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
page := &ContactsIndexPage{
Contacts: mustCollectContactEntries(r.Context(), conn, company, filters),
Filters: filters,
}
mustRenderMainTemplate(w, r, "contacts/index.gohtml", page)
}
func GetContactForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
locale := getLocale(r)
conn := getConn(r)
slug := params[0].Value
if slug == "import" {
ServeImportPage(w, r, params)
return
}
form := newContactForm(r.Context(), conn, locale)
if slug == "new" {
w.WriteHeader(http.StatusOK)
mustRenderNewContactForm(w, r, form)
return
}
if !ValidUuid(slug) {
http.NotFound(w, r)
return
}
if !form.MustFillFromDatabase(r.Context(), conn, slug) {
http.NotFound(w, r)
return
}
w.WriteHeader(http.StatusOK)
mustRenderEditContactForm(w, r, slug, form)
}
func mustRenderNewContactForm(w http.ResponseWriter, r *http.Request, form *contactForm) {
mustRenderMainTemplate(w, r, "contacts/new.gohtml", form)
}
type editContactPage struct {
Slug string
ContactName string
Form *contactForm
}
func mustRenderEditContactForm(w http.ResponseWriter, r *http.Request, slug string, form *contactForm) {
page := &editContactPage{
Slug: slug,
ContactName: form.Name.String(),
Form: form,
}
mustRenderMainTemplate(w, r, "contacts/edit.gohtml", page)
}
func HandleAddContact(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
form := newContactForm(r.Context(), conn, locale)
if err := form.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := verifyCsrfTokenValid(r); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
if !form.Validate(r.Context(), conn) {
w.WriteHeader(http.StatusUnprocessableEntity)
mustRenderNewContactForm(w, r, form)
return
}
company := mustGetCompany(r)
conn.MustExec(r.Context(), "select add_contact($1, $2, $3, $4, $5, $6, $7, $8, $9)", company.Id, form.Name, form.Phone, form.Email, form.Web, form.TaxDetails(), form.IBAN, form.BIC, form.Tags)
htmxRedirect(w, r, companyURI(company, "/contacts"))
}
func HandleUpdateContact(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
form := newContactForm(r.Context(), conn, locale)
if err := form.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := verifyCsrfTokenValid(r); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
if !form.Validate(r.Context(), conn) {
mustRenderEditContactForm(w, r, params[0].Value, form)
return
}
slug := params[0].Value
if !ValidUuid(slug) {
http.NotFound(w, r)
return
}
slug = conn.MustGetText(r.Context(), "", "select edit_contact($1, $2, $3, $4, $5, $6, $7, $8, $9)", slug, form.Name, form.Phone, form.Email, form.Web, form.TaxDetails(), form.IBAN, form.BIC, form.Tags)
if slug == "" {
http.NotFound(w, r)
}
htmxRedirect(w, r, companyURI(mustGetCompany(r), "/contacts"))
}
type contactFilterForm struct {
Name *InputField
Tags *TagsField
TagsCondition *ToggleField
}
func newContactFilterForm(locale *Locale) *contactFilterForm {
return &contactFilterForm{
Name: &InputField{
Name: "number",
Label: pgettext("input", "Name", locale),
Type: "search",
},
Tags: &TagsField{
Name: "tags",
Label: pgettext("input", "Tags", locale),
},
TagsCondition: &ToggleField{
Name: "tags_condition",
Label: pgettext("input", "Tags Condition", locale),
Selected: "and",
FirstOption: &ToggleOption{
Value: "and",
Label: pgettext("tag condition", "All", locale),
Description: gettext("Invoices must have all the specified labels.", locale),
},
SecondOption: &ToggleOption{
Value: "or",
Label: pgettext("tag condition", "Any", locale),
Description: gettext("Invoices must have at least one of the specified labels.", locale),
},
},
}
}
func (form *contactFilterForm) Parse(r *http.Request) error {
if err := r.ParseForm(); err != nil {
return err
}
form.Name.FillValue(r)
form.Tags.FillValue(r)
form.TagsCondition.FillValue(r)
return nil
}
func (form *contactFilterForm) HasValue() bool {
return form.Name.HasValue() ||
form.Tags.HasValue()
}
func mustCollectContactEntries(ctx context.Context, conn *Conn, company *Company, filters *contactFilterForm) []*ContactEntry {
args := []interface{}{company.Id}
where := []string{"contact.company_id = $1"}
appendWhere := func(expression string, value interface{}) {
args = append(args, value)
where = append(where, fmt.Sprintf(expression, len(args)))
}
if filters != nil {
name := strings.TrimSpace(filters.Name.String())
if name != "" {
appendWhere("contact.name ilike $%d", "%"+name+"%")
}
if len(filters.Tags.Tags) > 0 {
if filters.TagsCondition.Selected == "and" {
appendWhere("contact.tags @> $%d", filters.Tags)
} else {
appendWhere("contact.tags && $%d", filters.Tags)
}
}
}
rows := conn.MustQuery(ctx, fmt.Sprintf(`
select slug
, name
, coalesce(email::text, '')
, coalesce(phone::text, '')
, tags
from contact
left join contact_email using (contact_id)
left join contact_phone using (contact_id)
where (%s)
order by name
`, strings.Join(where, ") AND (")), args...)
defer rows.Close()
var entries []*ContactEntry
for rows.Next() {
entry := &ContactEntry{}
if err := rows.Scan(&entry.Slug, &entry.Name, &entry.Email, &entry.Phone, &entry.Tags); err != nil {
panic(err)
}
entries = append(entries, entry)
}
if rows.Err() != nil {
panic(rows.Err())
}
return entries
}
type contactForm struct {
locale *Locale
Name *InputField
HasTaxDetails *CheckField
BusinessName *InputField
VATIN *InputField
Phone *InputField
Email *InputField
Web *InputField
Address *InputField
City *InputField
Province *InputField
PostalCode *InputField
Country *SelectField
IBAN *InputField
BIC *InputField
Tags *TagsField
}
func newContactForm(ctx context.Context, conn *Conn, locale *Locale) *contactForm {
return &contactForm{
locale: locale,
Name: &InputField{
Name: "name",
Label: pgettext("input", "Name", locale),
Type: "text",
Required: true,
},
Phone: &InputField{
Name: "phone",
Label: pgettext("input", "Phone", locale),
Type: "tel",
Attributes: []template.HTMLAttr{
`autocomplete="tel"`,
},
},
Email: &InputField{
Name: "email",
Label: pgettext("input", "Email", locale),
Type: "email",
Attributes: []template.HTMLAttr{
`autocomplete="email"`,
},
},
Web: &InputField{
Name: "web",
Label: pgettext("input", "Web", locale),
Type: "url",
Attributes: []template.HTMLAttr{
`autocomplete="url"`,
},
},
HasTaxDetails: &CheckField{
Name: "has_tax_details",
Label: pgettext("input", "Need to input tax details", locale),
},
BusinessName: &InputField{
Name: "business_name",
Label: pgettext("input", "Business name", locale),
Type: "text",
Required: true,
Attributes: []template.HTMLAttr{
`autocomplete="organization"`,
`minlength="2"`,
},
},
VATIN: &InputField{
Name: "vatin",
Label: pgettext("input", "VAT number", locale),
Type: "text",
Required: true,
},
Address: &InputField{
Name: "address",
Label: pgettext("input", "Address", locale),
Type: "text",
Required: true,
Attributes: []template.HTMLAttr{
`autocomplete="address-line1"`,
},
},
City: &InputField{
Name: "city",
Label: pgettext("input", "City", locale),
Type: "text",
Required: true,
},
Province: &InputField{
Name: "province",
Label: pgettext("input", "Province", locale),
Type: "text",
Required: true,
},
PostalCode: &InputField{
Name: "postal_code",
Label: pgettext("input", "Postal code", locale),
Type: "text",
Required: true,
Attributes: []template.HTMLAttr{
`autocomplete="postal-code"`,
},
},
Country: &SelectField{
Name: "country",
Label: pgettext("input", "Country", locale),
Options: mustGetCountryOptions(ctx, conn, locale),
Required: true,
Selected: []string{"ES"},
Attributes: []template.HTMLAttr{
`autocomplete="country"`,
},
},
IBAN: &InputField{
Name: "iban",
Label: pgettext("input", "IBAN", locale),
Type: "text",
},
BIC: &InputField{
Name: "bic",
Label: pgettext("bic", "BIC", locale),
Type: "text",
},
Tags: &TagsField{
Name: "tags",
Label: pgettext("input", "Tags", locale),
},
}
}
func (form *contactForm) Parse(r *http.Request) error {
if err := r.ParseForm(); err != nil {
return err
}
form.Name.FillValue(r)
form.HasTaxDetails.FillValue(r)
form.BusinessName.FillValue(r)
form.VATIN.FillValue(r)
form.Phone.FillValue(r)
form.Email.FillValue(r)
form.Web.FillValue(r)
form.Address.FillValue(r)
form.City.FillValue(r)
form.Province.FillValue(r)
form.PostalCode.FillValue(r)
form.Country.FillValue(r)
form.IBAN.FillValue(r)
form.BIC.FillValue(r)
form.Tags.FillValue(r)
return nil
}
func (form *contactForm) Validate(ctx context.Context, conn *Conn) bool {
validator := newFormValidator()
country := "ES"
if form.HasTaxDetails.Checked {
if validator.CheckValidSelectOption(form.Country, gettext("Selected country is not valid.", form.locale)) {
country = form.Country.Selected[0]
}
if validator.CheckRequiredInput(form.BusinessName, gettext("Business name can not be empty.", form.locale)) {
validator.CheckInputMinLength(form.BusinessName, 2, gettext("Business name must have at least two letters.", form.locale))
}
if validator.CheckRequiredInput(form.VATIN, gettext("VAT number can not be empty.", form.locale)) {
validator.CheckValidVATINInput(ctx, conn, form.VATIN, country, gettext("This value is not a valid VAT number.", form.locale))
}
validator.CheckRequiredInput(form.Address, gettext("Address can not be empty.", form.locale))
validator.CheckRequiredInput(form.City, gettext("City can not be empty.", form.locale))
validator.CheckRequiredInput(form.Province, gettext("Province can not be empty.", form.locale))
if validator.CheckRequiredInput(form.PostalCode, gettext("Postal code can not be empty.", form.locale)) {
validator.CheckValidPostalCode(ctx, conn, form.PostalCode, country, gettext("This value is not a valid postal code.", form.locale))
}
}
if validator.CheckRequiredInput(form.Name, gettext("Name can not be empty.", form.locale)) {
validator.CheckInputMinLength(form.Name, 2, gettext("Name must have at least two letters.", form.locale))
}
if form.Phone.Val != "" {
validator.CheckValidPhoneInput(ctx, conn, form.Phone, country, gettext("This value is not a valid phone number.", form.locale))
}
if form.Email.Val != "" {
validator.CheckValidEmailInput(form.Email, gettext("This value is not a valid email. It should be like name@domain.com.", form.locale))
}
if form.Web.Val != "" {
validator.CheckValidURL(form.Web, gettext("This value is not a valid web address. It should be like https://domain.com/.", form.locale))
}
if form.IBAN.Val != "" {
validator.CheckValidIBANInput(ctx, conn, form.IBAN, gettext("This values is not a valid IBAN.", form.locale))
}
if form.BIC.Val != "" {
validator.CheckValidBICInput(ctx, conn, form.BIC, gettext("This values is not a valid BIC.", form.locale))
}
return validator.AllOK()
}
func (form *contactForm) MustFillFromDatabase(ctx context.Context, conn *Conn, slug string) bool {
return !notFoundErrorOrPanic(conn.QueryRow(ctx, `
select name
, vatin is not null
, business_name
, substr(vatin::text, 3)
, phone
, email
, uri
, address
, city
, province
, postal_code
, country_code
, iban
, bic
, tags
from contact
left join contact_email using (contact_id)
left join contact_phone using (contact_id)
left join contact_web using (contact_id)
left join contact_iban using (contact_id)
left join contact_swift using (contact_id)
left join contact_tax_details using (contact_id)
where slug = $1
`, slug).Scan(
form.Name,
form.HasTaxDetails,
form.BusinessName,
form.VATIN,
form.Phone,
form.Email,
form.Web,
form.Address,
form.City,
form.Province,
form.PostalCode,
form.Country,
form.IBAN,
form.BIC,
form.Tags))
}
func (form *contactForm) TaxDetails() *CustomerTaxDetails {
if !form.HasTaxDetails.Checked {
return nil
}
return &CustomerTaxDetails{
BusinessName: form.BusinessName.String(),
VATIN: form.VATIN.String(),
Address: form.Address.String(),
City: form.City.String(),
Province: form.Province.String(),
PostalCode: form.PostalCode.String(),
CountryCode: form.Country.String(),
}
}
func ServeEditContactTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
serveTagsEditForm(w, r, params, "/contacts/", "select tags from contact where slug = $1")
}
func HandleUpdateContactTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
handleUpdateTags(w, r, params, "/contacts/", "update contact set tags = $1 where slug = $2 returning slug")
}
func ServeImportPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
form := newContactImportForm(getLocale(r), getCompany(r))
mustRenderMainTemplate(w, r, "contacts/import.gohtml", form)
}
type contactImportForm struct {
locale *Locale
company *Company
File *FileField
}
func newContactImportForm(locale *Locale, company *Company) *contactImportForm {
return &contactImportForm{
locale: locale,
company: company,
File: &FileField{
Name: "file",
Label: pgettext("input", "Holded Excel file", locale),
MaxSize: 1 << 20,
Required: true,
},
}
}
func (form *contactImportForm) Parse(r *http.Request) error {
if err := r.ParseMultipartForm(form.File.MaxSize); err != nil {
return err
}
if err := form.File.FillValue(r); err != nil {
return err
}
return nil
}
func HandleImportContacts(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
locale := getLocale(r)
company := mustGetCompany(r)
form := newContactImportForm(locale, company)
if err := form.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := verifyCsrfTokenValid(r); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
workbook, err := xlsx.OpenBinary(form.File.Content)
if err != nil {
panic(err)
}
conn := getConn(r)
tx := conn.MustBegin(r.Context())
defer tx.MustRollback(r.Context())
relation := tx.MustGetText(r.Context(), "select begin_import_contacts()")
columns := []string{"name", "vatin", "email", "phone", "address", "city", "postal_code", "province", "country_code", "iban", "bic", "tags"}
for _, sheet := range workbook.Sheets {
tx.MustCopyFrom(r.Context(), relation, columns, len(sheet.Rows)-4, func(idx int) ([]interface{}, error) {
row := sheet.Rows[idx+4]
var values []interface{}
if len(row.Cells) < 23 {
values = []interface{}{"", "", "", "", "", "", "", "", "", "", "", ""}
} else {
phone := row.Cells[5].String() // mobile
if phone == "" {
phone = row.Cells[4].String() // landline
}
values = []interface{}{
row.Cells[1].String(),
row.Cells[2].String(),
row.Cells[3].String(),
phone,
row.Cells[6].String(),
row.Cells[7].String(),
row.Cells[8].String(),
row.Cells[9].String(),
row.Cells[11].String(),
row.Cells[19].String(),
row.Cells[20].String(),
row.Cells[22].String(),
}
}
return values, nil
})
}
tx.MustExec(r.Context(), "select end_import_contacts($1)", company.Id)
tx.MustCommit(r.Context())
htmxRedirect(w, r, companyURI(company, "/contacts"))
}