numerus/pkg/payments.go

740 lines
23 KiB
Go

package pkg
import (
"context"
"fmt"
"github.com/julienschmidt/httprouter"
"html/template"
"math"
"net/http"
"time"
)
const (
PaymentTypePayment = "P"
PaymentTypeCollection = "C"
)
func servePaymentIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
conn := getConn(r)
company := mustGetCompany(r)
locale := getLocale(r)
page := NewPaymentIndexPage(r.Context(), conn, company, locale)
page.MustRender(w, r)
}
func serveExpensePaymentIndex(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
expenseSlug := params[0].Value
conn := getConn(r)
company := mustGetCompany(r)
locale := getLocale(r)
expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug)
if expense == nil {
http.NotFound(w, r)
return
}
page := NewPaymentIndexPageForExpense(r.Context(), conn, company, locale, expense)
page.MustRender(w, r)
}
func serveInvoiceCollectionIndex(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
invoiceSlug := params[0].Value
conn := getConn(r)
company := mustGetCompany(r)
locale := getLocale(r)
invoice := mustGetCollectionInvoice(r.Context(), conn, invoiceSlug)
if invoice == nil {
http.NotFound(w, r)
return
}
page := NewPaymentIndexPageForInvoice(r.Context(), conn, company, locale, invoice)
page.MustRender(w, r)
}
type PaymentIndexPage struct {
Payments []*PaymentEntry
BaseURI string
Expense *PaymentExpense
Invoice *CollectionInvoice
}
func NewPaymentIndexPage(ctx context.Context, conn *Conn, company *Company, locale *Locale) *PaymentIndexPage {
return &PaymentIndexPage{
Payments: mustCollectPaymentEntries(ctx, conn, company, locale, "", 0),
BaseURI: companyURI(company, "/payments"),
}
}
func NewPaymentIndexPageForExpense(ctx context.Context, conn *Conn, company *Company, locale *Locale, expense *PaymentExpense) *PaymentIndexPage {
return &PaymentIndexPage{
Payments: mustCollectPaymentEntries(ctx, conn, company, locale, PaymentTypePayment, expense.Id),
BaseURI: expense.BaseURI(company),
Expense: expense,
}
}
func NewPaymentIndexPageForInvoice(ctx context.Context, conn *Conn, company *Company, locale *Locale, invoice *CollectionInvoice) *PaymentIndexPage {
return &PaymentIndexPage{
Payments: mustCollectPaymentEntries(ctx, conn, company, locale, PaymentTypeCollection, invoice.Id),
BaseURI: invoice.BaseURI(company),
Invoice: invoice,
}
}
func (page *PaymentIndexPage) MustRender(w http.ResponseWriter, r *http.Request) {
mustRenderMainTemplate(w, r, "payments/index.gohtml", page)
}
type PaymentExpense struct {
Id int
Slug string
InvoiceNumber string
}
func mustGetPaymentExpense(ctx context.Context, conn *Conn, expenseSlug string) *PaymentExpense {
if !ValidUuid(expenseSlug) {
return nil
}
expense := &PaymentExpense{}
if notFoundErrorOrPanic(conn.QueryRow(ctx, `
select expense_id
, slug
, coalesce(nullif(invoice_number, ''), slug::text)
from expense
where expense.slug = $1
`, expenseSlug).Scan(
&expense.Id,
&expense.Slug,
&expense.InvoiceNumber)) {
return nil
}
return expense
}
func (expense *PaymentExpense) BaseURI(company *Company) string {
return companyURI(company, "/expenses/"+expense.Slug+"/payments")
}
func (expense *PaymentExpense) calcRemainingPaymentAmount(ctx context.Context, conn *Conn) string {
return conn.MustGetText(ctx, "", `
select to_price(greatest(0, expense.amount + tax_amount - paid_amount)::int, decimal_digits)
from (
select coalesce (sum(payment.amount), 0) as paid_amount
from expense_payment
join payment using (payment_id)
where expense_payment.expense_id = $1
) as payment
cross join (
select coalesce (sum(amount), 0) as tax_amount
from expense_tax_amount
where expense_id = $1
) as tax
cross join (
select amount, decimal_digits
from expense
join currency using (currency_code)
where expense_id = $1
) as expense
`, expense.Id)
}
type CollectionInvoice struct {
Id int
Slug string
InvoiceNumber string
}
func mustGetCollectionInvoice(ctx context.Context, conn *Conn, invoiceSlug string) *CollectionInvoice {
if !ValidUuid(invoiceSlug) {
return nil
}
invoice := &CollectionInvoice{}
if notFoundErrorOrPanic(conn.QueryRow(ctx, `
select invoice_id
, slug
, invoice_number
from invoice
where invoice.slug = $1
`, invoiceSlug).Scan(
&invoice.Id,
&invoice.Slug,
&invoice.InvoiceNumber)) {
return nil
}
return invoice
}
func (invoice *CollectionInvoice) BaseURI(company *Company) string {
return companyURI(company, "/invoices/"+invoice.Slug+"/collections")
}
func (invoice *CollectionInvoice) calcRemainingPaymentAmount(ctx context.Context, conn *Conn) string {
return conn.MustGetText(ctx, "", `
select to_price(greatest(0, invoice_amount.total - collected_amount)::int, decimal_digits)
from (
select coalesce (sum(collection.amount), 0) as collected_amount
from invoice_collection
join collection using (collection_id)
where invoice_collection.invoice_id = $1
) as collection
cross join (
select total
, decimal_digits
from invoice_amount
join invoice using (invoice_id)
join currency using (currency_code)
where invoice_id = $1
) as invoice_amount
`, invoice.Id)
}
type PaymentEntry struct {
ID int
Type string
Slug string
PaymentDate time.Time
Description string
DocumentSlug string
InvoiceNumber string
Total string
OriginalFileName string
Tags []string
Status string
StatusLabel string
}
func mustCollectPaymentEntries(ctx context.Context, conn *Conn, company *Company, locale *Locale, paymentType string, documentId int) []*PaymentEntry {
rows := conn.MustQuery(ctx, `
select $5 as type
, 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, '')
, coalesce(expense.slug::text, '')
, coalesce(expense.invoice_number, '')
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)
left join expense_payment using (payment_id)
left join expense using (expense_id)
where payment.company_id = $2
and ($3 = '' or ($3 = $5 and expense_id = $4))
union all
select $6 as type
, collection_id
, collection.slug
, collection_date as payment_date
, description
, to_price(collection.amount, decimal_digits) as total
, collection.tags
, collection.payment_status
, psi18n.name
, coalesce(attachment.original_filename, '')
, coalesce(invoice.slug::text, '')
, coalesce(invoice.invoice_number, '')
from collection
join payment_status_i18n psi18n on collection.payment_status = psi18n.payment_status and psi18n.lang_tag = $1
join currency using (currency_code)
left join collection_attachment as attachment using (collection_id)
left join invoice_collection using (collection_id)
left join invoice using (invoice_id)
where collection.company_id = $2
and ($3 = '' or ($3 = $6 and invoice_id = $4))
order by payment_date desc, total desc
`, locale.Language, company.Id, paymentType, documentId, PaymentTypePayment, PaymentTypeCollection)
defer rows.Close()
var entries []*PaymentEntry
for rows.Next() {
entry := &PaymentEntry{}
if err := rows.Scan(&entry.Type, &entry.ID, &entry.Slug, &entry.PaymentDate, &entry.Description, &entry.Total, &entry.Tags, &entry.Status, &entry.StatusLabel, &entry.OriginalFileName, &entry.DocumentSlug, &entry.InvoiceNumber); 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)
}
func serveExpensePaymentForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
locale := getLocale(r)
conn := getConn(r)
company := mustGetCompany(r)
expenseSlug := params[0].Value
expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug)
if expense == nil {
http.NotFound(w, r)
return
}
form := newPaymentFormForExpense(r.Context(), conn, locale, company, expense)
paymentSlug := params[1].Value
if paymentSlug == "new" {
form.PaymentDate.Val = time.Now().Format("2006-01-02")
form.Description.Val = fmt.Sprintf(gettext("Payment of %s", locale), form.Expense.InvoiceNumber)
form.Amount.Val = form.Expense.calcRemainingPaymentAmount(r.Context(), conn)
form.MustRender(w, r)
return
}
if !ValidUuid(paymentSlug) {
http.NotFound(w, r)
return
}
if !form.MustFillFromDatabase(r.Context(), conn, paymentSlug) {
http.NotFound(w, r)
return
}
form.MustRender(w, r)
}
func serveInvoiceCollectionForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
locale := getLocale(r)
conn := getConn(r)
company := mustGetCompany(r)
invoiceSlug := params[0].Value
invoice := mustGetCollectionInvoice(r.Context(), conn, invoiceSlug)
if invoice == nil {
http.NotFound(w, r)
return
}
form := newPaymentFormForInvoice(r.Context(), conn, locale, company, invoice)
paymentSlug := params[1].Value
if paymentSlug == "new" {
form.PaymentDate.Val = time.Now().Format("2006-01-02")
form.Description.Val = fmt.Sprintf(gettext("Collection of %s", locale), form.Invoice.InvoiceNumber)
form.Amount.Val = form.Invoice.calcRemainingPaymentAmount(r.Context(), conn)
form.MustRender(w, r)
return
}
if !ValidUuid(paymentSlug) {
http.NotFound(w, r)
return
}
if !form.MustFillFromDatabase(r.Context(), conn, paymentSlug) {
http.NotFound(w, r)
return
}
form.MustRender(w, r)
}
type PaymentForm struct {
locale *Locale
company *Company
Slug string
BaseURI string
Expense *PaymentExpense
Invoice *CollectionInvoice
Type *SelectField
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,
BaseURI: companyURI(company, "/payments"),
Type: &SelectField{
Name: "type",
Label: pgettext("input", "Type", locale),
Required: true,
Options: []*SelectOption{
{Value: PaymentTypePayment, Label: pgettext("payment type", "Payment", locale)},
{Value: PaymentTypeCollection, Label: pgettext("payment type", "Collection", locale)},
},
},
Description: &InputField{
Name: "description",
Label: pgettext("input", "Description", locale),
Required: true,
Type: "text",
},
PaymentDate: &InputField{
Name: "payment_date",
Label: pgettext("input", "Payment 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 where company_id = $1 order by name", company.Id),
},
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 newPaymentFormForExpense(ctx context.Context, conn *Conn, locale *Locale, company *Company, expense *PaymentExpense) *PaymentForm {
form := newPaymentForm(ctx, conn, locale, company)
form.Type.Selected = []string{PaymentTypePayment}
form.BaseURI = expense.BaseURI(company)
form.Expense = expense
return form
}
func newPaymentFormForInvoice(ctx context.Context, conn *Conn, locale *Locale, company *Company, invoice *CollectionInvoice) *PaymentForm {
form := newPaymentForm(ctx, conn, locale, company)
form.Type.Selected = []string{PaymentTypeCollection}
form.BaseURI = invoice.BaseURI(company)
form.Invoice = invoice
return form
}
func (f *PaymentForm) MustRender(w http.ResponseWriter, r *http.Request) {
if f.Slug == "" {
f.Type.EmptyLabel = gettext("Select a type.", f.locale)
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 {
selectedType := f.Type.Selected
selectedPaymentAccount := f.PaymentAccount.Selected
f.PaymentAccount.Clear()
if notFoundErrorOrPanic(conn.QueryRow(ctx, `
select $2 as type
, description
, payment_date
, payment_account_id::text
, to_price(amount, decimal_digits)
, tags
from payment
join currency using (currency_code)
where payment.slug = $1
union all
select $3 as type
, description
, collection_date
, payment_account_id::text
, to_price(amount, decimal_digits)
, tags
from collection
join currency using (currency_code)
where collection.slug = $1
`, slug, PaymentTypePayment, PaymentTypeCollection).Scan(
f.Type,
f.Description,
f.PaymentDate,
f.PaymentAccount,
f.Amount,
f.Tags)) {
f.Type.Selected = selectedType
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.Type.FillValue(r)
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.CheckValidSelectOption(f.Type, gettext("Selected payment type is not valid.", f.locale))
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)
handleAddPaymentForm(w, r, conn, company, form)
}
func handleAddPaymentForm(w http.ResponseWriter, r *http.Request, conn *Conn, company *Company, form *PaymentForm) {
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() {
w.WriteHeader(http.StatusUnprocessableEntity)
form.MustRender(w, r)
return
}
var documentId any
if form.Type.String() == PaymentTypePayment {
if form.Expense != nil {
documentId = form.Expense.Id
}
slug := conn.MustGetText(r.Context(), "", "select add_payment($1, $2, $3, $4, $5, $6, $7)", company.Id, documentId, 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)
}
} else {
if form.Invoice != nil {
documentId = form.Invoice.Id
}
slug := conn.MustGetText(r.Context(), "", "select add_collection($1, $2, $3, $4, $5, $6, $7)", company.Id, documentId, form.PaymentDate, form.PaymentAccount, form.Description, form.Amount, form.Tags)
if len(form.File.Content) > 0 {
conn.MustQuery(r.Context(), "select attach_to_collection($1, $2, $3, $4)", slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content)
}
}
htmxRedirect(w, r, form.BaseURI)
}
func handleAddExpensePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
expenseSlug := params[0].Value
locale := getLocale(r)
conn := getConn(r)
company := mustGetCompany(r)
expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug)
if expense == nil {
http.NotFound(w, r)
return
}
form := newPaymentFormForExpense(r.Context(), conn, locale, company, expense)
handleAddPaymentForm(w, r, conn, company, form)
}
func handleAddInvoiceCollection(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
invoiceSlug := params[0].Value
locale := getLocale(r)
conn := getConn(r)
company := mustGetCompany(r)
invoice := mustGetCollectionInvoice(r.Context(), conn, invoiceSlug)
if invoice == nil {
http.NotFound(w, r)
return
}
form := newPaymentFormForInvoice(r.Context(), conn, locale, company, invoice)
handleAddPaymentForm(w, r, conn, company, form)
}
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
handleEditPaymentForm(w, r, conn, form)
}
func handleEditPaymentForm(w http.ResponseWriter, r *http.Request, conn *Conn, form *PaymentForm) {
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() {
w.WriteHeader(http.StatusUnprocessableEntity)
form.MustRender(w, r)
return
}
if form.Type.String() == PaymentTypePayment {
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)
}
} else {
if found := conn.MustGetText(r.Context(), "", "select edit_collection($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_collection($1, $2, $3, $4)", form.Slug, form.File.OriginalFileName, form.File.ContentType, form.File.Content)
}
}
htmxRedirect(w, r, form.BaseURI)
}
func handleEditExpensePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
company := mustGetCompany(r)
expenseSlug := params[0].Value
expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug)
if expense == nil {
http.NotFound(w, r)
return
}
form := newPaymentFormForExpense(r.Context(), conn, locale, company, expense)
form.Slug = params[1].Value
handleEditPaymentForm(w, r, conn, form)
}
func handleEditInvoiceCollection(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
locale := getLocale(r)
company := mustGetCompany(r)
invoiceSlug := params[0].Value
invoice := mustGetCollectionInvoice(r.Context(), conn, invoiceSlug)
if invoice == nil {
http.NotFound(w, r)
return
}
form := newPaymentFormForInvoice(r.Context(), conn, locale, company, invoice)
form.Slug = params[1].Value
handleEditPaymentForm(w, r, conn, form)
}
func handleRemovePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
company := mustGetCompany(r)
removePayment(w, r, params[0].Value, companyURI(company, "/payments"))
}
func removePayment(w http.ResponseWriter, r *http.Request, slug string, backURI string) {
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), remove_collection($1)", slug)
htmxRedirect(w, r, backURI)
}
func handleRemoveExpensePayment(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
expenseSlug := params[0].Value
expense := mustGetPaymentExpense(r.Context(), conn, expenseSlug)
if expense == nil {
http.NotFound(w, r)
return
}
company := mustGetCompany(r)
removePayment(w, r, params[1].Value, expense.BaseURI(company))
}
func handleRemoveInvoiceCollection(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
conn := getConn(r)
invoiceSlug := params[0].Value
invoice := mustGetCollectionInvoice(r.Context(), conn, invoiceSlug)
if invoice == nil {
http.NotFound(w, r)
return
}
company := mustGetCompany(r)
removePayment(w, r, params[1].Value, invoice.BaseURI(company))
}
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
union all
select mime_type
, content
from collection
join collection_attachment using (collection_id)
where slug = $1
`)
}
func servePaymentTagsEditForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
serveTagsEditForm(w, r, params, "/payments/", "select tags from payment where slug = $1 union all select tags from collection where slug = $1")
}
func handleUpdatePaymentTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
handleUpdateTags(w, r, params, "/payments/", "with p as (update payment set tags = $1 where slug = $2 returning slug), c as (update collection set tags = $1 where slug = $2 returning slug) select p.slug from p union all select c.slug from c")
}