numerus/pkg/payments.go

309 lines
8.7 KiB
Go

package pkg
import (
"context"
"fmt"
"github.com/julienschmidt/httprouter"
"html/template"
"math"
"net/http"
"time"
)
func servePaymentIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
page := NewPaymentIndexPage(r.Context(), conn, locale)
page.MustRender(w, r)
}
type PaymentIndexPage struct {
Payments []*PaymentEntry
}
func NewPaymentIndexPage(ctx context.Context, conn *Conn, locale *Locale) *PaymentIndexPage {
return &PaymentIndexPage{
Payments: mustCollectPaymentEntries(ctx, conn, locale),
}
}
func (page *PaymentIndexPage) MustRender(w http.ResponseWriter, r *http.Request) {
mustRenderMainTemplate(w, r, "payments/index.gohtml", page)
}
type PaymentEntry struct {
ID int
Slug string
PaymentDate time.Time
Description string
Total string
OriginalFileName string
Tags []string
Status string
StatusLabel string
}
func mustCollectPaymentEntries(ctx context.Context, conn *Conn, locale *Locale) []*PaymentEntry {
rows := conn.MustQuery(ctx, `
select payment_id
, payment.slug
, payment_date
, description
, to_price(payment.amount, decimal_digits) as total
, payment.tags
, payment.payment_status
, psi18n.name
, coalesce(attachment.original_filename, '')
from payment
join payment_status_i18n psi18n on payment.payment_status = psi18n.payment_status and psi18n.lang_tag = $1
join currency using (currency_code)
left join payment_attachment as attachment using (payment_id)
order by payment_date desc, total desc
`, locale.Language)
defer rows.Close()
var entries []*PaymentEntry
for rows.Next() {
entry := &PaymentEntry{}
if err := rows.Scan(&entry.ID, &entry.Slug, &entry.PaymentDate, &entry.Description, &entry.Total, &entry.Tags, &entry.Status, &entry.StatusLabel, &entry.OriginalFileName); err != nil {
panic(err)
}
entries = append(entries, entry)
}
if rows.Err() != nil {
panic(rows.Err())
}
return entries
}
func servePaymentForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
locale := getLocale(r)
conn := getConn(r)
company := mustGetCompany(r)
form := newPaymentForm(r.Context(), conn, locale, company)
slug := params[0].Value
if slug == "new" {
form.PaymentDate.Val = time.Now().Format("2006-01-02")
form.MustRender(w, r)
return
}
if !ValidUuid(slug) {
http.NotFound(w, r)
return
}
if !form.MustFillFromDatabase(r.Context(), conn, slug) {
http.NotFound(w, r)
return
}
form.MustRender(w, r)
}
type PaymentForm struct {
locale *Locale
company *Company
Slug string
Description *InputField
PaymentDate *InputField
PaymentAccount *SelectField
Amount *InputField
File *FileField
Tags *TagsField
}
func newPaymentForm(ctx context.Context, conn *Conn, locale *Locale, company *Company) *PaymentForm {
return &PaymentForm{
locale: locale,
company: company,
Description: &InputField{
Name: "description",
Label: pgettext("input", "Description", locale),
Required: true,
Type: "text",
},
PaymentDate: &InputField{
Name: "payment_date",
Label: pgettext("input", "Invoice Date", locale),
Required: true,
Type: "date",
},
PaymentAccount: &SelectField{
Name: "payment_account",
Label: pgettext("input", "Account", locale),
Required: true,
Options: MustGetOptions(ctx, conn, "select payment_account_id::text, name from payment_account order by name"),
},
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,
},
Tags: &TagsField{
Name: "tags",
Label: pgettext("input", "Tags", locale),
},
}
}
func (f *PaymentForm) MustRender(w http.ResponseWriter, r *http.Request) {
if f.Slug == "" {
f.PaymentAccount.EmptyLabel = gettext("Select an account.", f.locale)
mustRenderMainTemplate(w, r, "payments/new.gohtml", f)
} else {
mustRenderMainTemplate(w, r, "payments/edit.gohtml", f)
}
}
func (f *PaymentForm) MustFillFromDatabase(ctx context.Context, conn *Conn, slug string) bool {
selectedPaymentAccount := f.PaymentAccount.Selected
f.PaymentAccount.Clear()
if notFoundErrorOrPanic(conn.QueryRow(ctx, `
select description
, payment_date
, payment_account_id::text
, to_price(amount, decimal_digits)
, tags
from payment
join currency using (currency_code)
where payment.slug = $1
`, slug).Scan(
f.Description,
f.PaymentDate,
f.PaymentAccount,
f.Amount,
f.Tags)) {
f.PaymentAccount.Selected = selectedPaymentAccount
return false
}
f.Slug = slug
return true
}
func (f *PaymentForm) Parse(r *http.Request) error {
if err := r.ParseMultipartForm(f.File.MaxSize); err != nil {
return err
}
f.Description.FillValue(r)
f.PaymentDate.FillValue(r)
f.PaymentAccount.FillValue(r)
f.Amount.FillValue(r)
if err := f.File.FillValue(r); err != nil {
return err
}
f.Tags.FillValue(r)
return nil
}
func (f *PaymentForm) Validate() bool {
validator := newFormValidator()
validator.CheckRequiredInput(f.Description, gettext("Description can not be empty.", f.locale))
validator.CheckValidSelectOption(f.PaymentAccount, gettext("Selected payment account is not valid.", f.locale))
validator.CheckValidDate(f.PaymentDate, gettext("Payment date must be a valid date.", f.locale))
if validator.CheckRequiredInput(f.Amount, gettext("Amount can not be empty.", f.locale)) {
validator.CheckValidDecimal(f.Amount, f.company.MinCents(), math.MaxFloat64, gettext("Amount must be a number greater than zero.", f.locale))
}
return validator.AllOK()
}
func handleAddPayment(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
locale := getLocale(r)
conn := getConn(r)
company := mustGetCompany(r)
form := newPaymentForm(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)
}
form.MustRender(w, r)
return
}
slug := conn.MustGetText(r.Context(), "", "select add_payment($1, $2, $3, $4, $5, $6, $7)", company.Id, nil, form.PaymentDate, form.PaymentAccount, form.Description, form.Amount, form.Tags)
if len(form.File.Content) > 0 {
conn.MustQuery(r.Context(), "select attach_to_payment($1, $2, $3, $4)", slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content)
}
htmxRedirect(w, r, companyURI(company, "/payments"))
}
func handleEditPayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
company := mustGetCompany(r)
form := newPaymentForm(r.Context(), conn, locale, company)
form.Slug = params[0].Value
if !ValidUuid(form.Slug) {
http.NotFound(w, r)
return
}
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)
}
form.MustRender(w, r)
return
}
if found := conn.MustGetText(r.Context(), "", "select edit_payment($1, $2, $3, $4, $5, $6)", form.Slug, form.PaymentDate, form.PaymentAccount, form.Description, form.Amount, form.Tags); found == "" {
http.NotFound(w, r)
return
}
if len(form.File.Content) > 0 {
conn.MustQuery(r.Context(), "select attach_to_payment($1, $2, $3, $4)", form.Slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content)
}
htmxRedirect(w, r, companyURI(company, "/payments"))
}
func handleRemovePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
slug := params[0].Value
if !ValidUuid(slug) {
http.NotFound(w, r)
return
}
if err := verifyCsrfTokenValid(r); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
conn := getConn(r)
conn.MustExec(r.Context(), "select remove_payment($1)", slug)
company := mustGetCompany(r)
htmxRedirect(w, r, companyURI(company, "/payments"))
}
func servePaymentAttachment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
serveAttachment(w, r, params, `
select mime_type
, content
from payment
join payment_attachment using (payment_id)
where slug = $1
`)
}