numerus/pkg/expenses.go

468 lines
14 KiB
Go
Raw Normal View History

2023-05-03 10:46:25 +00:00
package pkg
import (
"context"
"fmt"
"github.com/julienschmidt/httprouter"
"html/template"
"math"
"net/http"
2023-05-07 20:49:52 +00:00
"strconv"
"strings"
2023-05-03 10:46:25 +00:00
"time"
)
type ExpenseEntry struct {
Slug string
InvoiceDate time.Time
InvoiceNumber string
Amount string
InvoicerName string
OriginalFileName string
Tags []string
2023-05-03 10:46:25 +00:00
}
type expensesIndexPage struct {
Expenses []*ExpenseEntry
TotalAmount string
Filters *expenseFilterForm
2023-05-03 10:46:25 +00:00
}
func IndexExpenses(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
conn := getConn(r)
2023-05-07 20:49:52 +00:00
locale := getLocale(r)
2023-05-03 10:46:25 +00:00
company := mustGetCompany(r)
2023-05-07 20:49:52 +00:00
filters := newExpenseFilterForm(r.Context(), conn, locale, company)
if err := filters.Parse(r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
2023-05-03 10:46:25 +00:00
page := &expensesIndexPage{
Expenses: mustCollectExpenseEntries(r.Context(), conn, company, filters),
TotalAmount: mustComputeExpensesTotalAmount(r.Context(), conn, filters),
Filters: filters,
2023-05-03 10:46:25 +00:00
}
mustRenderMainTemplate(w, r, "expenses/index.gohtml", page)
}
2023-05-07 20:49:52 +00:00
func mustCollectExpenseEntries(ctx context.Context, conn *Conn, company *Company, filters *expenseFilterForm) []*ExpenseEntry {
where, args := filters.BuildQuery(nil)
2023-05-07 20:49:52 +00:00
rows := conn.MustQuery(ctx, fmt.Sprintf(`
2023-05-03 10:46:25 +00:00
select expense.slug
, invoice_date
, invoice_number
, to_price(amount, decimal_digits)
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
, contact.name
, coalesce(attachment.original_filename, '')
2023-05-03 10:46:25 +00:00
, expense.tags
from expense
left join expense_attachment as attachment using (expense_id)
2023-05-03 10:46:25 +00:00
join contact using (contact_id)
join currency using (currency_code)
2023-05-07 20:49:52 +00:00
where (%s)
2023-05-03 10:46:25 +00:00
order by invoice_date
`, where), args...)
2023-05-03 10:46:25 +00:00
defer rows.Close()
var entries []*ExpenseEntry
for rows.Next() {
entry := &ExpenseEntry{}
if err := rows.Scan(&entry.Slug, &entry.InvoiceDate, &entry.InvoiceNumber, &entry.Amount, &entry.InvoicerName, &entry.OriginalFileName, &entry.Tags); err != nil {
2023-05-03 10:46:25 +00:00
panic(err)
}
entries = append(entries, entry)
}
if rows.Err() != nil {
panic(rows.Err())
}
return entries
}
func mustComputeExpensesTotalAmount(ctx context.Context, conn *Conn, filters *expenseFilterForm) string {
where, args := filters.BuildQuery(nil)
return conn.MustGetText(ctx, "0", fmt.Sprintf(`
select to_price(sum(amount)::integer, decimal_digits)
from expense
join currency using (currency_code)
where (%s)
group by decimal_digits
`, where), args...)
}
2023-05-03 10:46:25 +00:00
func ServeExpenseForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
locale := getLocale(r)
conn := getConn(r)
company := mustGetCompany(r)
form := newExpenseForm(r.Context(), conn, locale, company)
slug := params[0].Value
if slug == "new" {
w.WriteHeader(http.StatusOK)
form.InvoiceDate.Val = time.Now().Format("2006-01-02")
mustRenderNewExpenseForm(w, r, form)
return
}
if !form.MustFillFromDatabase(r.Context(), conn, slug) {
http.NotFound(w, r)
return
}
w.WriteHeader(http.StatusOK)
mustRenderEditExpenseForm(w, r, slug, form)
}
func mustRenderNewExpenseForm(w http.ResponseWriter, r *http.Request, form *expenseForm) {
locale := getLocale(r)
form.Invoicer.EmptyLabel = gettext("Select a contact.", locale)
mustRenderMainTemplate(w, r, "expenses/new.gohtml", form)
}
func mustRenderEditExpenseForm(w http.ResponseWriter, r *http.Request, slug string, form *expenseForm) {
page := &editExpensePage{
Slug: slug,
Form: form,
}
mustRenderMainTemplate(w, r, "expenses/edit.gohtml", page)
}
type editExpensePage struct {
Slug string
Form *expenseForm
}
type expenseForm struct {
locale *Locale
company *Company
Invoicer *SelectField
InvoiceNumber *InputField
InvoiceDate *InputField
Tax *SelectField
Amount *InputField
File *FileField
2023-05-03 10:46:25 +00:00
Tags *TagsField
}
func newExpenseForm(ctx context.Context, conn *Conn, locale *Locale, company *Company) *expenseForm {
return &expenseForm{
locale: locale,
company: company,
Invoicer: &SelectField{
Name: "invoicer",
Label: pgettext("input", "Contact", locale),
Required: true,
Options: mustGetContactOptions(ctx, conn, company),
},
InvoiceNumber: &InputField{
Name: "invoice_number",
Label: pgettext("input", "Invoice number", locale),
Type: "text",
},
InvoiceDate: &InputField{
Name: "invoice_date",
Label: pgettext("input", "Invoice Date", locale),
Required: true,
Type: "date",
},
Tax: &SelectField{
Name: "tax",
Label: pgettext("input", "Taxes", locale),
Multiple: true,
Options: mustGetTaxOptions(ctx, conn, company),
},
Amount: &InputField{
Name: "amount",
Label: pgettext("input", "Amount", locale),
Type: "number",
Required: true,
Attributes: []template.HTMLAttr{
`min="0"`,
template.HTMLAttr(fmt.Sprintf(`step="%v"`, company.MinCents())),
},
},
File: &FileField{
Name: "file",
Label: pgettext("input", "File", locale),
MaxSize: 1 << 20,
},
2023-05-03 10:46:25 +00:00
Tags: &TagsField{
Name: "tags",
Label: pgettext("input", "Tags", locale),
},
}
}
func (form *expenseForm) Parse(r *http.Request) error {
if err := r.ParseMultipartForm(form.File.MaxSize); err != nil {
2023-05-03 10:46:25 +00:00
return err
}
form.Invoicer.FillValue(r)
form.InvoiceNumber.FillValue(r)
form.InvoiceDate.FillValue(r)
form.Tax.FillValue(r)
form.Amount.FillValue(r)
if err := form.File.FillValue(r); err != nil {
return err
}
2023-05-03 10:46:25 +00:00
form.Tags.FillValue(r)
return nil
}
func (form *expenseForm) Validate() bool {
validator := newFormValidator()
validator.CheckValidSelectOption(form.Invoicer, gettext("Selected contact is not valid.", form.locale))
validator.CheckValidDate(form.InvoiceDate, gettext("Invoice date must be a valid date.", form.locale))
validator.CheckValidSelectOption(form.Tax, gettext("Selected tax is not valid.", form.locale))
validator.CheckAtMostOneOfEachGroup(form.Tax, gettext("You can only select a tax of each class.", form.locale))
if validator.CheckRequiredInput(form.Amount, gettext("Amount can not be empty.", form.locale)) {
validator.CheckValidDecimal(form.Amount, form.company.MinCents(), math.MaxFloat64, gettext("Amount must be a number greater than zero.", form.locale))
}
validator.CheckValidSelectOption(form.Tax, gettext("Selected tax is not valid.", form.locale))
validator.CheckAtMostOneOfEachGroup(form.Tax, gettext("You can only select a tax of each class.", form.locale))
return validator.AllOK()
}
func (form *expenseForm) MustFillFromDatabase(ctx context.Context, conn *Conn, slug string) bool {
return !notFoundErrorOrPanic(conn.QueryRow(ctx, `
select contact_id
, invoice_number
, invoice_date
, to_price(amount, decimal_digits)
, array_agg(tax_id)
, tags
2023-05-03 10:46:25 +00:00
from expense
left join expense_tax using (expense_id)
join currency using (currency_code)
where expense.slug = $1
group by contact_id
, invoice_number
, invoice_date
, amount
, decimal_digits
, tags
`, slug).Scan(
form.Invoicer,
form.InvoiceNumber,
form.InvoiceDate,
form.Amount,
form.Tax,
form.Tags))
}
func HandleAddExpense(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
company := mustGetCompany(r)
form := newExpenseForm(r.Context(), conn, 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
}
if !form.Validate() {
if !IsHTMxRequest(r) {
w.WriteHeader(http.StatusUnprocessableEntity)
}
mustRenderNewExpenseForm(w, r, form)
return
}
taxes := mustSliceAtoi(form.Tax.Selected)
slug := conn.MustGetText(r.Context(), "", "select add_expense($1, $2, $3, $4, $5, $6, $7)", company.Id, form.InvoiceDate, form.Invoicer, form.InvoiceNumber, form.Amount, taxes, form.Tags)
if len(form.File.Content) > 0 {
conn.MustQuery(r.Context(), "select attach_to_expense($1, $2, $3, $4)", slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content)
}
2023-05-03 10:46:25 +00:00
htmxRedirect(w, r, companyURI(company, "/expenses"))
}
func HandleUpdateExpense(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
company := mustGetCompany(r)
form := newExpenseForm(r.Context(), conn, 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
}
slug := params[0].Value
if !form.Validate() {
if !IsHTMxRequest(r) {
w.WriteHeader(http.StatusUnprocessableEntity)
}
mustRenderEditExpenseForm(w, r, slug, form)
return
}
taxes := mustSliceAtoi(form.Tax.Selected)
if found := conn.MustGetText(r.Context(), "", "select edit_expense($1, $2, $3, $4, $5, $6, $7)", slug, form.InvoiceDate, form.Invoicer, form.InvoiceNumber, form.Amount, taxes, form.Tags); found == "" {
http.NotFound(w, r)
return
}
if len(form.File.Content) > 0 {
conn.MustQuery(r.Context(), "select attach_to_expense($1, $2, $3, $4)", slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content)
}
htmxRedirect(w, r, companyURI(company, "/expenses"))
}
2023-05-07 20:49:52 +00:00
type expenseFilterForm struct {
locale *Locale
company *Company
Contact *SelectField
2023-05-07 20:49:52 +00:00
InvoiceNumber *InputField
FromDate *InputField
ToDate *InputField
Tags *TagsField
TagsCondition *ToggleField
}
func newExpenseFilterForm(ctx context.Context, conn *Conn, locale *Locale, company *Company) *expenseFilterForm {
return &expenseFilterForm{
locale: locale,
company: company,
Contact: &SelectField{
Name: "contact",
Label: pgettext("input", "Contact", locale),
EmptyLabel: gettext("All contacts", locale),
2023-05-07 20:49:52 +00:00
Options: mustGetContactOptions(ctx, conn, company),
},
InvoiceNumber: &InputField{
Name: "number",
Label: pgettext("input", "Invoice Number", locale),
Type: "search",
},
FromDate: &InputField{
Name: "from_date",
Label: pgettext("input", "From Date", locale),
Type: "date",
},
ToDate: &InputField{
Name: "to_date",
Label: pgettext("input", "To Date", locale),
Type: "date",
},
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 *expenseFilterForm) Parse(r *http.Request) error {
if err := r.ParseForm(); err != nil {
return err
}
form.Contact.FillValue(r)
2023-05-07 20:49:52 +00:00
form.InvoiceNumber.FillValue(r)
form.FromDate.FillValue(r)
form.ToDate.FillValue(r)
form.Tags.FillValue(r)
form.TagsCondition.FillValue(r)
return nil
}
2023-05-08 10:58:54 +00:00
func (form *expenseFilterForm) BuildQuery(args []interface{}) (string, []interface{}) {
var where []string
appendWhere := func(expression string, value interface{}) {
args = append(args, value)
where = append(where, fmt.Sprintf(expression, len(args)))
}
maybeAppendWhere := func(expression string, value string, conv func(string) interface{}) {
if value != "" {
if conv == nil {
appendWhere(expression, value)
} else {
appendWhere(expression, conv(value))
}
}
}
appendWhere("expense.company_id = $%d", form.company.Id)
maybeAppendWhere("contact_id = $%d", form.Contact.String(), func(v string) interface{} {
customerId, _ := strconv.Atoi(form.Contact.Selected[0])
return customerId
})
maybeAppendWhere("invoice_number = $%d", form.InvoiceNumber.String(), nil)
maybeAppendWhere("invoice_date >= $%d", form.FromDate.String(), nil)
maybeAppendWhere("invoice_date <= $%d", form.ToDate.String(), nil)
if len(form.Tags.Tags) > 0 {
if form.TagsCondition.Selected == "and" {
appendWhere("expense.tags @> $%d", form.Tags)
} else {
appendWhere("expense.tags && $%d", form.Tags)
}
}
return strings.Join(where, ") AND ("), args
}
2023-05-08 10:58:54 +00:00
func ServeEditExpenseTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
company := getCompany(r)
slug := params[0].Value
form := newTagsForm(companyURI(company, "/expenses/"+slug+"/tags"), slug, locale)
if notFoundErrorOrPanic(conn.QueryRow(r.Context(), `select tags from expense where slug = $1`, form.Slug).Scan(form.Tags)) {
2023-05-08 10:58:54 +00:00
http.NotFound(w, r)
return
}
mustRenderStandaloneTemplate(w, r, "tags/edit.gohtml", form)
}
func HandleUpdateExpenseTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
locale := getLocale(r)
conn := getConn(r)
company := getCompany(r)
slug := params[0].Value
form := newTagsForm(companyURI(company, "/expenses/"+slug+"/tags/edit"), slug, 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 conn.MustGetText(r.Context(), "", "update expense set tags = $1 where slug = $2 returning slug", form.Tags, form.Slug) == "" {
http.NotFound(w, r)
}
mustRenderStandaloneTemplate(w, r, "tags/view.gohtml", form)
}
func ServeExpenseAttachment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
slug := params[0].Value
conn := getConn(r)
var contentType string
var content []byte
if notFoundErrorOrPanic(conn.QueryRow(r.Context(), `
select mime_type
, content
from expense
join expense_attachment using (expense_id)
where slug = $1
`, slug).Scan(&contentType, &content)) {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(int64(len(content)), 10))
w.WriteHeader(http.StatusOK)
w.Write(content)
}